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
- # FORWARD GEOCODING: From address to lat/long
- def get_google_results(latlng, api_key=None, return_full_response=False):
- """
- 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')
- return output
- """
- # Results will be in JSON format - convert to dict using requests functionality
- results = results.json()
- #print(results)
- # if there's no results or an error, return empty results.
- if len(results['results']) == 0:
- output = {
- "formatted_address" : None,
- "latitude": None,
- "longitude": None,
- "accuracy": None,
- "google_place_id": None,
- "type": None,
- "postcode": None
- }
- else:
- answer = results['results'][0]
- output = {
- "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'),
- "google_place_id": answer.get("place_id"),
- "type": ",".join(answer.get('types')),
- "postcode": ",".join([x['long_name'] for x in answer.get('address_components')
- if 'postal_code' in x.get('types')])
- }
- # Append some other details:
- output['input_string'] = address
- output['number_of_results'] = len(results['results'])
- output['status'] = results.get('status')
- if return_full_response is True:
- output['response'] = results
- 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"] = "AIzaSyCXzdKgQIiAtBAltTkrN0OXDhl8PUg5dvg"
- #gm = googlemaps.Client(key=api_key)
- cur.execute("SELECT latitude, longitude from geocoding")
- latlng = cur.fetchall()
- t = 0
- x = []
- s = []
- s1 = ""
- for l in latlng:
- for a in l:
- s.append(float(a))
- s1 = str(s[0]) + ', ' + str(s[1])
- print(s1)
- x.append(get_google_results(str(s1), api_key, False))
- 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_API.csv', sep = ',')
- print(df['formatted_address'].values)
- """
- 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