class Geocoder(object): def __init__(self, API_KEY=None): if not API_KEY: # get keys from os.environ, because we may not have current_app context API_KEY = os.environ.get('GEOCODE_API_KEY') self.client = GeocodioClient(API_KEY) def zipcode(self, zipcode, cache=None): if cache: districts = cache.get_district(zipcode) if len(districts) == 1: d = districts[0] d['source'] = 'local district cache' return Location(d) else: # TODO, how to handle districts that span states? return self.geocode(zipcode) else: return self.geocode(zipcode) def geocode(self, address): results = self.client.geocode(address).get('results') if not results: return None else: return Location(results[0]) def reverse(self, latlon): results = self.client.reverse(latlon).get('results') if not results: return None else: return Location(results[0])
def geocode(self, *args, **kwargs): """ Geocodes the object. Uses either a `get_display_address` method on the object or the arguments provided. :returns: the object itself """ separator = kwargs.pop('separator', ', ') save = kwargs.pop('save', True) if hasattr(self, 'get_display_address'): address = self.get_display_address() elif not args: raise ValueError("Must provide field names for address display if no" " get_display_address method is present") else: address = separator.join([getattr(self, arg) for arg in args]) client = GeocodioClient(settings.GEOCODIO_API_KEY) result = client.geocode(address) # TODO handle None self.point = decimal.Decimal(str(result.coords[0])), decimal.Decimal(str(result.coords[1])) if save: self.save() return self.point
def geocode_address(address): """Geocode an address Take an address, send it to Geocode.io, and return a result for use in the app. Ensure that it's a US address in a state (or DC) we support. Args: address: unicode address Returns: (Created Boolean, GeoLookup object) Tuple """ # If we've looked up this address before, use the result we got lookup_object = GeoLookup.objects.filter(lookup=address[:255]).first() if lookup_object: geocode_response = lookup_object.response created = False else: geocodio_client = GeocodioClient(settings.GEOCODIO_KEY) # If the address is bad or not detailed enough, this will raise a # GeocodioDataError. We should catch that and pass it up as a # validation error like we do with all other validation exceptions try: geocode_response = geocodio_client.geocode( address, fields=['cd116', 'stateleg', 'timezone']) except GeocodioDataError as error: raise ValidationError(unicode(error)) # Save the response as a GeoLookup to save us from hitting the geocode # service for the same addresses over-and-over (this is most helpful # for zipcodes) lookup_object = GeoLookup(lookup=address[:255], response=geocode_response) lookup_object.save() created = True # Sometimes Geocode.io can parse the address but cannot find it on a map. # In those cases, return a ValidationError and let some other method handle # it. if len(geocode_response.get('results')) == 0: raise ValidationError( 'Address could not be found. Try a valid zipcode or state.') result = geocode_response['results'][0] address_components = result['address_components'] # Geocod.io supports some other countries (like Canada) but we don't. if address_components.get('country') != 'US': raise ValidationError('Not a US Address') # We only support some states in the app. If you try to import someone from # a territory reject the input. if address_components.get('state') not in dict(STATES).keys(): raise ValidationError('Not a supported US state (or DC)') return (created, lookup_object)
def getLatLongFromAddress(address): client = GeocodioClient(config.GEOCODE_KEY) returned = client.geocode(address) print() print(returned) location = returned['results'][0]['location'] latitude = location['lat'] longitude = location['lng'] return latitude, longitude
def forecast(): if request.method == 'POST': project_path = request.form['address'] user_agent = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0' } geo_client = GeocodioClient(os.getenv('GEOCODIO_KEY')) try: location1 = geo_client.geocode(project_path) coords = location1.coords try: url = 'https://api.weather.gov/points/' + str( coords[0]) + ',' + str(coords[1]) except: return "National Weather Service lookup failed." sys.exit(1) except: return "Location not found. Please ensure the address was entered correctly." sys.exit(1) data = requests.get(url, headers=user_agent) location_data = data.json() cwa = location_data['properties']['cwa'] location_url = location_data['properties']['forecast'] forecast = requests.get(location_url) forecast_json = forecast.json() wfo = csv.reader(open('wfo.csv', "r"), delimiter=",") for row in wfo: if cwa == row[0]: wfo_info = row[0] + ' - ' + row[1] forecast_day_list = [] forecast_list = [] # Retrieves 7 days and 7 nights of forecasts. for x in range(0, 14): forecast_day = str( forecast_json['properties']['periods'][x]['name']) forecast_day_list.append(forecast_day) forecast = str( forecast_json['properties']['periods'][x]['detailedForecast']) forecast_list.append(forecast) return render_template('forecast.html', forecast=forecast_list, forecast_day=forecast_day_list, wfo=wfo_info)
def bulk_geocode(qs, *args, **kwargs): """ Geocodes a queryset in bulk The goal is to minimize the number of API calls :returns: the slice of the queryset provided that was geocoded. """ separator = kwargs.pop('separator', ', ') def location_name(location): # IF qs.model has attr 'get_display_address, use that if hasattr(qs.model, 'get_display_address'): return location.get_display_address() return separator.join([getattr(location, arg) for arg in args]) client = GeocodioClient(settings.GEOCODIO_API_KEY) geocoded_addresses = client.geocode([location_name(location) for location in qs]) with transaction.commit_on_success(): for location in qs: location.point = geocoded_addresses.get(location_name(location)).coords location.save() # TODO return only portion of the qs that was geocoded return qs
def restaurants(): address = request.args.get('address') if not address: return "Bad Request!<br>Address parameter is empty or invalid." client = GeocodioClient('e69dd65d59f64d56bb99e5fea55f5b1d999a696') zomato = Pyzomato('188eda180987998d1dd37a7b93fee08a') location = client.geocode(address) # .coords to get lat and lng right away lat = location['results'][0]['location']['lat'] # parsing json lng = location['results'][0]['location']['lng'] zomatoData = zomato.getByGeocode(lat, lng) output = { 'restaurants': [] } for r in zomatoData['nearby_restaurants']: output['restaurants'].append(dict({'name': r['restaurant']['name'], 'address': r['restaurant']['location']['address'], 'cuisines:': r['restaurant']['cuisines'], 'rating': r['restaurant']['user_rating']['aggregate_rating'] })) print(output) return jsonify(output)
def geocode(request): from geocodio import GeocodioClient from geocodio.exceptions import GeocodioDataError # HACK from geocodio.client import ALLOWED_FIELDS ALLOWED_FIELDS.append("cd115") # HACK # Look up address or coordinate. client = GeocodioClient(settings.GEOCODIO_API_KEY) try: if "address" in request.POST: info = client.geocode(request.POST["address"], fields=["cd115"]) elif "latitude" in request.POST: info = client.reverse_point(float(request.POST["latitude"]), float(request.POST.get( "longitude", "")), fields=["cd115"]) else: return JsonResponse({ 'status': 'error', 'message': 'invalid query' }) result = info["results"][0] except (ValueError, GeocodioDataError, IndexError): return JsonResponse({ 'status': 'error', 'message': 'The location was not understood.' }) # Extract fields from result. coord = result["location"] address = result["formatted_address"] state = result["address_components"].get("state") if state not in state_apportionment: return JsonResponse({ 'status': 'error', 'message': 'The location does not seem to be in the United States.' }) if "fields" not in result: return JsonResponse({ 'status': 'error', 'message': 'We could not determine the congressional district for that location.' }) dist = result["fields"]["congressional_district"]["district_number"] if dist in (98, 99): dist = 0 if (state_apportionment[state] in ("T", 1) and dist != 0) \ or (state_apportionment[state] not in ("T", 1) and not (1 <= dist <= state_apportionment[state])): raise ValueError("Hmm. We got back invalid data. " + repr(request.POST) + " -- " + repr(info)) cd = "%s%02d" % (state, dist) # Return. return JsonResponse({ 'status': 'ok', 'coord': coord, 'address': address, 'city': result["address_components"].get("city"), 'cd': cd, 'state': state_names[state], 'district_html': ordinal_html(dist) if dist > 0 else "At Large", })
def sms(): account_sid = os.getenv('ACCOUNT_SID') auth_token = os.getenv('AUTH_TOKEN') client = Client(account_sid, auth_token) if request.method == 'POST': number = "+1" + request.form['number'] project_path = request.form['address'] user_agent = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0' } geo_client = GeocodioClient(os.getenv('GEOCODIO_KEY')) try: location1 = geo_client.geocode(project_path) coords = location1.coords try: url = 'https://api.weather.gov/points/' + str( coords[0]) + ',' + str(coords[1]) except: return "National Weather Service lookup failed." sys.exit(1) except: return "Location not found. Please ensure the address was entered correctly." sys.exit(1) data = requests.get(url, headers=user_agent) location_data = data.json() cwa = location_data['properties']['cwa'] location_url = location_data['properties']['forecast'] forecast = requests.get(location_url) forecast_json = forecast.json() forecast_day_list = [] forecast_list = [] for x in range(0, 4): forecast_day = str( forecast_json['properties']['periods'][x]['name']) forecast_day_list.append(forecast_day) forecast = str( forecast_json['properties']['periods'][x]['detailedForecast']) forecast_list.append(forecast) custom = [] custom.append(forecast_day_list[0]) custom.append(forecast_list[0]) custom.append(forecast_day_list[1]) custom.append(forecast_list[1]) custom.append(forecast_day_list[2]) custom.append(forecast_list[2]) custom.append(forecast_day_list[3]) custom.append(forecast_list[3]) body = ("Here's your weather report for " + project_path + ": " + "\n\n" + custom[0] + ': ' + custom[1] + '\n\n' + custom[2] + ': ' + custom[3] + "\n\n" + custom[4] + ': ' + custom[5] + '\n\n' + custom[6] + ': ' + custom[7] + "\n\n" + "Enjoy your day!") message = client.messages \ .create( body=body, from_='+12058945876', to=number ) return render_template('weather.html')
class GeocodioCoder(): """Geocodio geocoder class.""" def __init__(self, api_key=os.environ.get('GEOCODIO_KEY')): """Initialize Geocodio geocoder class.""" self.client = GeocodioClient(api_key) @staticmethod def _format_result(address, geocoding_result): """Format an address and geocoding result for use throughout the application.""" try: return { 'address': address, 'latitude': geocoding_result['results'][0]['location']['lat'], 'longitude': geocoding_result['results'][0]['location']['lng'], } except (IndexError, KeyError): pass try: return { 'address': address, 'latitude': geocoding_result.coords[0], 'longitude': geocoding_result.coords[1], } except Exception as error: logger.warning(error) logger.warning(geocoding_result) return None def geocode(self, address): """Geocode a single point with Geocodio.""" result = self._safe_geocode(address) if result: return GeocodioCoder._format_result(address=address, geocoding_result=result) return None def geocode_batch(self, addresses): """ Geocode a list of addresses with Geocodio. Returns a list of dictionaries with address, latitude, and longitude. The results are returned in the same order as the original list. """ try: results = self._safe_geocode(addresses) except GeocodioError as error: logger.error(error.__class__.__name__ + ' - ' + str(error)) results = [] if len(addresses) == 0: return [] if results: geocoded_addresses = [ GeocodioCoder._format_result( address=address, geocoding_result=results.get(address)) for address in addresses if results.get(address) and results.get(address).coords ] else: logger.warning( 'Error in batch geocoding - switching to single geocoding.') with multiprocessing.dummy.Pool(processes=MAX_THREADS) as executor: geocoded_addresses = executor.map(self.geocode, addresses) return [ geocoded_address for geocoded_address in geocoded_addresses if geocoded_address ] def _safe_geocode(self, addresses): if isinstance(addresses, (list, set)): if len(addresses) > 1000: raise GeocodioError( 'Too many addresses. Switch to single geocoding.') try: return self.client.geocode(list(addresses)) except GeocodioError as error: logger.info('Error {} - in geocoding batch.'.format( error.__class__.__name__)) else: try: return self.client.geocode(addresses) except (GeocodioAuthError, GeocodioDataError, GeocodioServerError) as error: logger.debug('Error {} - in geocoding address {}.'.format( error.__class__.__name__, addresses)) return None
class LocationManager(GraphManager): def __init__(self, *args, **kwargs): self._smarty_auth_id = getattr(settings, 'SMARTY_STREETS_AUTH_ID', None) self._smarty_auth_token = getattr(settings, 'SMARTY_STREETS_AUTH_TOKEN', None) api_key = getattr(settings, 'GEOCODIO_API_KEY', None) if api_key is None: warn('No Geocodio API key found. Will not able to geocode.') self._geocode_client = None else: self._geocode_client = GeocodioClient(api_key) super(LocationManager, self).__init__(*args, **kwargs) @staticmethod def _update_address_location(address, geocode_result): #TODO: More robust error handling for bad geocodio requests coords = geocode_result.coords if coords and len(coords) == 2: address.latitude = coords[0] address.longitude = coords[1] address.save() else: raise GeocodingError('Could not get results from Geocodio') def geocode_address(self, address): """ Looks up an address, finds its latitude and longitude and generates the appropriate geohashes :return: """ if self._geocode_client is None: raise ImproperlyConfigured('Cannot geocode address as the Geocodio client is not properly configured') result = self._geocode_client.geocode(address.formatted_address) self._update_address_location(address, result) def geocode_addresses(self, addresses): """ For geocoding a batch of addresses :return: """ if self._geocode_client is None: raise ImproperlyConfigured('Cannot geocode address as the Geocodio client is not properly configured') formatted_addresses = [address.formatted_address for address in addresses] results = self._geocode_client.geocode(formatted_addresses) for result, address in zip(results, addresses): try: self._update_address_location(address, result) except GeocodingError: logger.error('Could not geocode results for address <%s>' % address.formatted_address) @staticmethod def _prepare_smarty_streets_input(address): smarty_input = { 'street': address.line_1, 'street2': address.line_2, 'city': address.city, 'state': address.state, 'zipcode': address.zip_code } if smarty_input.get('street2') is None: del smarty_input['street2'] return smarty_input def get_address_delivery_barcode(self, address): smarty_input = self._prepare_smarty_streets_input(address) smarty_url = 'https://api.smartystreets.com/street-address' smarty_input['auth-id'] = self._smarty_auth_id smarty_input['auth-token'] = self._smarty_auth_token r = requests.get(smarty_url, params=smarty_input) if r.status_code != 200: #TODO: More robust error handling for bad smarty streets requests pass response = r.json() for result in response: if result.get('input_index') == 0: address.delivery_point_barcode = result.get('delivery_point_barcode') address.save()
def get_coordinates(location: str) -> tuple: client = GeocodioClient(CONFIG["geocod"]["key"]) return client.geocode(location).coords
geoFile = open('newBrothers.geojson', 'w') geoFile.write('{"type":"FeatureCollection","features":[\n') client = GeocodioClient("0c410ad5ac00a2e7a055ade70475c465605a6ed") geo_pattern = re.compile("'lat': -*[0-9]+.[0-9]+, 'lng': -*[0-9]+.[0-9]+") num_pattern = re.compile("-*[0-9]+.[0-9]+") for brother in brothers: print(brother) i += 1 try: data = brother.split(',') zip_code = int(data[1].strip("'")) name = data[2].strip("'") try: location = client.geocode(zip_code) geo = re.search(geo_pattern, str(location)) nums = re.findall(num_pattern, geo.group()) lat = nums[0].strip("'") # this is a string lng = nums[1].strip("'") # this is a string # now to take the lat, long, and name and to build the .geojson... geoLine = '\t{"type":"Feature","geometry":{"type":"Point","coordinates":[' + \ lng + ',' + lat + ']},"properties":{"title":"' + name + '"}}' if i < len(brothers): geoLine += ',\n' geoFile.write(geoLine) print(str(i) + " wrote geoFile line") except GeocodioDataError: print('Could not process ' + name + '\nPlease check zip code: ' + zip_code + '\n')
def clean_data(df): # setup dataframe temp = df.copy() temp['Cleaned Location'] = temp['Cleaned Location'].fillna('') # set up api keys to be used api_keys = [ 'b42752c85bb22c5b5e924be26276bb246257c25', 'bb553e0bbff5b333b8bb9555a93b976f55e3e35', 'e3b53edefba3e7a34673473470bf4a5e0fb765e', '6589fabe9f95daba2a255e9eb21fe111a55959a', 'a27856bccaec6b36eba866877e60262bc83e535', '5611b20511d00d6365e6eb10b51e1e0e562a02e' ] current_key = 0 client = GeocodioClient(api_keys[current_key]) print('using key:', api_keys[current_key]) for i, row in temp.iterrows(): # if data is already processed skip if temp.loc[i,'Error'] == False or temp.loc[i,'Error'] == True: continue # if the cleaned location is empty, set up the address to be cleaned if not temp.loc[i,'Cleaned Location']: temp.loc[i,'Cleaned Location'] = temp.loc[i,'Location'] # add Milwaukee, WI to address if not already present if 'MILWAUKEE, WI' not in temp.loc[i,'Cleaned Location']: if 'MKE' in temp.loc[i,'Cleaned Location']: temp.loc[i,'Cleaned Location'] = temp.loc[i,'Cleaned Location'].replace('MKE',' MILWAUKEE, WI') else: temp.loc[i,'Cleaned Location'] = temp.loc[i,'Cleaned Location']+ ', MILWAUKEE, WI' # clean addresses of common abbreviations and typos temp.loc[i,'Cleaned Location'] = address_dictionary_1(temp.loc[i,'Cleaned Location']) # loop through api keys until a key works, otherwise save data while len(api_keys) > current_key: try: # get and record coordinates of given address geocoded_location = client.geocode(temp.loc[i,'Cleaned Location']) break except: current_key += 1 if len(api_keys) <= current_key: print('no more keys remaining...') return temp client = GeocodioClient(api_keys[current_key]) print('using next key: ', api_keys[current_key]) # check whether data exists (works perfectly fine, but can be improved) if len(geocoded_location['results']) > 0: coordinates = dict(geocoded_location['results'][0]['location']) temp.loc[i,'Latitude'] = coordinates['lat'] temp.loc[i,'Longitude'] = coordinates['lng'] temp.loc[i,'Error'] = False # log errors else: temp.loc[i,'Error'] = True return temp
client = None if runAPI: client = GeocodioClient("a60b68a3bcaa9a0b368a6660098b5aa35855906") latlonFile = "parkingGarageFile1.csv" with open(latlonFile, 'wb') as csvfile: latlonwriter = csv.writer(csvfile, delimiter=',') i = 0 for address in addressLists: if i < 650: i += 1 continue if i % 100 == 0: print("\n\n" + "Completed " + str(i) + " queries\n\n") i += 1 geocoded_location = None if runAPI: geocoded_location = client.geocode(address) if geocoded_location is None: continue coords = geocoded_location.coords if coords is None: continue print(coords) latlonwriter.writerow([address, coords[0], coords[1]]) #client = GeocodioClient("a60b68a3bcaa9a0b368a6660098b5aa35855906") #for address in addressLists: # geocoded_location = client.geocode(address)
def locater(request, tabnum): if tabnum == 1: activeTab = "emplist_tab" elif tabnum == 2: activeTab = "worksites_tab" else: activeTab = "emphomelist_tab" form1 = SiteDropDownForm(request.POST or None) sitesList = WorkSiteLocations.workSitesByLocationList.sites_info() map_js = [] response = "" if ('locations_info' in request.session) and ('state_list' in request.session): locations_info = request.session['locations_info'] state_list = request.session['state_list'] else: loc_list = [] state_list = [] locations_info = [] client = GeocodioClient(GEOCODIO_API_KEY) infoLists = EmployeeData.empZipCodeList.filter_list() zipList = infoLists[0] empByZipList = infoLists[1] try: response = client.geocode(zipList) for resp_dict in response: for dk1, dv1 in resp_dict.items(): if dk1 == 'results': d = {} result_dicts = dv1[0] addr_comp = result_dicts.get('address_components') d['state'] = addr_comp.get('state') d['zip'] = addr_comp.get('zip') d['lat'] = result_dicts.get('location').get('lat') d['long'] = result_dicts.get('location').get('lng') loc_list.append(d) d1 = {d['zip']:d for d in loc_list} final_loc_list = [dict(d, **d1.get(d['zip'], {})) for d in empByZipList] temp = defaultdict(list) for item in final_loc_list: temp[item['state']].append(item) loc_groups = dict(temp) for dk2, dv2 in loc_groups.items(): state_name = str(us.states.lookup(dk2)) state_list.append(state_name) locations_info.append({state_name:dv2}) request.session['state_list'] = state_list request.session['locations_info'] = locations_info except Exception as e: response = "error" print(response) if response == "error": error_html = "var error_html = '<br><br><br><br><h3>An error occurred, and the map is unavailable at this time</h3><lead>Please check back later.</lead>';" error_js = "$('#leaflet-maps').append(error_html);" map_js.append(error_html) map_js.append(error_js) else: map_js = get_map_js(locations_info) if request.method == 'POST': site_ID = request.POST.get('site') request.session['site_ID'] = site_ID else: if 'site_ID' in request.session: site_ID = request.session['site_ID'] form1.fields['site'].initial = site_ID else: site_ID = 1 employee_list = EmployeeData.empListByWorkSite.emp_list(site_ID) page = request.GET.get('page', 1) paginator = Paginator(employee_list, 10) try: empList = paginator.page(page) except PageNotAnInteger: empList = paginator.page(1) except EmptyPage: empList = paginator.page(paginator.num_pages) maps_js_code = ' '.join(map_js) context = {"locater_page":"active","jobaid_menu":"active",activeTab:"active","sitesList":sitesList,"empList":empList,'form1':form1, "state_list":state_list,"maps_js_code":maps_js_code} return render(request, 'departments/locater.html', context)
from requests.packages.urllib3.exceptions import InsecurePlatformWarning requests.packages.urllib3.disable_warnings() start_time = time.time() printToLog("Start: " + strftime("%Y-%m-%d %H:%M:%S") + "\n") with open(inCSV, 'r') as inFile: reader = csv.DictReader(inFile, delimiter=',', quotechar='"') for row in reader: # Cat address and defined state for geocoding catAddr = row['address'] + " " + stateVar kmlAddr = row['address'] # used for printing to fail log # Run above list through Geocodio, return coords in Lat/Long geoResult = gc.geocode(catAddr).coords # I had to either append [::-1] to the above to reverse it inline, or do so later. # I need to cut out the Long/Lat in the next two for boundary checks. # I decided this way was easier to read, albeit not as compact. reverseGeo = geoResult[::-1] # Slice the string into two parts, cast it to a string, then to a float to compare. # Yes, this is horrendously ugly. floatGeoLong = float( str(reverseGeo[1:]).replace('(', '').replace(')', '').replace(',', '')) floatGeoLat = float( str(reverseGeo[:1]).replace('(', '').replace(')', '').replace(',', ''))
def clean_data(df): # setup dataframe and geocodio client temp = df.copy() client = GeocodioClient("b42752c85bb22c5b5e924be26276bb246257c25") # add additional columns temp['Cleaned_Location'] = temp['Location'] temp['Coordinates'] = '' temp['Error_Logging'] = '' # retrieve all addresses previously geocoded coordinate_df = pd.read_csv('Coordinate_Dictionary.csv') for i, row in temp.iterrows(): # use address dictionary for coordinates if location exists in address dictionary location = temp.loc[i, 'Location'] if location in coordinate_df['Location'].unique(): temp.loc[i, 'Cleaned_Location'] = coordinate_df.loc[ coordinate_df['Location'] == location, 'Cleaned_Location'].iloc[0] temp.loc[i, 'Coordinates'] = coordinate_df.loc[ coordinate_df['Location'] == location, 'Coordinates'].iloc[0] continue # add milwaukee, WI to address if not already present if 'MKE' in temp.loc[i, 'Cleaned_Location']: temp.loc[i, 'Cleaned_Location'] = temp.loc[ i, 'Cleaned_Location'].replace('MKE', ' MILWAUKEE, WI') else: temp.loc[i, 'Cleaned_Location'] = temp.loc[ i, 'Cleaned_Location'] + ', MILWAUKEE, WI' # clean addresses of common abbreviations and typos temp.loc[i, 'Cleaned_Location'] = address_dictionary_1( temp.loc[i, 'Cleaned_Location']) # get and record coordinates of given address try: geocoded_location = client.geocode(temp.loc[i, 'Cleaned_Location']) # catch error when our api key has run out of calls except: print('No calls remaining...') # save all geocoded addresses temp = temp.loc[0:i - 1, :] coordinate_df.to_csv('Coordinate_Dictionary.csv', index=False, mode='w') return temp # check whether data exists (works perfectly fine, but can be improved) if len(geocoded_location['results']) > 0: coordinates = str(geocoded_location['results'][0]['location']) # add new coordinates to coordinate dictionary coordinate_entry = pd.DataFrame({ 'Location': [temp.loc[i, 'Location']], 'Cleaned_Location': [temp.loc[i, 'Cleaned_Location']], 'Coordinates': [coordinates] }) coordinate_df = coordinate_df.append(coordinate_entry, ignore_index=True) # log errors else: coordinates = '' temp.loc[i, 'Error_Logging'] = str(geocoded_location) error = pd.DataFrame({ 'location': [temp.loc[i, 'Location']], 'cleaned_location': [temp.loc[i, 'Cleaned_Location']], 'geocoding_result': [temp.loc[i, 'Error_Logging']] }) error.to_csv('../geocoding_data/Error_Logging.csv', mode='a', header=False) temp.loc[i, 'Coordinates'] = coordinates coordinate_df.to_csv('Coordinate_Dictionary.csv', index=False, mode='w') return temp
from geocodio import GeocodioClient import os from dotenv import load_dotenv load_dotenv() GEOCODIO_API_KEY = os.getenv("GEOCODIO_API_KEY") client = GeocodioClient(GEOCODIO_API_KEY) geocoded_addresses = client.geocode(["2405 Legislative Drive, Regina, SK"]) # print(geocoded_addresses) print(geocoded_addresses.coords) print(geocoded_addresses[0].coords) locations = client.reverse([(45.61625, -61.630912), (43.685815, -79.759934)]) print(locations.formatted_addresses)
!pip install pygeocodio #Basic usage #Import the API client and ensure you have a valid API key: from geocodio import GeocodioClient client = GeocodioClient(YOUR_API_KEY) #Geocoding #Geocoding an individual address: geocoded_location = client.geocode("42370 Bob Hope Drive, Rancho Mirage CA") geocoded_location.coords (33.738987255507, -116.40833849559) #Batch geocoding #You can also geocode a list of addresses: geocoded_addresses = client.geocode([ '2 15th St NW, Washington, DC 20024', '3101 Patterson Ave, Richmond, VA, 23221' ]) #Return a list of just the coordinates for the resultant geocoded addresses: >>> geocoded_addresses.coords [(38.890083, -76.983822), (37.560446, -77.476008)] >>> geocoded_addresses[0].coords (38.890083, -76.983822), (37.560446, -77.476008) #Lookup an address by queried address:
from geocodio import GeocodioClient client = GeocodioClient('7d7bff58c5fbdf9b5afc0c7dd59d0bddcb0d9db') location = client.geocode('truckee') print(location.coords)