def create_ctarail_zip_df(): ''' Finds the lattitude and longitude of CTA rail stations using the MapQuest API. Processes addresses without postal codes to find lat/lon, then reverse geocodes the lat/lon to find the postal code. Output: zip_df (DataFrame): pandas DataFrame containing zipcode of rail stations in the the order that stations appear in CTA_RailStations.shp ''' cta_rail = geopd.read_file("CTA_RailStations.shp") ad = cta_rail["ADDRESS"] ad = ad + " Chicago, IL" lat_lst = [] lon_lst = [] zip_lst = [] for i in range(len(ad)): print("Get lat/lon:", i) g = geocoder.mapquest(ad.iloc[i], key="mmcN5Afp3QejG7fOZ0ljDyhrneaqeazD") lat_lst.append(g.lat) lon_lst.append(g.lng) for i in range(len(lon_lst)): print("Get Address:", i) g = geocoder.mapquest([lat_lst[i], lon_lst[i]], method='reverse', key="mmcN5Afp3QejG7fOZ0ljDyhrneaqeazD") postal = g.postal zip_lst.append(postal) zip_df = pd.DataFrame({"zipcode": zip_lst}) return zip_df
def getLatLong(route_points): lat_long_points = [] print("Points received to get lat long: ", route_points) if type(route_points) == list: for i in range(len(route_points)): geo_loc = geocoder.mapquest(route_points[i], key=API_KEY) lat_long_points.append([geo_loc.lng, geo_loc.lat]) return lat_long_points if type(route_points) == str: geo_loc = geocoder.mapquest(route_points, key=API_KEY) lat_long_point = [geo_loc.lng, geo_loc.lat] return lat_long_point
def create_ctabus_zip_df(): ''' Finds the zipcode for each CTA bus stop using the lattitude and longitude values provided by the CTA_BusStops.shp. Uses the MapQuest API to reverse geocode the lat/lon coordinates and obtain the zipcode. Note: This will take about 30+ minutes to run. There are 10,846 CTA bus stops. ''' cta_bus = geopd.read_file("CTA_BusStops.shp") lat = cta_bus["POINT_Y"] lon = cta_bus["POINT_X"] bus_zip_lst = [] for i in range(len(lat)): print("Finding Zipcode:", i) g = geocoder.mapquest([lat.iloc[i], lon.iloc[i]], method='reverse', key="mmcN5Afp3QejG7fOZ0ljDyhrneaqeazD") postal = g.postal bus_zip_lst.append(postal) clean_bus_zips = [] for z in bus_zip_lst: if z: z = z[:5] clean_bus_zips.append(z) zip_df = pd.DataFrame({"zipcode": clean_bus_zips}) return zip_df
def searchArea(kw, location=geocoder.ip('me')): start = time.strftime("%m/%d/%Y") start = datetime.strptime(start, "%m/%d/%Y") date = str(start - timedelta(days=7)) keyword = kw.lower() g = geocoder.mapquest(location, key=credentials['MapquestKey']) current_location = str(g.latlng[0]) + "," + str(g.latlng[1]) count = 0 tweets = [] last_tweet_id = None more_tweets = True check_tweet_id = '69' while more_tweets: try: tweets_to_add = api.GetSearch(geocode=(current_location + ",5mi"), since=date[:10], include_entities=False, count=100, max_id=last_tweet_id) last_tweet_id = tweets_to_add[len(tweets_to_add) - 1].id_str if check_tweet_id == last_tweet_id: raise Exception list_add = [s.full_text for s in tweets_to_add] for tweet in list_add: word_list = re.sub("[^\w]", " ", tweet).split() for word in word_list: word_check = word.lower() if word_check == keyword: count += 1 break tweets.append(tweet) check_tweet_id = last_tweet_id except: more_tweets = False return count
def get_address_from_coordinates_spb(crd): kinds = ['house', 'district', 'locality'] result = {} for kind in kinds: geocode_yandex = geocoder.yandex( crd, method='reverse', kind=kind, lang='RU', key='7bb41e4d-5a27-4b8c-a856-ee56d3284019') yandex_address_array = geocode_yandex.address.split(',') print(yandex_address_array) if len(yandex_address_array) == 4: result = { 'city': yandex_address_array[1].strip(), 'street': yandex_address_array[2].strip(), 'house': yandex_address_array[3].strip(), } geocode_mapquest = geocoder.mapquest(crd, method='reverse', key=settings.MAPQUEST_MAP_KEY) result.update({'postal': geocode_mapquest.postal}) else: result = { 'city': yandex_address_array[1].strip(), } return result
def generate_text(lat, lon, config): text = ("[Google Maps](https://www.google.com/maps/search/?api=1&query=" + str(lat) + "," + str(lon) + ")") if config['geocoding']: if config['static_provider'] == "google": geocode = geocoder.google([db_poi_lat, db_poi_lon], method='reverse', key=config['static_key'], language=config['language']) elif config['static_provider'] == "osm": geocode = geocoder.mapquest([db_poi_lat, db_poi_lon], method='reverse', key=config['static_key'], language=config['language']) elif config['static_provider'] == "mapbox": geocode = geocoder.mapbox([db_poi_lat, db_poi_lon], method='reverse', key=config['static_key'], language=config['language']) else: address = "" text = (navigation + "\n" + geocode.address) return text
def locate(destination): import openrouteservice #find user's current location startGeocoder = geocoder.ip('me') s_lat = startGeocoder.lat s_lng = startGeocoder.lng start_pos = (s_lng, s_lat) #find the coordinates of the desired location eg = geocoder.mapquest(destination, key=geo_key) e_lat = eg[0].lat e_lng = eg[0].lng end_pos = (e_lng, e_lat) coords = (start_pos, end_pos) print(coords) client = openrouteservice.Client(route_key) routes = client.directions(coords, units="mi", profile="driving-car") #format direction output output = "" for route in routes["routes"][0]["segments"][0]["steps"]: output += "In " + str( route["distance"]) + " miles, " + route["instruction"] + ".\n" return output
def get_lat_lng(df: 'Dataframe Object'): """finds the latitude and longitude values args: Dataframe Object returns Mapquest Batch Object """ try: lat_n_lng = geocoder.mapquest(df.iloc[:, 0], method='batch', key=KEY) return lat_n_lng except IndexError: return "<h1>Please upload the Correct file</h1>"
def geocode(row): api_key = os.environ.get('MAPQUEST_API_KEY') if not api_key: print 'MAPQUEST_API_KEY not set' else: address = "{} Boulder, Colorado".format(row[0]) print address g = geocoder.mapquest(address, key=api_key) return (g.json['lat'], g.json['lng'])
def geo_data(lat,lon): try: geocoded = geocoder.mapquest([lat, lon], method='reverse', key=os.environ['MAPQUEST_KEY']) geolist = (geocoded.country, geocoded.city, geocoded.json['raw']['street'], geocoded.postal) return geolist except Exception as e: log.error(e) geolist = ('unknown','unknown','unknown','unknown') return geolist
def test_mapquest_batch(): url = 'http://www.mapquestapi.com/geocoding/v1/batch' data_file = 'tests/results/mapquest_batch.json' with requests_mock.Mocker() as mocker, open(data_file, 'r') as input: mocker.get(url, text=input.read()) g = geocoder.mapquest(locations, method='batch', timeout=10) assert g.ok expected_results = [[39.738453, -104.984853], [40.015831, -105.27927]] assert [result.latlng for result in g] == expected_results
def run(output, start): logging.basicConfig() #g = geocoder.mapquest('Salta, None, Argentian', key='SmpPVNYKcPvAJeT0VefAvJf8p8VvSqcJ') #key = 'SmpPVNYKcPvAJeT0VefAvJf8p8VvSqcJ' key = 'PJFmpZU3vg79oKbIoncDGIAaPNGlHPU1' data = [] with open(output, 'w') as fw: with open('wine_full.json') as fr: rr = json.load(fr) print "Input len: ", len(rr) sep = ', ' count = 0 addrs = [] list_10 = [] eof = len(rr) - 1 total = 0 begin = 0 progress = 0 for idx, line in enumerate(rr): if begin < start: begin = begin + 1 continue addr = makeAddr(line) addrs.append(addr) list_10.append(line) count = count + 1 total = total + 1 progress = progress + 1 if progress % 1000 == 0: print progress if count == 10 or idx == eof: g = geocoder.mapquest(addrs, method='batch', key=key) # append to original data for idx, val in enumerate(g): list_10[idx]['lat'] = val.raw['latLng']['lat'] list_10[idx]['lng'] = val.raw['latLng']['lng'] data.append(list_10[idx]) addrs = [] count = 0 list_10 = [] if total == 15000: break print "Output len: ", len(data) json.dump(data, fw)
def findGeoFunc(location): # get longitutde and latitude with location query geoCode = geocoder.mapquest(location, key=geoCodeKey) latitude = geoCode.lat longitute = geoCode.lng # Log to console # print(str(location) + "\n Latitude:" + str(latitude) + " Longitude:" + str(longitute) + '\n') # return as array return ([latitude, longitute])
def getLocation(place: str) -> list: """Gets location of lat/long based on input""" area = [] g = geocoder.mapquest(location=place, key='KEY') destination = g.latlng for items in destination: area.append(items) area.append('5mi') return area
def geocode_worker(inputrow): try: r = geocoder.mapquest(inputrow, key='rszS6XG8TKX2oHEIiJexOAHiMwdYYxCS') lat = r.lat lng = r.lng print(r) except Exception: lat = None lng = None print('fail') return lat, lng
def test_mapquest_with_bbox(): g = geocoder.mapquest(winnetka, bbox=winnetka_bbox) assert g.ok osm_count, fields_count = g.debug()[0] assert osm_count >= 2 assert fields_count >= 11 for result in g: assert (result.lng >= winnetka_bbox[0]) and (result.lng <= winnetka_bbox[2]) assert (result.lat >= winnetka_bbox[1]) and (result.lat <= winnetka_bbox[3])
def find_coordinates(address): """ str -> float, float Function returns coordinates of given address. >>> find_coordinates('London, UK') (51.50015, -0.12624) """ coordinates = geocoder.mapquest(address) film_lat = coordinates.json['lat'] film_lng = coordinates.json['lng'] return film_lat, film_lng
def get_coordinates(street, city, state, zipcode): g = geocoder.mapquest(f'{street}, {city}, {state}, {zipcode}', key=MAPQUEST_API_KEY) if g.ok: lat = g.json.get('lat', 0) lng = g.json.get('lng', 0) return (lat, lng) return (0, 0)
def geocode(self, appartement): """Retrieve the lat and long using different fallback services""" g = geocoder.google(appartement["address"]) if not g.latlng: g = geocoder.osm(appartement["address"]) if not g.latlng and MAPQUEST_API_KEY: g = geocoder.mapquest(appartement["address"], key=MAPQUEST_API_KEY) # if we can't geocode the address, we return the map center if g.latlng: return g.latlng else: return MAP_LATLNG
def getTweetState(tweet): west = tweet['place']['bounding_box']['coordinates'][0][0][0] east = tweet['place']['bounding_box']['coordinates'][0][2][0] north = tweet['place']['bounding_box']['coordinates'][0][2][1] south = tweet['place']['bounding_box']['coordinates'][0][0][1] lat = (north + south)/2 long = (west+east)/2 #address = geolocator.reverse((lat,long), exactly_one=True) location = ''.join([str(lat),",",str(long)]) state = mapquest(location).state return str(state)
def find_coordinates(address): """ str -> float, float Function returns coordinates of given address. >>> find_coordinates('London, UK') (51.50015, -0.12624) """ if address is not None: coordinates = geocoder.mapquest(address) lat = coordinates.json['lat'] lng = coordinates.json['lng'] return lat, lng else: return None, None
def ziptolatlng(address): if address in latlngdict: lat, lng = latlngdict[address] else: g = gc.mapquest(address, key=gc_api_key) if g.status_code == 200: lat, lng = g.latlng latlngdict[address] = (lat, lng ) # Store so do not have to fetch next time pkl.dump(latlngdict, open('../data/latlngdict.pkl', 'wb')) else: lat, lng = 500, 500 return lat, lng
def getgeo_mapquest(ip_list): count=1 latlng_set=[] for ip in ip_list: geoinfo = geocoder.mapquest(ip) print("[mapquest] {} ({}/{}) country: {}".format(ip, count, len(ip_list), geoinfo.json.get('country'))) if geoinfo.latlng: latlng_set.append([ip, geoinfo.latlng[0], geoinfo.latlng[1]]) else: print("{} not found".format(ip)) latlng_set.append([ip, "","" ]) count = count + 1 #print(latlng_set) return latlng_set
def getgeo_mapquest(ip_list): count = 1 latlng_set = [] for ip in ip_list: geoinfo = geocoder.mapquest(ip) print("[mapquest] {} ({}/{}) country: {}".format( ip, count, len(ip_list), geoinfo.json.get('country'))) if geoinfo.latlng: latlng_set.append([ip, geoinfo.latlng[0], geoinfo.latlng[1]]) else: print("{} not found".format(ip)) latlng_set.append([ip, "", ""]) count = count + 1 #print(latlng_set) return latlng_set
def geocode(self, address): """Retrieve the lat and long using different fallback services""" if GEOLOCALISE is False: return MAP_LATLNG g = geocoder.google(address) if not g.latlng: g = geocoder.osm(address) if not g.latlng and MAPQUEST_API_KEY: g = geocoder.mapquest(address, key=MAPQUEST_API_KEY) # if we can't geocode the address, we return the map center if g.latlng: return g.latlng else: return MAP_LATLNG
def userInput(): l = [] cont = True i = 1 while cont == True: city = raw_input("Please enter a city for your campaign:") if city == 'stop': cont = False else: i = i + 1 geocode_result = geocoder.mapquest(str(city),key='0avVckAOpv7m7HANtaBaRsSLfisXr9Ne') l.append((city,city,geocode_result.lat,geocode_result.lng, i, None)) return l
def update_geo_real(): ''' Use a true upstream geocoder to identify the locations ''' query = '''select * from DispatchLogs where Long=-96.784636''' c.execute(query) rows = c.fetchall() success = 0 total = len(rows) i = 0 for r in rows: # if r['GeoLookupType'] == 2: # print 'skipping...' #i += 1 # continue address = "%s %s, ND" % (r['Address'], r['VenueDescription']) result = geocoder.google(address).latlng coder = 'google' #result = [None, None] #coder = 'none' if (result[0] == None): #result = geocoder.tomtom(address).latlng coder = 'tomtom' if (result[0]) == None: try: result = geocoder.mapquest(address).latlng except simplejson.decoder.JSONDecodeError: # invalid address parsing error pass if result[1] == -96.784636: result = [None, None] coder = 'mapquest' if (result[0]) == None: result = geocoder.google(address).latlng coder = 'google' lat, lon = result print(address) print('%d/%d (%.5f%%) %.9f, %.9f - %s' % (i, total, (float(i) / total) * 100, lat, lon, coder)) if lat != None: update_record(r['CFSID'], lat, lon, 2) success += 1 conn.commit() i += 1 print(success, 'successful lookups of ', total, ' total rows')
def get(self): sql_server = SQL_Server() params0 = request.args.get('patient_id') params = request.args.get('user') params2 = (request.args.get('home_location')) geocoded_location = geocoder.mapquest(params2, key=MAP_QUEST_KEY) params2 = f"{geocoded_location.lat},{geocoded_location.lng}" params3 = request.args.get('email_information') if params != 'null': sql_server.insert_PatientId( params, params0, SQL_Server.dateTimeToString(datetime.now())) sql_server.insert_HomeInformation( params, params2, SQL_Server.dateTimeToString(datetime.now())) sql_server.insert_ContactInformation( params, params3, SQL_Server.dateTimeToString(datetime.now())) sql_server.save_database() sql_server.close_database() return "Home Location and Contact Information data added to User's table"
def geolocation(): lat = request.form['lat'] lon = request.form['lon'] logger.info('Lat: %s - Lon: %s', lat, lon) # get address from lat, lon response = geocoder.mapquest('{}, {}'.format(lat, lon)) if response.status_code == 200: address = '{}, {}, {}'.format(response.city, response.province, response.country) response = calc_my_position_address(address, MY_POSITION_FILENAME, upload=False) output = os.path.join('assets', 'data', 'my-position.json') save_json(response.latlng, output) return 'OK'
def lookup(address=None, neighborhood=None, city=None, state=None, country=None): """Geo-code an address and get its neighbhorhood name To make this compatible with any database, coordinates are stored as integers with 7-digit decimal precision to fit in 32 bits Args: address (str): street address neighborhood (str): neighborhood name city (str): city state (str): state country (str): 2-letter country abbreviation Returns: tuple: lat, long, neighborhood """ location = '%s,%s,%s' % (city, state, country) if address or neighborhood: location = '%s,%s' % (address or neighborhood, location) try: geo = geocoder.mapquest(location) except Exception as ex: if 'Provide API Key' in str(ex): logging.error('geocode: no MapQuest key set') else: logging.warning('action=geo_lookup error=%s' % str(ex)) return (None, None, '') # POINT column type only supported in PostgreSQL / sqlite # geo = 'POINT(%f %f)' % (geo.lng, geo.lat) geolat = int(geo.lat * 1.0e7) geolong = int(geo.lng * 1.0e7) if address and not neighborhood: # TODO neighborhood-lookup support neighborhood = 'A neighborhood%s' % (' in %s' % city if city else '') logging.info('geocode: lat=%f long=%f neighborhood="%s"' % (geo.lat, geo.lng, neighborhood)) Metrics().store('geo_lookup_total') return (geolat, geolong, neighborhood)
def geolocator(address): g = geocoder.mapquest(address, key=MAPQUEST_KEY).json addy = g['address'] zip = g['postal'] lat = g['lat'] long = g['lng'] city = g['city'] state = g['state'] geo_dict = { 'address': addy, 'zip': zip, 'lat': lat, 'long': long, 'city': city, 'state': state } return geo_dict
def sort(self, nfos): gres = geocoder.mapquest([n["indirizzo"] for n in nfos], method='batch', key=mapquest_key) for i, c in enumerate(gres): nfos[i]["latlng"] = c.latlng nfos[i][ "osm_url"] = "http://www.openstreetmap.org/directions?" + urlencode( { "route": ";".join( map(lambda c: ','.join(map(str, c)), (self.source.latlng, c.latlng))), "engine": "graphhopper_foot" }) return sorted(nfos, key=lambda nfo: great_circle( nfo["latlng"], self.source.latlng, ).m)
def create_data_array(self): locations = [[float(33.573110), float(-7.589843)]] self._cr.execute( "SELECT d.id,d.adresse " "FROM parcauto_demande d " "LEFT JOIN parcauto_ordremission om ON om.id = d.ordremission_id " "WHERE d.state = 'paslivre' AND om.id IS NULL") loc_temp = [] for res in self.env.cr.fetchall(): loc_temp.append(res) if loc_temp: g = geocoder.mapquest([i[1] for i in loc_temp], method='batch', key='2M3DloLAMyAYBjIdZFBpS7HejnT00e8r') for result in g: locations.append( [float(result.latlng[0]), float(result.latlng[1])]) ############## self._cr.execute("rollback") demands = [0] self._cr.execute( "SELECT d.poids_total " "FROM parcauto_demande d " "LEFT JOIN parcauto_ordremission om ON om.id = d.ordremission_id " "WHERE d.state = 'paslivre' AND om.id IS NULL") for res in self.env.cr.fetchall(): demands.append(int(res[0])) data = [locations, demands] else: data = [[], []] return data
def geolocation(): lat = request.form['lat'] lon = request.form['lon'] logger.info('Lat: %s - Lon: %s', lat, lon) # get address from lat, lon response = geocoder.mapquest('{}, {}'.format(lat, lon)) if response.status_code == 200: address = '{}, {}, {}'.format( response.city, response.province, response.country ) response = calc_my_position_address( address, MY_POSITION_FILENAME, upload=False ) output = os.path.join('assets', 'data', 'my-position.json') save_json(response.latlng, output) return 'OK'
def get_zips(lats=lats, lngs=lngs): latlng_grid = get_latlng_grid(lats, lngs) gc_api_key = '9GOLlJifpGuxjGPy2519C6NkcmtXxAYM' gs = [] postals = [] nopostals = [] for latlng in latlng_grid: print(latlng) g = gc.mapquest(latlng, key=gc_api_key, method='reverse') gs.append(g) if g.postal: postals.append(latlng) print('POSTAL!') else: nopostals.append(latlng) print('NO POSTAL!', g.status_code) time.sleep(0.1) print(len(gs)) return {res.postal[:5] for res in gs if res.postal[:5].isnumeric()}, postals, nopostals
line = next(in_reader) st = states_by_name[line[3]].abbr county_bound = county_bound_by_fips[st] county_name = county_name_by_fips[st] newline = line[:9] p = Point(float(line[7]), float(line[8])) found = False for fips in county_bound: if p.within(county_bound[fips]): newline = newline + [fips] found = True break if not found: g = geocoder.mapquest( [float(line[8]), float(line[7])], method='reverse', key='iiRjK2GnItDwVgJ9jTDM41TGFmvD3gAo' ) if g.county in county_name.values(): for cfips, cname in county_name.items(): if cname == g.county: newline = newline + [cfips] else: newline = newline + ['_TBD_'] newline = newline + line[-8:] out_writer.writerow(newline) for s in newline[:-1]: all.write('%s\t' % s) all.write('%s\n' % newline[-1]) n = n + 1 print("%04d: %s processed." % (n, rte_in))
def geocode5(address): g = geocoder.mapquest(address) latlng = g.latlng return latlng
import geocoder import csv rows = [] fieldnames = ['Licensee Name', 'DBA', 'License #', 'Street Address', 'City', 'Zip', 'Operation', 'lat', 'lng'] # Change file name to be geocoded with open('pot-cultivation-no-dups.csv') as f: reader = csv.DictReader(f, delimiter=',') for line in reader: g = geocoder.mapquest(line['location']) # Add the CSV line data into the Geocoder JSON result result = g.json result.update(line) # Store Geocoder results in a list to save it later rows.append(result) with open('pot-cultivation-geocoded.csv', 'a') as f: writer = csv.DictWriter(f, fieldnames=fieldnames, extrasaction='ignore') writer.writeheader() writer.writerows(rows) #time.sleep(2)
address = address.replace(" ","") #format postcode list = address.split(', '); postcode = list[len(list)-1] #format station name stationname = str(header[0].contents[0]) stationname = stationname[:-2] except: #error calling url. Continue to next crs code print 'Networkrail ERROR:' + crscode continue try: #geocode postcode. Try arcgis and then mapquest if arcgis fails. g = geocoder.arcgis(postcode) if not g.lat: g = geocoder.mapquest(postcode, key='PXstG2wqhxmTuWThW0lC6RhDWJ89DHTe') line = '"' + crscode +'", "'+ str(g.lat) +'", "'+ str(g.lng) +'", "'+stationname +'", "'\ + postcode +'", "' + operator + '", "'+ address +'"' print line f.write(line+'\n') # python will convert \n to os.linesep except: print 'geocoding ERROR:' + crscode continue f.close()
def test_mapquest(): g = geocoder.mapquest(location) assert g.ok assert g.city == city
def test_mapquest(): g = geocoder.mapquest(location, timeout=10) assert g.ok osm_count, fields_count = g.debug()[0] assert osm_count == 3 assert fields_count == 10
import geocoder import csv #import time rows = [] fieldnames = ['address', 'street_number direction_one street street_type direction_two suite', 'city', 'postal', 'lat', 'lng', 'Price', 'Seller_first_name', 'Seller_last_name', 'Buyer_first_name', 'Buyer_last_name', 'Date'] # Change file name to be geocoded with open('Dubus Excel_12-26-2016.csv') as f: reader = csv.DictReader(f, delimiter=',') for line in reader: g = geocoder.mapquest(line['location'], key='Qb2nRPKta84mwdnWUMI4BEIgQo5y6EAX') # Add the CSV line data into the Geocoder JSON result result = g.json result.update(line) # Store Geocoder results in a list to save it later rows.append(result) with open('home-sales-master-template.csv', 'a') as f: writer = csv.DictWriter(f, fieldnames=fieldnames, extrasaction='ignore') writer.writeheader() writer.writerows(rows) #time.sleep(2)
def geocode(location): try: g = geocoder.mapquest(location, key = 'OX8iJIr1ZJbHLyGHd7p6BygUMCBiFutY') return g.json except: foo(location)
def test_mapquest_reverse(): g = geocoder.mapquest(ottawa, method='reverse', timeout=10) assert g.ok
def test_multi_results(): g = geocoder.mapquest(location, maxRows=3, timeout=10) assert len(g) == 3