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 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)
from stravalib.client import Client import pandas as pd from ratelimit import rate_limited from sqlalchemy import create_engine from geocodio import GeocodioClient ONE_MINUTE = 60 chunksize = 10 #Initialize api keys and database connections to use in code STRAVA_API_KEY = os.environ.get('STRAVA_API_KEY') GEOCODIO_API_KEY = os.environ.get('GEOCODIO_API_KEY') client = Client(access_token=STRAVA_API_KEY) geocodio_client = GeocodioClient(GEOCODIO_API_KEY) engine = create_engine( 'postgresql://*****:*****@mydbs.cahzu59qwcbo.us-east-2.rds.amazonaws.com:5432/strava_zillow' ) #bisect_rectange function from: #Author: <Ryan Baumann> #Title: <athletedataviz> #Availability: <https://www.ryanbaumann.com/blog/2016/4/10/on-caching-how-advs-segments-works> def bisect_rectange(numSplits, minlat, minlong, maxlat, maxlong): """Split a lat long bounded rectangle into (numSplits+1)^2 sub-rectangles. Returns a list of arrays containing lat long bounds for sub-rectangles
def get_coordinates(location: str) -> tuple: client = GeocodioClient(CONFIG["geocod"]["key"]) return client.geocode(location).coords
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')
import os import requests import helpers from helpers import myprint, get_database_engine from column_name_mappings import column_name_mappings import pandas as pd from geocodio import GeocodioClient from dotenv import load_dotenv load_dotenv() geocodio_api_key, most_recent_run_url, date_of_run_url = os.getenv( "GEOCODIO_API_KEY"), os.getenv("MOST_RECENT_RUN_URL"), os.getenv( "DATE_OF_RUN_URL") engine, client = get_database_engine( force_cloud=False), GeocodioClient(geocodio_api_key) # updates our postgreSQL database with the data from the most recent scraper run # to re-run the script, replace most_recent_run_url with the API url (in quotes!) for the Apify actor run dataset items that you want def update_database(): latest_jobs = requests.get(most_recent_run_url).json() # use these two lines if you're updating using a local csv file # latest_jobs = pd.read_csv("dataset_apify-dol-actor-AJaB_2022-05-03_22-00-16-286.csv").drop(columns=["Unnamed: 0"]) # latest_jobs = latest_jobs.to_dict('records') if not latest_jobs: myprint("No new jobs.") return myprint(f"There are {len(latest_jobs)} new jobs.")
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 __init__(self, api_key=os.environ.get('GEOCODIO_KEY')): """Initialize Geocodio geocoder class.""" self.client = GeocodioClient(api_key)
df.to_excel(writer, index=False, sheet_name='Sheet1', columns=header) workbook = writer.book worksheet = writer.sheets['Sheet1'] worksheet.set_column('A:A', 15) worksheet.set_column('B:B', 45) worksheet.set_column('C:C', 15) writer.save() os.remove(outCSV) apiKey = getInput("Please enter your Geocodio API Key", str) gc = GeocodioClient(apiKey) outCSV = 'P:/Out_CSV.csv' outExcel = 'P:/Test_Output.xlsx' root = tk() # Hides the TK background window root.withdraw() cancelSel = gui.confirm("Please select your Territory GeoJSON file", "GeoJSON Location", ['OK', 'Cancel']) killProgram(cancelSel) # Select the territory GeoJSON file if version_info.major == 2: # Python 2.x wants the default as the last item. Python 3.x wants it as the first.
addressStreet1 = row[6] addressStreet2 = row[7] city = row[8] state = row[9] zipCode = row[10] extraSpace = "" if addressStreet2 != "": extraSpace = " " query = addressNum + " " + addressStreet1 + extraSpace + addressStreet2 + ", " + city + ", " + state + ", " + zipCode addressLists.append(query) #print(addressLists) print(len(addressLists)) 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)
def _get_client(): client = GeocodioClient(current_app.config['GEOCODIO_API_KEY']) return client
#!/usr/bin/python from flask import Flask, request, jsonify, redirect, url_for from flask_restful import Resource, Api from geocodio import GeocodioClient from pyzomato import Pyzomato import requests.exceptions app = Flask(__name__) api = Api(app) app.config['JSON_SORT_KEYS'] = False #API KEYS client = GeocodioClient('f46ef5bbdcfbbebd4dcc75c5b6cce9767ee744b') zomato = Pyzomato('ac9ae8751e5e53622383740fd5a20d9c') class Home(Resource): def get(self): r = requests.get('https://api.geocod.io/v1.3/geocode') r2 = requests.get('https://developers.zomato.com/api/v2.1/geocode') if(r.status_code == 500): return {'message': "Geocodio is Down. Error code: 500"} elif(r2.status_code == 500): return {'message': "Zomato is Down. Error code: 500"} else: {"about: this is home"} def post(self):
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)
import re import bs4 import requests URL = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vSD3MRGlkbpxYV3agtpCUShQTCDNHqMHm3-' \ 'fw5AEJXcOzm2uNBBMzeVx1IUNeco2NjCAq3vLoC9H2CD/pub?output=csv' r = requests.get(URL) soup = bs4.BeautifulSoup(r.content, 'html5lib') lines = soup.prettify().split('\n') brothers = lines[5:-2] i = 0 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
from flask import Flask, render_template, request import json from geocodio import GeocodioClient, exceptions import re, requests import time #source_url = 'https://waterservices.usgs.gov/nwis/iv/?format=json&bBox=-120.234468,38.864888,-119.195384,40.263760&period=PT2H¶meterCd=00060,00065&siteType=LK,ST&siteStatus=all' app = Flask(__name__) geocodio_client = GeocodioClient('7d7bff58c5fbdf9b5afc0c7dd59d0bddcb0d9db') @app.route("/") @app.route("/resume") def resume(): project_name = 'Resume' return render_template("resume.html", project_name=project_name) @app.route("/rivers") def rivers(): project_name = 'Rivers' return render_template("project.html", project_name=project_name) @app.route('/geocode', methods=['POST']) def geocode(): jsdata = request.form['data'] try: geocode_result = get_coordinates(geocodio_client, jsdata) return_data = json.dumps(geocode_result) return return_data
from pymongo import MongoClient import numpy as np import pandas as pd import json import datetime lob.api_key = #SECRET geocodio_key = #SECRET mongo_user = #SECRET mongo_pwd = #SECRET fake = Faker() fake.add_provider(internet) geocodio = GeocodioClient(geocodio_key) client = MongoClient('mongodb+srv://'+mongo_user+':'+mongo_pwd+'@lasagna-class-project-d.ljwaj.mongodb.net/endless-pastabilities?retryWrites=true&w=majority') def build_requestors(build_num, base_lat, base_long, radius, cohort=None): """ Build Number, Base Latitude, Base Longitude, Radius, Cohort (optional) """ col_names = ['name', 'address', 'city', 'state', 'zip_code', 'email', 'phone', 'special_veg', 'special_vgn', 'special_dairy', 'special_gluten', 'special_nut', 'special_other', 'describe', 'lat', 'long', 'lasagna_mama', 'date_delivered', 'cohort', 'active', 'num_adults', 'num_kids', 'quantity'] df = pd.DataFrame(columns=col_names, index=list(range(build_num)))
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
def init_client(apk): client = GeocodioClient(apk) return client
import os import pandas as pd from geocodio import GeocodioClient import requests import sqlalchemy from colorama import Fore, Style from inspect import getframeinfo, stack import smtplib, ssl from datetime import datetime from pytz import timezone from sqlalchemy import create_engine from dotenv import load_dotenv load_dotenv() geocodio_api_key = os.getenv("GEOCODIO_API_KEY") client = GeocodioClient(geocodio_api_key) # when this is True we will only check for accuracy jobs located in `our_states` state_checking = True our_states = ["texas", "tx", "kentucky", "ky", "tennessee", "tn", "arkansas", "ar", "louisiana", "la", "mississippi", "ms", "alabama", "al"] # prints `message` in red def print_red(message): print(Fore.RED + message + Style.RESET_ALL) # prints `message` along with the file and line info where from which the print function was called # if is_red=="red", the message will be printed in red # if emai_also=="yes", an email will be sent as well def myprint(message, is_red="", email_also=""): try: if email_also != "yes":
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", })
from flask import url_for from geocodio import GeocodioClient from pyzomato import Pyzomato import requests import json #Flask app setup app = Flask(__name__) app.secret_key = 'Secret Key' #API keys zKey = '3637e5d5a1b6d7c7ab4aae535a508b13' geoKey = '7dff5f5b70e753fe777774b74004fb73e3f3037' zClient = Pyzomato(zKey) geoClient = GeocodioClient(geoKey) @app.route('/', methods=["POST", "GET"]) def homePage(): if request.method == 'GET': return render_template('index.html') else: address = request.form['address'] try: location = geoClient.geocode(address) return getRestaurants(address) except: flash('Please enter a valid address') return redirect('/')
"""This script is used for implementing the most recent address fixes from the PostgreSQL low_accuracies table.""" import os import helpers from helpers import myprint, print_red_and_email, make_query, get_database_engine, handle_null import pandas as pd from geocodio import GeocodioClient from dotenv import load_dotenv load_dotenv() geocodio_api_key = os.getenv("GEOCODIO_API_KEY") engine, client = get_database_engine( force_cloud=True), GeocodioClient(geocodio_api_key) # fixed is a DataFrame of low_accuracies table rows that have been fixed def implement_fixes(fixed, fix_worksites=False): # worksite_or_housing is a string - either "worksite" or "housing" # sets the "{worksite_or_housing}_fixed_by", "fixed" columns to failed, False in the i-th row of df def mark_as_failed(i, worksite_or_housing, df): df.at[i, f"{worksite_or_housing}_fixed_by"] = "failed" df.at[i, "fixed"] = False # worksite_or_housing is a string - either "worksite" or "housing" # overwrites the geocoding results columns of the i-th row in df based on its worksite_or_housing address columns # if the geocoding of the new address columns results in accuracy too low or an accuracy type in helpers.bad_accuracy_types, marks the row as failed def fix_by_address(i, row, worksite_or_housing, df): if worksite_or_housing == "worksite": full_address = helpers.create_address_from(
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
!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:
@author: Leonardo Roman 11/17/2018 RESTful api that performs sequential API calls to two RESTful servers. This python application performs GET respose by accepting an address string as parameter and uses it to perform a GET call to Geocode.io API in order to get the coordinates of given address. After getting such coordinates, another API call is perform to Zomato.io API in order to get the 20th nearest restaurants around. The data obtained from Zomato is then cleaned up and return back to the user in the original GET request to this application. """ from flask import Flask, request, Response, json from geocodio import GeocodioClient from pyzomato import Pyzomato # from pyspark import SparkContext # GIOCODE API KEY: geocode_client = GeocodioClient('API KEY') # ZOMATO API KEY: zomato_client = Pyzomato('API KEY') app = Flask(__name__) @app.route("/restaurant") def start(): data = {'route': 'restaurant', 'echo': 'GET'} js = json.dumps(data) resp = Response(js, status=200, mimetype='application/json') resp.headers['Link'] = 'http://luisrei.com' return resp @app.route("/restaurant/<address>", methods=['GET'])
""" Views for the board app """ from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth.decorators import login_required import requests from authentication.models import UserProfile from geocodio import GeocodioClient from .models import Event, Musician_Advertisement, EventApplication, AdApplication from .forms import EventForm, AdForm # pylint: disable=invalid-name client = GeocodioClient('2f48b44cbca3558fcc7888282c4824b54ce88bf') # Create your views here. @login_required def board(request): """ Let a logged in user see the board page """ # pylint: disable=unused-variable user = request.user return render(request, 'board/board.html') def event_submit(request): """ Allows for the submission for a one-time event listing """
from geocodio import GeocodioClient client = GeocodioClient('e7da75f3ee9ab5dc5ec5eb557c91adffb5529e5') geocoded_location = client.geocode("42370 Bob Hope Drive, Rancho Mirage CA") print(f'{geocoded_location.coords}') #get codinates geocoded_addresses = client.geocode([ '2 15th St NW, Washington, DC 20024', '3101 Patterson Ave, Richmond, VA, 23221' ]) print(f"{geocoded_addresses.coords}") print(f"{geocoded_addresses[0].coords}") print(f'{geocoded_addresses[1].coords}') # get co-ordinates cord = geocoded_addresses.get('2 15th St NW, Washington, DC 20024').coords print(f'{cord}') #parsing address par = client.parse('1600 Pennsylvania Ave, Washington DC') print(f'{par}') #Find matching address location = client.reverse((56.58, -15.40)) addre = location.formatted_address print(f'{addre}') #Find multiple address locations = client.reverse([