def get_location_data(lat, lon): # Nominatim takes combined lat and lon in one argument input_location = str(lat + ', ' + lon) # user_agent can be any email address geolocator = Nominatim(user_agent="*****@*****.**") # actual call to get location data location = geolocator.reverse(input_location) # the location includes a ton of data - getting the raw data to provide # more generic information address = location.raw['address'] display_location = ", ".join([ address.get('city', ''), address.get('state', ''), address.get('country', '') ]) # timezone processing requires lat and lon to be separate floats, though latitude, longitude = float(lat), float(lon) tz = pytz.timezone(TimezoneFinder().timezone_at(lng=longitude, lat=latitude)) return display_location, tz
def coordi(message): if message.text == 'Get location': x = round(uniform(51.262, 56.172), 4) y = round(uniform(23.178, 32.777), 4) x, y = str(x), str(y) coord = '{},{}'.format(x, y) geolocator = Nominatim(user_agent='geobot') location = geolocator.reverse(coord) r = location.raw adr = r.get('address') cc = adr.get('country_code') loc = location.address dist = distance.distance(MINSK, coord) dist = str(dist) dist = dist.split(' ') dist = round(float(dist[0]), 2) dist = 'Distance between Minsk and this place: {} km.\nIf you want to know distance between you and this place ' \ 'send your location to bot'.format(dist) link = 'https://www.google.com/maps/place/{}'.format(coord) if cc == 'by': place.clear() place.append(coord) bot.send_message(message.chat.id, "Why don't you go to:\n{}".format(loc)) bot.send_message(message.chat.id, link) bot.send_message(message.chat.id, dist) else: print('None BY') coordi(message)
def create(self, validated_data): print(validated_data) geolocator = Nominatim() # location_id = int(validated_data.pop('location_id', None)) lng = validated_data.pop('lng', None) lat = validated_data.pop('lat', None) street_address = validated_data.pop('street_address', None) #owner_id = int(validated_data.pop('user_id', None)) if lat > 0: location = geolocator.reverse("{}, {}".format(lng, lat)) street_address = location.address street_address = street_address.split(', ')[0] + ", " + street_address.split(', ')[1] print(street_address) else: location = geolocator.geocode(street_address) lat = location.latitude lng = location.longitude data = {'lat': lat, 'lng': lng, 'street_address': street_address} location = Location.objects.create(**data) # limitations_serializer = LimitationSerializer(data={'authority_id':10,'reason':'smth','location_id':location._get_pk_val()}, many=True) # print(limitations_serializer.initial_data) # # if limitations_serializer.is_valid(): # # print(1) # limitations = limitations_serializer.save() # print(limitations) # else: # print(limitations_serializer.errors) # #limitations_data = self.context.get('view').request.FILES # print(limitations.__dir__) return location
def recover_adress(df, year): locator = Nominatim(user_agent="myGeocoder") address_dict = {} add = [] for latitude, longitude in df[df["address_known"] == False][[ "latitude", "longitude" ]].itertuples(index=False): if not math.isnan(latitude): add.append((latitude, longitude)) add = set(add) with tqdm(total=len(add)) as bar: for latitude, longitude in add: bar.set_description( f"processing addresses lat={str(latitude)}, lon={longitude}") try: addresse = str(latitude) + ", " + str(longitude) address_dict[(latitude, longitude)] = locator.reverse(addresse) except Exception as e: print( "Could not find addresse for coordinates ", str(latitude), str(longitude), e, ) bar.update(1) for k, v in address_dict.items(): try: address_dict[k] = v.raw except: print("There was an issue with:", k, v) with open(f"address_{year}.pickle", "wb") as f: pickle.dump(address_dict, f) return address_dict
def getAlpha2Countries(self): geolocator = Nominatim(timeout=60) for location in self.locations: geo = geolocator.geocode(location) if geo is not None: loc = geolocator.reverse("{}, {}".format( geo.latitude, geo.longitude)) self.alpha2Countries.append( loc.raw['address']['country_code'].upper())
def get_city_on_coord(lat, lon): geolocator = Nominatim(user_agent='test/1') location = geolocator.reverse(f'{lat},{lon}', language='en') loc_dict = location.raw if 'city' in loc_dict['address'].keys(): return loc_dict['address']['city'] else: return loc_dict['address']['municipality']
def coordi(message): if message.text == 'Куда отправиться?': # случайные координаты в приблизительных границах Беларуси lon = round(uniform(51.262, 56.172), 4) lat = round(uniform(23.178, 32.777), 4) lon, lat = str(lon), str(lat) coord = '{},{}'.format(lon, lat) geolocator = Nominatim(user_agent='geobot') location = geolocator.reverse( coord) # получаем место на карте по координатам r = location.raw # получаем json adr = r.get('address') # из json берем адрес cc = adr.get('country_code') # из адреса берем код страны if cc == 'by': place.clear() loc = location.address # строка с человекочитаемым адресом place.append(coord) # переписываем значение координат места place.append(loc) dist = distance.distance( MINSK, coord) # вычисление расстояния между Минском и адресом dist = str(dist) dist = dist.split(' ') dist = round(float(dist[0]), 2) # округленное значение расстояния dist = 'Растояние от Октябрьской площади Минска до этого места: {} km.\nЧто бы узнать расстояние от ' \ 'твоего местонахождения до {} пришли боту свою геолокацию или проложи свой маршрут с ' \ 'использованием одного из сервисов'.format(dist, loc.split(',')[0]) links.clear() links.append( 'Это место на картах Google":\nhttps://www.google.com/maps/place/{}' .format(coord)) links.append( 'Это место на картах Yandex:\nhttps://yandex.com/maps/?text={}' .format(coord)) links.append( 'Это место на картах архитектурного наследия Беларуси:\nhttps://orda.of.by/.map/?{}' .format(coord)) links.append( 'Это место на картах MapsMe:\nmaps.google.com/{}'.format( coord)) keyboard = telebot.types.InlineKeyboardMarkup() key_ya = telebot.types.InlineKeyboardButton(text='Yandex', callback_data='ya') key_gg = telebot.types.InlineKeyboardButton(text='Google', callback_data='gg') key_globus = telebot.types.InlineKeyboardButton( text='карты Globus.tut.by', callback_data='globus') key_maps = telebot.types.InlineKeyboardButton( text='приложение Maps.me', callback_data='maps') keyboard.add(key_ya, key_gg) keyboard.add(key_globus, key_maps) bot.send_message(message.chat.id, "Почему бы сегодня не отправится:\n{}".format( loc)) #.split(',')[0])) bot.send_message(message.chat.id, dist, reply_markup=keyboard) else: print('None BY') coordi(message)
def get_content(lon=None, lat=None): log.info(f"Pharmacy map creator started [{lon}][{lat}]") locator = Nominatim(user_agent='bot') radius = 1000 # read full dataset raw = requests.get( "http://overpass-api.de/api/interpreter?data=<query type='node'><around lat='" + str(lat) + "' lon='" + str(lon) + "' radius='" + str(radius) + "'/></query><print/>").text data = BeautifulSoup(raw, features='xml') pharmacies = data.find_all('tag', {'k': 'amenity', 'v': 'pharmacy'}) address = pd.Series([ locator.reverse((pharmacy.parent['lat'], pharmacy.parent['lon']), timeout=10000).address for pharmacy in pharmacies ], dtype=str) latitude = pd.Series([pharmacy.parent['lat'] for pharmacy in pharmacies], dtype=float) longitude = pd.Series([pharmacy.parent['lon'] for pharmacy in pharmacies], dtype=float) data = pd.DataFrame({ 'address': address, 'latitude': latitude, 'longitude': longitude }) data['distance'] = data.apply(lambda row: geopy.distance.distance( (row['latitude'], row['longitude']), (lat, lon)).km, axis=1) # getting area borders min_lat = data['latitude'].min() max_lat = data['latitude'].max() min_lon = data['longitude'].min() max_lon = data['longitude'].max() data = data.sort_values(by=['distance']) message = f"Ближайшие аптеки в радиусе {radius} метров \r\n \r\n" for index, point in data.head(min(10, len(data))).iterrows(): message += f"⚕ [{round(point['distance'], 2)} км] {point['address']} \r\n" return map_extension.save_plot(log, data, min_lat, max_lat, min_lon, max_lon, pt_color='#00EB62FF', pt_size=1000, user_lat=lat, user_lon=lon), message
def set_city(df): geolocator = Nominatim(user_agent = 'test_1') cor = (df['lat'],df['lon']) location = geolocator.reverse(cor) address = location.raw['address'] df['address'] = address try: df['city'] = address['city'] except KeyError: df['city'] = "Null" return df
def country(self, obj): """returns the country of the last recorded location for driver""" longitude = obj.live_location_longitude latitude = obj.live_location_latitude geolocator = Nominatim() try: location = geolocator.reverse("{}, {}".format(longitude, latitude), language='en') return location.raw.get('address', {}).get('country', '') except Exception: return ''
def get_geo_node(lat, lon): geolocator = Nominatim(user_agent="pieters-data-gatherer", timeout=2) geo_name = "%.6f, %.6f" % (lat, lon) location = geolocator.reverse(geo_name).raw address = location.get('address') geo = GeoCoordinate.get_or_create({ "name": geo_name, "lat": lat, "lon": lon })[0] if address is not None and 'house_number' in address: country = Country.get_or_create({'name': address['country']})[0] states = country.states.filter(name=address['state']).all() if len(states) > 0: state = states[0] else: state = State(name=address['state']).save() country.states.connect(state) town_name = dict_get_first(address, ['town', 'city', 'village']) towns = state.towns.filter(name=town_name).all() if len(towns) > 0: town = towns[0] else: town = Town(name=town_name).save() state.towns.connect(town) road_name = dict_get_first( address, ['road', 'footway', 'pedestrian', 'cycleway', 'path']) roads = town.roads.filter(name=road_name).all() if len(roads) > 0: road = roads[0] else: try: road = Road(name=road_name).save() town.roads.connect(road) except: print(road_name) house_numbers = road.house_numbers.filter( name=address['house_number']).all() if len(house_numbers) > 0: house_number = house_numbers[0] else: house_number = HouseNumber(name=address['house_number']).save() road.house_numbers.connect(house_number) house_number.geos.connect(geo) return geo
def doAction(self,r,sr,words,sensorList): os.system("espeak -s 120 'searching'") lastFix = sensorList['location'].getLastData() if lastFix["lastFix"] == None: return "I don't know where you are" if("how high up" in words or "altitude" in words): return "you are " + str(int(float(lastFix["lastFix"]["alt"]))) + " meters up." geoloc = Nominatim() coor = str(lastFix["lastFix"]['lat'])+", "+str(lastFix["lastFix"]['lon']) loc = geoloc.reverse(coor,timeout=10) loc1 = loc.address.split(", ") del loc1[-4:] return "you are at " + str(loc1)
def add_country_and_city(sender, **kwargs): """The receiver called before a user address is saved to get the country and city from location coordinates""" address = kwargs['instance'] longitude = address.location_longitude latitude = address.location_latitude geolocator = Nominatim() try: location = geolocator.reverse("{}, {}".format(longitude, latitude), language='en') address.country = location.raw.get('address', {}).get('country', '') address.city = location.raw.get('address', {}).get( 'state', '') or location.raw.get('address', {}).get('city', '') except GeocoderTimedOut: return add_country_and_city(sender, **kwargs) # recursion except Exception: pass
def doAction(self,r,sr,words,sensorList): if "how's the weather in" in words: location = words.split("how's the weather in")[-1].strip(" ") else: os.system("espeak -s 120 'searching'") lastFix = sensorList['location'].getLastData() if lastFix["lastFix"] == None: return "I don't know where you are" geoloc = Nominatim() coor = str(lastFix["lastFix"]['lat'])+", "+str(lastFix["lastFix"]['lon']) loc = geoloc.reverse(coor,timeout=10) loc1 = loc.address location = loc1.split(", ")[-2] location = pywapi.get_location_ids(location) if len(location) == 0: return "location not found" locationId = next (iter (location.keys())) w = pywapi.get_weather_from_weather_com(locationId, units="imperial") return "It is " + w["current_conditions"]["temperature"] + "degrees and " + w["current_conditions"]["text"]
def nearby(current_user_position=None): cordinat = request.args.get('data') geolocator = Nominatim(user_agent="jual_ikan") location = geolocator.reverse(cordinat) get_json_value = location.raw get_state_name = get_json_value['address']['state'] # current_user_position = get_state_name current_user_position = 'Sumatera Selatan' urutan_ikan_dalam_tampilan_halamanerr = db.session.query( Ikan.id_ikan, Ikan.nama_ikan, Ikan.berat_ikan_dalam_Kg, Ikan.foto_ikan, Penjual).join(Penjual).filter( Penjual.domisili == current_user_position) return render_template("nearby_places.html", IKANS=urutan_ikan_dalam_tampilan_halamanerr, STATE=get_state_name)
def transform_zip(next_crime_raw): geolocator = Nominatim() location = geolocator.reverse(str(str(next_crime_raw['lat']) + ", " + str(next_crime_raw['lon']))) zip = location.raw['address']['postcode'] location = geolocator.geocode(str(zip)) boundingbox = location.raw['boundingbox'] maxlat = float(boundingbox[1]) minlat = float(boundingbox[0]) maxlng = float(boundingbox[3]) minlng = float(boundingbox[2]) meanlat = (maxlat + minlat) / 2 meanlng = (maxlng + minlng) / 2 try: zip = re.search('^787d{2}$', zip).group(1) print('zip: ' + str(zip)) except Exception: pass return Zip(zip_code=zip, lat=meanlat, lng=meanlng, pop=20000, family_income=50000)
def get_location(self, latitude, longitude): # Nominatim takes combined lat and lon in one argument input_location = str(latitude + ', ' + longitude) # user_agent can be any email address geolocator = Nominatim(user_agent="*****@*****.**") # actual call to get location data location = geolocator.reverse(input_location) # the location includes a ton of data - getting the raw data to provide # more generic information address = location.raw['address'] address_list = [ address.get('city', ''), address.get('state', ''), address.get('country', '') ] display_location = ", ".join(filter(None, address_list)) return display_location
def coordi(message): if message.text == 'Get location': x = round(uniform(51.262, 56.172), 4) y = round(uniform(23.178, 32.777), 4) x, y = str(x), str(y) coord = '{},{}'.format(x, y) geolocator = Nominatim(user_agent='geobot') location = geolocator.reverse(coord) r = location.raw adr = r.get('address') cc = adr.get('country_code') loc = location.address dist = distance.distance(MYPLACE, coord) dist = str(dist) dist = 'Distance from Minsk to this place: {} km'.format(dist[0:3:]) link = 'https://www.google.com/maps/place/{}'.format(coord) if cc == 'by': bot.send_message(message.chat.id, loc) bot.send_message(message.chat.id, link) bot.send_message(message.chat.id, dist) else: print('None BY') coordi(message)
print("SLEEP " + str(secs)) time.sleep(secs) print("GEOCODING LOCATION: " + str(counter)) address = data.iloc[row] print(address) #print(address.to_string()) locator = Nominatim(user_agent="myGeocoder") #geocode = RateLimiter(locator.geocode, min_delay_seconds=2) try: #location = address.apply(geocode) location = locator.geocode(address, timeout=30) print(location.raw) latitude = location.latitude longitude = location.longitude location = locator.reverse([latitude, longitude]) display_name = location.raw['display_name'] print(display_name) country = location.raw['address']['country'] country_code = location.raw['address']['country_code'] except AttributeError: latitude = None longitude = None except KeyError: country = None country_code = None except NameError:
def get_geo_location(lat, long): geo = Nominatim() string = "{0} , {1}".format(lat, long) geo_location = geo.reverse(string, timeout=5) return geo_location.address
# Converting coordinates to geographical locations # pip install geopy from geopy import Nominatim lat = float(input('Enter lattitude : ')) lon = float(input('Enter longitude : ')) coord = (lat, lon) # [Example] coord = (26.8393,80.9231) try: geolocator = Nominatim(user_agent='test/1') location = geolocator.reverse(f'{coord[0]},{coord[1]}') print('Based on entered coordinates, the location is :', location.address) except: print('looks like you are not connected with internet') print('or given coordinates may be wrong')
PAYMENTS_CSV_PATH = '~/Downloads/payments.csv' columns = ['id', 'Card Address Country', 'Card Address City'] df = pd.read_csv(PAYMENTS_CSV_PATH, encoding="ISO-8859-1")[columns].set_index('id') geolocator = Nominatim() for reg in models.Registration.query.all(): order = models.Order.query.join(models.OrderProduct, aliased=False). \ join(models.order_product_registrations_mapping, aliased=False). \ filter_by(registration_id=reg.id).first() if order and order.payments: for payments in order.payments: if payments.stripe_charge_id in df.index: location_str = ' '.join(list(df.loc[payments.stripe_charge_id].dropna().values)) # print(reg.name, '-', location_str) geolocator_reverse_data = geolocator.reverse(geolocator.geocode(location_str).point, language='en') city = geolocator_reverse_data.raw['address'].get('city') if not city: city = geolocator_reverse_data.raw['address'].get('town') if not city: city = geolocator_reverse_data.raw['address'].get('village') if not city: city = geolocator_reverse_data.raw['address'].get('county') state = geolocator_reverse_data.raw['address'].get('state') country = geolocator_reverse_data.raw['address']['country'] print(reg.name, '-', country, '-', state, '-', city) # print(geolocator_reverse_data.raw['address']) reg.country = country reg.state = state reg.city = city
def generateMap(self, tiles, map_zoom_start=6, heatmap_radius=7, heatmap_blur=4, heatmap_min_opacity=0.2, heatmap_max_zoom=4): map_data = [(coords[0], coords[1], magnitude) for coords, magnitude in self.coordinates.items()] map_data_with_year = [ (coords[0], coords[1], magnitude, coords[2]) for coords, magnitude in self.coordinates.items() ] df_data = pd.DataFrame(map_data_with_year, columns=['Lat', 'Long', 'Weight', 'Year']) year_list = df_data.Year.sort_values().unique() map_data_by_year = [] for year in year_list: map_data_by_year.append( df_data.loc[df_data.Year == year, ['Lat', 'Long', 'Weight']].groupby( ['Lat', 'Long']).sum().reset_index().values.tolist()) # Generate map m = folium.Map(location=self.max_coordinates, zoom_start=map_zoom_start, tiles=tiles) world_imagery = "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}" folium.TileLayer( tiles=world_imagery, name="World Imagery", attr= 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community' ).add_to(m) folium.TileLayer(tiles='Stamen Terrain', name='Stamen Terrain').add_to(m) folium.TileLayer('cartodbdark_matter', name='Dark Matter').add_to(m) # Generate heat map heatmap = HeatMap( map_data, max_val=self.max_magnitude, min_opacity=heatmap_min_opacity, radius=heatmap_radius, blur=heatmap_blur, max_zoom=heatmap_max_zoom).add_to( folium.FeatureGroup(name="Combined HeatMap").add_to(m)) locator = Nominatim(user_agent="geocoder", timeout=None) timesVisited = [x[2] for x in map_data] timesVisited.sort(reverse=True) top20Visited = timesVisited[19] marker_group = folium.FeatureGroup(name="Markers") mc = MarkerCluster() for lat, lon, freq in map_data: if freq >= top20Visited: coordinates = lat, lon location = locator.reverse(coordinates) times_visited = location.address + "\nVisited " + str( freq) + " times" mc.add_child( folium.Marker(location=[lat, lon], popup=times_visited)) folium.plugins.HeatMapWithTime(map_data_by_year, name="HeatMap by Year", index=year_list.tolist(), min_opacity=heatmap_min_opacity, radius=heatmap_radius, gradient={ 0.2: 'blue', 0.4: 'lime', 0.6: 'orange', 1: 'red' }).add_to(m) mc.add_to(marker_group) marker_group.add_to(m) folium.LayerControl().add_to(m) return m
def add(): with open("extraction/other_crimes.out") as data_file: data = json.load(data_file) crime_data = iter(data['crimes']) for line in range(1): next_crime = next(crime_data) date = next_crime['date'] date = date[:date.find('T')] converted_year = convert_year(date) converted_month = convert_month(date) converted_day = convert_day(date) # # next_crime_formatted = Crime(lat=next_crime['lat'], lng=next_crime['lon'], time=datetime.date(year=converted_year, month=converted_month, day=converted_day, address=next_crime['address'], description=next_crime['link']) # next_crime_type = CrimeType(name=next_crime['type'], desc='crimes are bad') geolocator = Nominatim() location = geolocator.reverse("30.25, -97.75") zip = location.raw['address']['postcode'] location = geolocator.geocode(str(zip)) boundingbox = location.raw['boundingbox'] maxlat = float(boundingbox[1]) minlat = float(boundingbox[0]) maxlng = float(boundingbox[3]) minlng = float(boundingbox[2]) meanlat = (maxlat + minlat) / 2 meanlng = (maxlng + minlng) / 2 #next_zip = Zip(zip_code=zip, lat=meanlat, lng=meanlng) #next_week = Week( # crime_1 = Crime(lat=30.28500, lng=-97.7320000, time=datetime.date(year=2015, month=10, day=28), address="gdc", description="Graffiti of pig on building") # crime_2 = Crime(lat=30.30000, lng=-97.730000, time=datetime.date(year=2015, month=10, day=20), address="Duval Rd", description="Burglary at Quacks Bakery") # crime_3 = Crime(lat=30.27000, lng=-97.719000, time=datetime.date(year=2015, month=10, day=14), address="12th and Chicon", description="Murder on 12th and Chicon") crime_type_1 = CrimeType(name='Vandalism', desc = "Vandalism is bad") crime_type_2 = CrimeType(name='Burglary', desc = "Burglary is bad") crime_type_3 = CrimeType(name='Assault', desc = "Assault is bad") zip_1 = Zip(zip_code=78704, lat=32.123, lng=32.123, pop=20000, family_income=50000) zip_2 = Zip(zip_code=78705, lat=30.123, lng=30.123, pop=23000, family_income=30000) zip_3 = Zip(zip_code=78706, lat=35.123, lng=35.123, pop=19000, family_income=45000) week_1 = Week(start=datetime.date(year=2015, month=10, day=11), end=datetime.date(year=2015, month=10, day=17)) week_2 = Week(start=datetime.date(year=2015, month=10, day=18), end=datetime.date(year=2015, month=10, day=24)) week_3 = Week(start=datetime.date(year=2015, month=10, day=25), end=datetime.date(year=2015, month=10, day=31)) #set up all of the foreign key relationships print("Crime one week: " + str(week_1.start)) try: for crime in crimes: print('crime: ' + str(crime)) # session.add() # session.add(crime_1) # session.add(crime_2) # session.add(crime_3) session.add(crime_type_1) session.add(crime_type_2) session.add(crime_type_3) session.add(zip_1) session.add(zip_2) session.add(zip_3) session.add(week_1) session.add(week_2) session.add(week_3) print("commiting to database") session.commit() except Exception as e: print(e) session.rollback() print("Everything broke")
def coordinate_task(lat, long): """Coordinates -> Address.""" locator = Nominatim(user_agent="geocoder_app") coordinate_address = locator.reverse(f"{lat}, {long}") return coordinate_address.raw
def usuario_login(token, token_fcm, latitude, longitude, fcm_type, movil): if latitude == '-1': latitud_registro = 41.683490 else: latitud_registro = Decimal(latitude) if longitude == '-1': longitud_registro = -0.888479 else: longitud_registro = Decimal(longitude) if token == 'nothing': return 'Error' else: try: user_info = auth.get_account_info(token) user_uid = user_info['users'][0]['localId'] try: name = user_info['users'][0]['displayName'] if name == '': name = user_info['users'][0]['email'].split("@")[0] except: name = user_info['users'][0]['email'].split("@")[0] try: profile_image = user_info['users'][0]['providerUserInfo'][0][ 'photoUrl'] except: profile_image = 'https://www.iconsdb.com/icons/preview/black/book-xxl.png' except: print("Error con firebase en login social") return 'Error' try: geolocator = Nominatim(user_agent="bookalo") location = geolocator.reverse( str(latitud_registro) + ',' + str(longitud_registro)) try: ciudad = location.raw['address']['city'] except: ciudad = location.raw['address']['county'] except: ciudad = 'Zaragoza' try: user = Usuario.objects.get(uid=user_uid) if user.esta_baneado: return status.HTTP_401_UNAUTHORIZED else: user.latitud_registro = latitud_registro user.longitud_registro = longitud_registro user.ciudad = ciudad user.save() update_last_connection(user) try: if movil == 'true': es_movil = True else: es_movil = False sessions = Sesion.objects.filter(usuario=user) if sessions: for session in sessions: if session_needs_deleting(session): session.delete() user = Usuario.objects.get(uid=user_uid) try: sesion = Sesion.objects.get(token_fcm=token_fcm, usuario=user) sesion.token = token sesion.save() except Exception as ex: Sesion.objects.create(token=token, token_fcm=token_fcm, usuario=user, es_movil=es_movil) else: try: user = Usuario.objects.get(uid=user_uid) Sesion.objects.create(token=token, token_fcm=token_fcm, usuario=user, es_movil=es_movil) except Exception as ex: user = Usuario.objects.get(uid=user_uid) Sesion.objects.create(token=token, token_fcm=str(ex), usuario=user, es_movil=es_movil) except Exception as ex: print("Error while looking for active sessions") return UserSerializer(user).data except Usuario.DoesNotExist: new_user_data = Usuario.objects.create( username=user_uid, uid=user_uid, token_fcm=token_fcm, nombre=name, latitud_registro=latitud_registro, longitud_registro=longitud_registro, imagen_perfil=profile_image, ciudad=ciudad) Sesion.objects.create(token=token, token_fcm=token_fcm, usuario=new_user_data) update_last_connection(new_user_data) return UserSerializer(new_user_data).data
def set_location(self, coordinates): locator = Nominatim() self.location = locator.reverse(coordinates).address
print("[") for tweet in cursor: place = tweet['place'] coordinates = tweet['coordinates'] location = None if coordinates != None: lon = coordinates['coordinates'][0] lat = coordinates['coordinates'][1] if -170 < lon < -60 and 12 < lat < 72: tries = 3 while tries > 0: try: time.sleep(1) location = geolocator.reverse("%f, %f" % (lat, lon)) break except geopy.exc.GeocoderTimedOut: time.sleep(1) tries -= 1 except geopy.exc.QuotaExceeded: time.sleep(10) elif place != None: place_coordinates = place['bounding_box']['coordinates'] lon = (float(place_coordinates[0][0][0]) + float(place_coordinates[0][1][0])) / 2 lat = (float(place_coordinates[0][0][1]) + float(place_coordinates[0][2][1])) / 2 if -170 < lon < -60 and 12 < lat < 72 and place[ 'country'] == "United States":
class Cave(Base): """ Cave class instance for storing caves to which belong images and hands """ # Primary attributes name = Column(String(50)) description = Column(String(200)) latitude = Column(Float) longitude = Column(Float) project_id = Column(Integer, ForeignKey("projects.id")) # Secondary attributes (retrieved using geopy library) city = Column(String(50)) town = Column(String(50)) village = Column(String(50)) suburb = Column(String(50)) country = Column(String(50)) country_code = Column(String(2)) county = Column(String(50)) state = Column(String(50)) continent = Column(String(50)) address = Column(String(200)) # Relationships project = relationship("Project", back_populates="caves") images = relationship("Image", order_by=Image.id, back_populates="cave", cascade="all, delete-orphan") def __init__(self, **kwargs): super().__init__(**kwargs) self.geolocator = Nominatim(user_agent="Kalimain") try: self.location = self.geolocator.reverse( "%f, %f" % (self.latitude, self.longitude)) except GeocoderServiceError: warnings.warn( "Unable to reach service: only primary attributes will be set", ApiConnectionWarning) else: # Set secondary attributes self.get_secondary_attributes() def __eq__(self, other): if not isinstance(other, Cave): return False if self.latitude == other.latitude and self.longitude == other.longitude: return True else: return False def get_continent(self): if self.country is not None: continent_code = country_alpha2_to_continent_code( self.country_code.upper()) return convert_continent_code_to_continent_name(continent_code) def get_secondary_attributes(self): self.address = self.location.raw["display_name"] for key, val in self.location.raw["address"].items(): try: self.__setattr__(key, val) except AttributeError: pass self.continent = self.get_continent()
## add columns for output tables locs['street_address'] = "" locs['city'] = "" locs['state'] = "" locs['zipcode'] = np.nan ## fetch address data from lat and lon values geolocator = Nominatim() for i in range(locs.shape[0]): lat = locs.iloc[i]['latitude'] lon = locs.iloc[i]['longitude'] lat_lon = str(lat) + ', ' + str(lon) try: a_obj = geolocator.reverse(lat_lon) except: a_obj = geolocator.reverse(lat_lon) ## address components try: street_address = a_obj.raw['address'][ 'house_number'] + ' ' + a_obj.raw['address']['road'] except: street_address = a_obj.address zipcode = a_obj.raw['address']['postcode'] city = a_obj.raw['address']['city'] state = a_obj.raw['address']['state'] ## insert into dataframe locs['street_address'].iloc[i] = street_address
geolocator = Nominatim() accidents = data['accidents'] # hood_info will store whatever we want to know about a given neighborhood # ex: ' # {hood: [[incidents], total_incedents, severe, ...] # we can continue adding info to the dict hood_info = defaultdict(list) i = 0 for v in accidents: # if i == 50: # break try: zippy = \ geolocator.reverse(str(v['lat']) + ', ' + str(v['lng'])).raw['display_name'].split('Illinois')[1].split( ',')[1].replace(" ", "") except Exception: print('geolocator could not reverse.') i += 1 continue if zippy not in zip_dict: print('zip:' + zippy + ' not in common neighborhoods') continue hood = zip_dict[zippy] # the neighborhood name associated with a zip if hood in hood_info: hood_info[hood][0].append(v) hood_info[hood][1] += 1 else: hood_info[hood] = [[v], 1, 0]
from geopy import Nominatim import json import csv locator = Nominatim(user_agent='myGeocoder') with open("datasets\data-preview.csv",'r') as f: reader = csv.reader(f) addr = [] for case in reader: if case[1] == 'US': if case[0] == "": next else: addr.append("\"{},{}\"".format(case[2],case[3])) for place in addr: print(place) location = locator.reverse(place) print(location.raw) # print("Latitude = {}, Longitude = {}".format(location.latitude, location.longitude))
pw.append(k.get('osmid')) except: # to catch and skip noneType iterations continue # DO NOT CHANGE TIMEOUT... THIS IS TO PREVENT YOUR IP FROM BEING BANNED locator = Nominatim(user_agent="myGeocoder", timeout=30) building = {} autofillList = [] count = 0 # testing algorithmn speed start_time = time.time() for k in walkNodeList: coordinates = k.get('y'), k.get('x') location = locator.reverse(coordinates) k["address"] = location[0] print(count) count += 1 if location[0] not in autofillList: print(location[0]) autofillList.append(location[0]) else: continue for item in mrtNodeList: try: if "PE" in item.get('ref') or "PW" in item.get('ref'): coordinates = item.get('y'), item.get('x') location = locator.reverse(coordinates) autofillList.append(location[0])
def get_zip(next_crime_raw): geolocator = Nominatim() location = geolocator.reverse(str(str(next_crime_raw['lat']) + ", " + str(next_crime_raw['lon']))) return location.raw['address']['postcode']