def answer(bot, update): chat_id = update['chat']['id'] if update['text'][0] == '/': if update['text'] == '/start': bot.send_message( chat_id, "Hello! Enter any place in the USA and I will find where you can eat nearby" ) return if update['text'] == '/help': bot.send_message( chat_id, "Hello! It's a FastFood bot. You can send them the name of some\ place in the USA and it'll send you where you can eat nearby.\ Send /start to start. It doesn't know another command yet.") return else: bot.send_message( chat_id, "Excuse me. I haven't been taught that command yet.") return else: coordinates = update['text'].split(', ') geo = None # Если пользователь ввел географические координаты if coordinates[0].replace('.', '', 1).isdigit() and coordinates[1].replace( '.', '', 1).isdigit(): USA_coordinates = geocoder.geocodefarm('USA').bbox if USA_coordinates['southwest'][0] < float(coordinates[0]) < USA_coordinates['northeast'][0] and \ USA_coordinates['southwest'][1] < float(coordinates[1]) < USA_coordinates['northeast'][1]: geo = coordinates else: bot.send_message( chat_id, "Sorry, the service works only for US restaurants") return else: geo = geocoder.arcgis( update['text'] ) # Возвращает характеристики географического объекта введенного словами if geo.latlng is None: bot.send_message( chat_id, "Please make sure that you entered the data correctly") return else: temp = geo.latlng # Оставляем в geo только географические координаты geo = temp database = sqlite3.connect("FastFood.db") cursor = database.cursor() # Выбираем из базы ресторан(ы) близжайший к указаной точке restaurants = cursor.execute( "SELECT name, address, city, websites, MIN((latitude - {})*(latitude - {}) + \ (longitude - {})*(longitude - {})) FROM FastFood".format( geo[0], geo[0], geo[1], geo[1])) for restaurant in restaurants: bot.send_message( chat_id, "The restaurant next to you: {}, {}, {} {}".format( restaurant[0], restaurant[1], restaurant[2], restaurant[3]))
def geolocate(address, try_all=True): try: # see https://astral.readthedocs.io/en/latest/#cities a = lookup(address, database()) return a.latitude, a.longitude except: pass # use online geocoder location_data = geocoder.geonames(address, method='details', key='jarbas') if not location_data.ok: location_data = geocoder.geocodefarm(address) if not location_data.ok: location_data = geocoder.osm(address) if try_all: # more are just making it slow if not location_data.ok: location_data = geocoder.google(address) if not location_data.ok: location_data = geocoder.arcgis(address) if not location_data.ok: location_data = geocoder.bing(address) if not location_data.ok: location_data = geocoder.canadapost(address) if not location_data.ok: location_data = geocoder.yandex(address) if not location_data.ok: location_data = geocoder.tgos(address) if location_data.ok: location_data = location_data.json lat = location_data.get("lat") lon = location_data.get("lng") return lat, lon raise ValueError
def test_geocodefarm_reverse(): url = 'https://www.geocode.farm/v3/json/reverse/?lat=45.3&lon=-75.4&lang=&country=' data_file = 'tests/results/geocodefarm_reverse.json' with requests_mock.Mocker() as mocker, open(data_file, 'r') as input: mocker.get(url, text=input.read()) result = geocoder.geocodefarm(coordinates, method='reverse') assert result.ok
def geocodefarm_point(self, location_str): g = geocoder.geocodefarm(location_str) if g.ok: self.geojson_point = g.geojson else: self.geojson_point = { 'status': 'no_match', 'location_str': location_str }
def geolocate(address, service="geocodefarm"): data = {} if service == "geocodefarm": location_data = geocoder.geocodefarm(address) elif service == "osm": location_data = geocoder.osm(address) elif service == "google": location_data = geocoder.google(address) elif service == "arcis": location_data = geocoder.arcgis(address) elif service == "bing": location_data = geocoder.bing(address) elif service == "canadapost": location_data = geocoder.canadapost(address) elif service == "yandex": location_data = geocoder.yandex(address) elif service == "tgos": location_data = geocoder.tgos(address) else: raise ValueError("Unknown geocoder service") if location_data.ok: location_data = location_data.json data["country"] = location_data.get("country") data["country_code"] = location_data.get("country_code") data["region"] = location_data.get("region") data["address"] = location_data.get("address") data["state"] = location_data.get("state") data["confidence"] = location_data.get("confidence") data["lat"] = location_data.get("lat") data["lon"] = location_data.get("lng") data["city"] = location_data.get("city") data["postal"] = location_data.get("postal") data["timezone"] = location_data.get("timezone_short") else: return None location = { "city": { "name": data["city"], "state": { "name": data["state"], "country": { "code": data["country_code"], "name": data["country"] } } }, "coordinate": { "latitude": data["lat"], "longitude": data["lon"] }, "timezone": { "name": data["timezone"] } } return location
def test_geocodefarm(): url = 'https://www.geocode.farm/v3/json/forward/?addr=New+York+City&lang=&country=&count=1' data_file = 'tests/results/geocodefarm.json' with requests_mock.Mocker() as mocker, open(data_file, 'r') as input: mocker.get(url, text=input.read()) result = geocoder.geocodefarm(location) assert result.ok osm_count, fields_count = result.debug()[0] assert osm_count == 3 assert fields_count == 15
def get_address(latitude, longitude): import geocoder where = known_location(latitude, longitude) if where: return where else: import requests try: g = geocoder.geocodefarm([latitude, longitude], method="reverse") except requests.exceptions.RequestException as e: return "Unknown" if g.address == None: return "Bad Request" else: return g.address
def geolocate(self, address, try_all=True): if address in self.geocache: return self.geocache[address] try: # should be installed from default skills from astral.geocoder import database, lookup # see https://astral.readthedocs.io/en/latest/#cities a = lookup(address, database()) self.geocache[address] = (a.latitude, a.longitude) return a.latitude, a.longitude except: pass # use online geocoder location_data = geocoder.osm(address) if not location_data.ok: location_data = geocoder.geocodefarm(address) if try_all: # more are just making it slow if not location_data.ok: location_data = geocoder.google(address) if not location_data.ok: location_data = geocoder.arcgis(address) if not location_data.ok: location_data = geocoder.bing(address) if not location_data.ok: location_data = geocoder.canadapost(address) if not location_data.ok: location_data = geocoder.yandex(address) if not location_data.ok: location_data = geocoder.tgos(address) if location_data.ok: location_data = location_data.json lat = location_data.get("lat") lon = location_data.get("lng") self.geocache[address] = (lat, lon) return lat, lon raise ValueError
def test_geocodefarm(): g = geocoder.geocodefarm(location) assert g.ok assert str(g.city) == city
locations.add(location(ll[0][0], ll[0][1])) locations.add(location(ll[-1][0], ll[-1][1])) if small > 30: break small += 1 tot_accuracy = 0 for location in locations: accuracy = 0 #use geocoder and mapzen to get a reverse geocode. google = geocoder.google( [float(location.latitude), float(location.longitude)], method='reverse') osm = geocoder.geocodefarm( [float(location.latitude), float(location.longitude)], method='reverse') #farm = geocoder.geocodefarm([float(location.longitude),float(location.latitude)], method='reverse') location.google_address = google.address location.osm_address = osm.address if google.street and osm.street and SequenceMatcher( None, google.street, osm.street).ratio() > .6: accuracy += 1 elif google.street and osm.street: print("google street: " + google.address) print("osm street: " + osm.address) else: print("street not there") if google.postal == osm.postal: accuracy += 1 elif google.postal and osm.postal:
lat_lng_coords = None while (lat_lng_coords is None): g = geocoder.arcgis( '{}, London, United Kingdom'.format(arcgis_geocoder)) lat_lng_coords = g.latlng return lat_lng_coords # %% sample = get_latlng('SE2') sample # %% gg = geocoder.geocodefarm(sample, method='reverse') gg # %% start = time.time() postal_codes = df_se_top['Postcode'] coordinates = [ get_latlng(postal_code) for postal_code in postal_codes.tolist() ] end = time.time() print("Time of execution: ", end - start, "seconds") # %% df_se_loc = df_se_top
st.write( "Enter a place, street or address and see if the results of differenct geocoders give similar results!" ) st.text("") address_input = st.text_input("Enter address and press Enter", "Pariser Platz, Berlin") if not address_input: st.stop() st.text("") st.text("") api_names = ["🔴 Arcgis", "🟡 OSM", "🟢 GeocodeFarm"] a = geocoder.arcgis(address_input) o = geocoder.osm(address_input) g = geocoder.geocodefarm(address_input) api_results = [a, o, g] points = [] api_cols = st.beta_columns(3) for col, name, result in zip(api_cols, api_names, api_results): col.markdown(f"## {name}") result = result.json if result is not None: col.markdown(f"**Address**: \n\n {result['address']}") col.markdown(f"**Longitude, Latitude**: \n\n {result['lng']}, {result['lat']}") col.text("") expander = col.beta_expander("Show full information")
import geocoder dat = geocoder.geocodefarm('Cuautitlan Izcalli') print(str(dat.latlng)) dat = geocoder.reverse(dat.latlng) print(dat.address) #Direccion print(dat.country) #país print(dat.state) #estado print(dat.county) #Municipio print(dat.street) #Calle
def test_geocodefarm_reverse(): g = geocoder.geocodefarm(ottawa, method='reverse') assert g.ok
# of structured information # about the place # but it is not the place # the place has been abstracted # beyond recognition # we should be so lucky # that geocodefarm gives us this information # for free # originally i tried to use google # but they asked for my credit card # i almost gave it to them # but switched to geocodefarm instead # this information is free now # but also not really abstracted = geocoder.geocodefarm(place) # this code will place a value judgement # upon your place # true or false # if this code determines # that your place is truly a place # this code will try to tell you # that your place is a series of numbers # but it is not if abstracted.ok == True: print(f"Congrats! Your place exists. Its coordinates are {abstracted.latlng}") # this code determined # that your place is false # this code will try to tell you
import geocoder lat = 40.7608 lon = -111.8910 location = geocoder.geocodefarm([lat, lon], key=None, method='reverse') print(location.json)