def doctor_add(request): if request.method == "POST": name = request.POST["name"] address = request.POST["address"] speciality = request.POST["speciality"] locator = geopy.Nominatim(user_agent='myGeocoder') location = locator.geocode(address) lat = location.latitude long_ = location.longitude doc_obj = Doctor.objects.create(name=name, address=address, speciality=speciality, latitude=lat, longitude=long_) doc_obj.save() return redirect("index") return render(request, template_name="doctor_add.html")
def main(): geolocator = geopy.Nominatim(user_agent="weighted-geo-center") data = pd.DataFrame(columns=["address", "weight"]) count = int(input("How many addresses do you want to enter? ")) for i in range(0, count): data.at[i, "address"] = input(f"Enter address #{i + 1}: ") data.at[i, "weight"] = float( input(f"Enter weight for address #{i + 1}: ")) print("\nData Input:\n", data) for i, row in data.iterrows(): data.at[i, "lat"], data.at[i, "lng"] = get_coordinates( geolocator, row["address"]) time.sleep(WAIT_BETWEEN_REQUESTS) print("\nData w/ Geo Coordinates:\n", data) geo_center = calc_weighted_center(data) print("") print(f"The weighted geographic center is: {geo_center}") print( f"Open in Google Maps: http://www.google.com/maps/place/{geo_center[0]},{geo_center[1]}" )
def updateShop(request): user = CustomUser.objects.get(email=request.user) locator = geopy.Nominatim(user_agent="myGeocoder") form = CustomShopChangeForm(instance=user) if request.method == 'POST': form = CustomShopChangeForm(request.POST,request.FILES, instance=user) # location = locator.geocode(address) if form.is_valid(): data = request.POST.copy() address = data.get('street') + ' ' + data.get('zip_code') + ' ' + data.get('city_name') location = locator.geocode(address) #Imagename = request.FILES['user_Main_Img'].name # replace the longitude latitude information form_new = form.save(commit=False) form_new.longitude = location.longitude form_new.latitude = location.latitude form_new.group_membership = '3' if form.is_valid() and 'user_Main_Img' in request.FILES: Imagename = request.FILES['user_Main_Img'].name form_new.userImg_Url = Imagename form_new.save() return redirect('/') else: form_new.save() return redirect('/') else: form = CustomShopChangeForm(request.POST, instance=user) context = {'form': form} return render(request, 'users/updateShop.html', {'form': form})
def generate_friends_data(friends_dict: dict) -> list: ''' Get dictionary with info about friends from twitter, geocode their coordinates, and return tuple with them and nickname. ''' geolocator = geopy.Nominatim(user_agent='my-aplication') geocode = RateLimiter(geolocator.geocode, min_delay_seconds=1) result = [] used_locations = [] for user in friends_dict: try: location = geolocator.geocode(user['location']) coordinates = [location.latitude, location.longitude] if coordinates in used_locations: coordinates[0] += random.randrange(1, 2) / 10000 coordinates[1] += random.randrange(1, 2) / 10000 used_locations.append(coordinates) result.append( (user['screen_name'], coordinates[0], coordinates[1])) except: continue return result
def GetCoors(): dataFrame = pandas.read_csv("zips.csv") geoLocator = geopy.Nominatim(user_agent="*****@*****.**") geoCode = RateLimiter(geoLocator.geocode, min_delay_seconds=3) output = {} for zipCode in dataFrame.values: zipCode = str(zipCode[0]).strip() if '-' in zipCode: zipCode = zipCode[0:zipCode.index('-')] res = geoCode(zipCode + ", United States of America") if res != None: if zipCode in output: output[zipCode]["Count"] = output[zipCode]["Count"] + 1 else: output[zipCode] = {} output[zipCode]["Count"] = 1 output[zipCode]["Latitude"] = res.latitude output[zipCode]["Longitude"] = res.longitude print("Processing %s" % zipCode) with open("coors.json", "w") as f: json.dump(output, f) return output
def find_closest_films(year, location): """ (int),(tuple) -> (set) Function get a year of a film, user location, and filters 10 closest film. """ film_dict = get_film_year_and_location(read_file()) closest_film_lst = [] geolocator = geopy.Nominatim(user_agent="myGeolocator", timeout=10) if year in film_dict: while film_dict[year] and len(closest_film_lst) < 50: try: film = film_dict[year].pop() film_loc_obj = geolocator.geocode(film[1]) film_loc = film_loc_obj.latitude, film_loc_obj.longitude closest_film_lst.append((film[0], film_loc)) except: continue else: return None closest_film_lst.sort(key=lambda elm: abs(elm[1][0] - location[0]) + abs( elm[1][1] - location[1])) closest_film_set = set(closest_film_lst[0:10]) return closest_film_set
def add_coords(filtered_lst): """ Find coordinates for list of films """ for line in filtered_lst: try: location = line[2] location = location.split(", ") geolocator = geopy.Nominatim(user_agent="main.py") geocode = RateLimiter(geolocator.geocode, min_delay_seconds=0.05) adres = geolocator.geocode(location) if adres == None: location = location[1:] adres = geolocator.geocode(location) if adres == None: location = location[1:] adres = geolocator.geocode(location) coords = (float(adres.latitude), float(adres.longitude)) line.append(coords) except GeocoderUnavailable: line.append("error") return filtered_lst
def form_valid(self, form): """ Verify form and save object """ self.object = form.save(commit=False) lat = self.object.latitude lng = self.object.longitude # Use Geocoding to find address geolocator = gp.Nominatim(user_agent='CovidClusteringLocator') address = geolocator.reverse(str(lat) + ", " + str(lng)) self.object.address = address.address raw_dict = address.raw # Try to find the name of the municipality in the address possible_names = ["town", "village", "municipality"] for name in possible_names: if name in raw_dict["address"]: self.object.municipality = raw_dict["address"][name] break else: self.object.municipality = "Unknown" self.object.save() return redirect('map_clusters')
def generate_bounding_box(address1, address2): ''' Generate a bounding box determined by two addresses. This bounding box is a determinant for all street info that is pulled from the OSM database. Only streets located within the bounding box will be fetched. -------------------------------------------------------------------------------------------- The bounding box is generated as such: - The bounding box area includes both addresses, plus a 1 kilometre buffer area surrounding them. - It is determined by 4 latitude longitude coordinates; one for each side of the box. ''' #Geolocator to convert address to longitude / latitude locations. geolocator = geopy.Nominatim() location1 = geolocator.geocode(address1) location2 = geolocator.geocode(address2) #North, south, east, west bounds for the bounding box. north = max(location1.latitude, location2.latitude) #Northern-most point. south = min(location1.latitude, location2.latitude) #Southern-most point. east = max(location1.longitude, location2.longitude) #East-most point. west = min(location1.longitude, location2.longitude) #West-most point. #Add approximately 1 km of distance to each parameter of the bounding box. #(1 kilometer is converted to longitude/latitude degrees) north = north + (1 / 111.321543) south = south - (1 / 111.321543) east = east + abs((1 / (math.cos(east) * 111.321543))) west = west - abs((1 / (math.cos(east) * 111.321543))) #Return the bounding box coordinates. return north, south, east, west
def process(rdd): try: #process the rdd tweets = list(rdd) for tweet in tweets: lat = None lon = None # print(tweet.get('text').encode("ascii", "ignore")) tweet_text = tweet.get('text').encode("ascii", "ignore") df = pd.DataFrame({'text': str(tweet_text)}, index=[0]) # print(pd_df) acc = ml_model.pipeline(df) loc = tweet.get('user').get('location') # print(loc) if loc is not None: locator = geopy.Nominatim(user_agent="MyGeocoder") location = locator.geocode(loc) lat = location.latitude lon = location.longitude # print("location points " + str(location.latitude) + ", " + str(location.longitude)) data = { "tweet": tweet_text, "location": { "lat": lat, "lon": lon }, "analysis": acc } print(data) if lat is not None and acc == 'YES': print("sending data to kibana") send_loc_to_es(data) except Exception as e: # print(e) pass
def __init__(self, mongoDB): self.mongoDB = mongoDB self.elevation_url = 'http://localhost:8081/api/v1/lookup' ctx = ssl.create_default_context(cafile=certifi.where()) geopy.geocoders.options.default_ssl_context = ctx self.geo_locator = geopy.Nominatim(user_agent='address', timeout=None)
def get_polygon_city(cityName, country): """ Ask an API for the coordinates that circle a city Parameters ---------- str : cityName Name of the city str : country name of the country Returns ------- list(tuple(coordinates)): a list of coordinates """ geolocator = geopy.Nominatim(user_agent="monAppTwitter") location = geolocator.geocode(cityName + "," + country) osm_id = location.raw["osm_id"] #Turin : 44880 #Grenoble : 80348 #Annecy : 102480 page = urllib.request.urlopen( 'http://polygons.openstreetmap.fr/get_geojson.py?id=' + str(osm_id) + '¶ms=0') cityCoords = json.loads(str( page.read())[2:-3])["geometries"][0]["coordinates"][0][0] return cityCoords
def run_example(): # students = data_generator.generate_students() # print(students[145]) # student = Student(first_name="Mikołaj", last_name="Lewandowski") # print(student.grades_avg) geo_locator = geopy.Nominatim()
def convert_to_coordinates(self): address = u'%s %s' % (self.city, self.address) try: locator = geopy.Nominatim(user_agent="myGeocoder") location = locator.geocode(address) except (ValueError): pass return location
def cargar_ubicacion(): import geopy from geopy.geocoders import Nominatim geolocator = geopy.Nominatim(user_agent="specify_your_app_name_here") print("\nIngrese su dirección actual") print("Ej: Avenida Corrientes 600, Buenos Aires\n") direccion = geolocator.geocode(input("Direccion: ")) latitud = direccion.latitude longitud = direccion.longitude return latitud, longitud
def get_preference_details_as_list(self): geolocator = geopy.Nominatim(user_agent="intern-buddy") geoLocation1 = geolocator.geocode(self.preferences.location) coordinate1 = (geoLocation1.latitude, geoLocation1.longitude) hangout_outside = 1 if self.preferences.hangout_outside else 0 return [ coordinate1[0], coordinate1[1], self.preferences.group_size, self.preferences.school_level, hangout_outside, self.preferences.position_type ]
def convert_city_to_geoloc(data, city_col): geoloc_df = pd.DataFrame() geoloc_df["yeshuv"] = data[city_col].unique() geoloc_df.dropna(axis=0, how='any', inplace=True) locator = geopy.Nominatim(country_bias='Israel', user_agent="myGeocoder", timeout=4) geocode = RateLimiter(locator.geocode, min_delay_seconds=1.5) # delay between geocoding calls, pre-requisite of API geoloc_df['location'] = geoloc_df['yeshuv'].apply(geocode) # create location column geoloc_df['point'] = geoloc_df['location'].apply(lambda loc: tuple( loc.point) if loc else None) # create longitude, laatitude and altitude from location column (returns tuple) return geoloc_df
def convert_city_to_geoloc_multithreading(data, city_col): geoloc_df = pd.DataFrame() geoloc_df["Yeshuv"] = data[city_col].unique() geoloc_df.dropna(axis=0, how='any', inplace=True) geoloc_list = geoloc_df["Yeshuv"].to_list() locator = geopy.Nominatim(country_bias='Israel', user_agent="myGeocoder", timeout=4) geocode_rate_limited = RateLimiter(locator.geocode, min_delay_seconds=1.5) # delay between geocoding calls, pre-requisite of API pool = multiprocessing.Pool(processes=1) # multiprocessing.cpu_count() gives 12 CPUs addresses = pool.map(geocode_rate_limited, geoloc_list) return addresses
def location_to_coords(location): """ (str) -> (tuple) Function to get coordinates from a location recursively, in case GeoPy raises an error """ geolocator = geopy.Nominatim(user_agent="myGeolocator", timeout=10) user_location_obj = geolocator.geocode(location) if user_location_obj is not None: return user_location_obj.latitude, user_location_obj.longitude
def getgeo(): while True: try: geolocator = geopy.Nominatim() #location = geolocator.geocode(raw_input("Enter a location: \n")) # hard code location for testing location = geolocator.geocode("market street san francisco") break except: print "Connection to geolocator timed out. Trying again.." time.sleep(3) return location
def make_map(di): ''' dictionary -> None A function creating a map with 3 layers ''' mapp = folium.Map(zoom_start=6) fg1 = folium.FeatureGroup(name="Locations") fg2 = folium.FeatureGroup(name="Movies") fg3 = folium.FeatureGroup(name="Area") for key in di: tn = geopy.Nominatim(timeout=3).geocode(key) try: lt = tn.latitude ln = tn.longitude fg1.add_child( folium.CircleMarker(location=[lt, ln], radius=10, popup=key, color='red', fill_opacity=0.5)) name = '' for e in di[key]: y = ' '.join(e) if "'" in y: y = y.replace("'", "*") name += y name += ', ' fg2.add_child( folium.Marker(location=[lt, ln], popup=name[:-2], icon=folium.Icon())) fg3.add_child( folium.GeoJson( data=open('world.json', 'r', encoding='utf-8-sig').read(), style_function=lambda x: { 'fillColor': 'white' if x['properties']['AREA'] < 1000 else 'blue' if 1000 <= x['properties']['AREA'] < 100000 else 'green' if 100000 <= x['properties'][ 'AREA'] < 1000000 else 'purple' })) except AttributeError: continue mapp.add_child(fg1) mapp.add_child(fg2) mapp.add_child(fg3) mapp.add_child(folium.LayerControl()) mapp.save("Map_movies.html")
def resolve_address(address): ''' Attempt to resolve a given address. This is done by determining if it can be found by geolocator. If the address cannot be resolved then an AttributeError exception will be thrown. ''' #Geolocator object geolocator = geopy.Nominatim() #Throws error if address not resolved: #Obtain full addresses from geolocator. #The replacement is just to remove the comma after street number for more standard appearance. full_address = geolocator.geocode(address).address.replace(",","",1) return full_address
def convert_lon_lat(df): locator = geopy.Nominatim(user_agent="myGeocoder") # convenient function to delay between geocoding calls geocode = RateLimiter(locator.geocode, min_delay_seconds=1) df['location'] = df['ADDRESS'].apply(geocode) # 3 - create longitude, latitude and altitude from location column (returns tuple) df['point'] = df['location'].apply(lambda loc: tuple(loc.point) if loc else None) df[['latitude', 'longitude', 'altitude']] = pd.DataFrame(df['point'].tolist(), index=df.index) return df
def github_job_locations(cursor: sqlite3.Cursor, data): geolocator = geopy.Nominatim(user_agent="api_jobs.py") for item in data: location = geolocator.geocode(item["location"]) if location == "remote" or location == "Remote" or location is None or location.longitude is None \ or location.latitude is None: continue job_location = item["location"] job_title = item["title"] company_name = item["company"] latitude = location.latitude longitude = location.longitude cursor.execute(f'''INSERT INTO JobLocations(title, location, company, latitude, longitude) VALUES (?,?,?,?,?) ''', (job_title, job_location, company_name, latitude, longitude))
def get_user_country(user_location): """(str) -> (str) Return a country from a user coordinates """ geo_locator = geopy.Nominatim(user_agent="User Location", timeout=10) location = geo_locator.reverse(user_location, language='en') location = str(location).split(', ') country = location[-1] if country == 'United States of America': country = 'USA' elif country == 'United Kingdom': country = 'UK' return country
def address_to_coordinates(address): """ Parameters: -- address: Dictionary of the addresses from the order list taken out of woocomerce """ visits = {} # Set the address of your vehicle(s) adress_depot = "Post-Passage 9, 4051 Basel" locator = geopy.Nominatim(user_agent="myGeocoder") location = locator.geocode(adress_depot) fleet = { "vehicle_1": { "start_location": { "id": "depot", "name": "alte Post", "lat": location.latitude, "lng": location.longitude } }, } # Extract the coordinates (lat, long) by geocode from addresses and print if # address can not be found as the routific is a demo file i cannot be larger # than 8 for i, key in enumerate(address.keys()): if i > 1600: print("[WARNING]\tToo many orders") continue name = address[key]["name"] adresse = address[key]["address"] + ", " + address[key][ "postcode"] + ", " + address[key]["city"] location = locator.geocode(adresse) if not location: print("[WARNING]\t", adresse, "does not exist") continue lat = location.latitude long = location.longitude visits[key] = {"location": {"name": name, "lat": lat, "lng": long}} # To not overload the server time.sleep(0.1) # Put together address of vehicles (fleet) and visitis of customer into one # dictionary data = {"visits": visits, "fleet": fleet} return data
def processTweets(listTweets): processed_tweets = [] if not listTweets: return None for tweet in listTweets: if tweet['user location']: locator = geopy.Nominatim(user_agent='myGeocoder') cities = ['sydney', 'melbourne', 'brisbane'] found = False for city in cities: if re.search(city, tweet['user location'].lower()): processed_tweets.append(tweet) found = True break if found: continue if tweet['user location'].lower( ) == 'australia' or tweet['user location'].lower() == 'aus': continue try: location = locator.geocode(tweet['user location'], viewbox=[(-10.5, 110.99), (-44.43, 157.87)]) except GeocoderTimedOut as e: print("Geocoder TimedOut... sleeping 5") sleep(5) continue except GeocoderUnavailable as e: print("Geocoder Unavailable.... sleeping 5") sleep(5) except Exception as e: print('caught geocode error') print(e) continue if not location: continue point = Point(location.latitude, location.longitude) coords = [(-11, 112), (-11, 154), (-44, 112), (-44, 154)] poly = Polygon(coords) if poly.contains(point): processed_tweets.append(tweet) return processed_tweets
def stackoverflow_job_locations(cursor: sqlite3.Cursor, stackjobsdata): geolocator = geopy.Nominatim(user_agent="api_jobs.py") debug_count = 0 for job in stackjobsdata: cities = GeoText(job.title) debug_count = debug_count + 1 print(debug_count) location = geolocator.geocode(cities.cities, timeout=15) if location == "remote" or location == "Remote" or location is None: continue else: word = location.address worddiv = word.split(', ') cursor.execute( f'''INSERT INTO JobLocations(title, location, company, latitude, longitude) VALUES (?,?,?,?,?) ''', (job.title, worddiv[0], job.author, location.latitude, location.longitude))
def get_film_coordinates(film_dict): """(dict) -> (dict) Return a dictionary of coordinates of films :param film_dict: (dict) = {location(str): {film(str), ...}, ...) :return: (dict) = {coordinates(tuple)(int): {film(str), ...}, ...) """ coordinate_dict = dict() for location in film_dict.keys(): try: locator = geopy.Nominatim(user_agent="filmGeocoder", timeout=10) coordinates = locator.geocode(location) coordinate_dict[coordinates.latitude, coordinates.longitude] = film_dict[location] except (TypeError, AttributeError, IndexError): continue return coordinate_dict
def __init__(self, data_folder="data", terms_folder="terms"): self.cache = shelve.open(os.path.join(data_folder, "cache.db")) self.terms_db = TermsDB(terms_folder) # Coords limits for geolocation # bot left top right self.limits = (-47, -24.05, -46.30, -23.35) self.regions = None self.osm = geopy.Nominatim(view_box=self.limits) self.gm = geopy.GoogleV3() self.server_options = { "osm": self.geocode_osm, "gm": self.geocode_gm, } self.shapefy_regions( os.path.join(data_folder, "subprefeituras.geojson"))