Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import psycopg2
- from geopy.geocoders import Nominatim
- import os
- import googlemaps
- import requests
- import json
- from pandas.io.json import json_normalize
- import pandas as pd
- from sqlalchemy import create_engine
- import sql
- import difflib
- # REVERSE GEOCODING: From lat/long to address
- def get_google_results(latlng, api_key=None, return_full_response=False, sp=None):
- """
- Get geocode results from Google Maps Geocoding API.
- Note, that in the case of multiple google geocode reuslts,
- this function returns details of the FIRST result.
- """
- # Set up your Geocoding url
- geocode_url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng={0}&key={1}'
- request = geocode_url.format(latlng, api_key)
- #if api_key is not None:
- #geocode_url = geocode_url + "&key={}".format(api_key)
- result = {}
- # Ping google for the reuslts:
- #results = requests.get(geocode_url)
- data = json.loads(requests.get(request).text)
- if len(data['results']) > 0:
- result = data['results'][0]
- answer = result
- output = {
- "address_components": answer.get('address_components'),
- "formatted_address": answer.get('formatted_address'),
- "latitude": answer.get('geometry').get('location').get('lat'),
- "longitude": answer.get('geometry').get('location').get('lng'),
- "accuracy": answer.get('geometry').get('location_type'),
- "place_id": answer.get("place_id"),
- "type": ",".join(answer.get('types'))
- }
- output['input_string'] = latlng
- output['status'] = result.get('status')
- output['license'] = sp
- return output
- if __name__ == "__main__":
- conn = psycopg2.connect("dbname=mehmed user=postgres password = '' host=localhost")
- cur = conn.cursor()
- return_full_response = False
- api_key = os.environ["GOOGLE_API_KEY"] = "KEY"
- #gm = googlemaps.Client(key=api_key)
- cur.execute("SELECT distinct on (location) location, license from businesses where location is not null limit 595")
- latlng = cur.fetchall()
- t = 0
- x = []
- s = []
- s1 = ""
- sp = ''
- br = 0
- for l in latlng:
- for a in l:
- if br < 1:
- s.append(a)
- else:
- sp = a
- br = br + 1
- br = 0
- s1 = str(s)
- s1 = s1[3:-3]
- x.append(get_google_results(s1, api_key, False, sp))
- sp = ''
- s = []
- if t == 1:
- break
- t = t + 1
- df = pd.DataFrame.from_dict(json_normalize(x), orient='columns')
- #engine = create_engine('postgresql://localhost:5432')
- #df.to_sql('forward', engine)
- #sql.write_frame(df, 'forward', conn, flavor='postgresql')
- df.to_csv('reverse_geocoding_APIx13.csv', sep = ',')
- print(df.columns)
- """
- print(df["accuracy"])
- print(df["formatted_address"])
- print(df["google_place_id"])
- print(df["input_string"])
- print(df["latitude"])
- print(df["longitude"])
- print(df["number_of_results"])
- print(df["postcode"])
- print(df["status"])
- print(df["type"])
- """
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement