Advertisement
Guest User

Untitled

a guest
Jul 18th, 2018
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.33 KB | None | 0 0
  1. import psycopg2
  2. from geopy.geocoders import Nominatim
  3. import os
  4. import googlemaps
  5. import requests
  6. import json
  7. from pandas.io.json import json_normalize
  8. import pandas as pd
  9. from sqlalchemy import create_engine
  10. import sql
  11.  
  12.  
  13.  
  14. # FORWARD GEOCODING: From address to lat/long
  15.  
  16.  
  17. def get_google_results(latlng, api_key=None, return_full_response=False):
  18.     """
  19.    Get geocode results from Google Maps Geocoding API.
  20.    Note, that in the case of multiple google geocode reuslts,
  21.    this function returns details of the FIRST result.
  22.    """
  23.     # Set up your Geocoding url
  24.     geocode_url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng={0}&key={1}'
  25.     request = geocode_url.format(latlng, api_key)
  26.     #if api_key is not None:
  27.         #geocode_url = geocode_url + "&key={}".format(api_key)
  28.     result = {}
  29.     # Ping google for the reuslts:
  30.     #results = requests.get(geocode_url)
  31.     data = json.loads(requests.get(request).text)
  32.     if len(data['results']) > 0:
  33.         result = data['results'][0]
  34.     answer = result
  35.     output = {
  36.         "address_components": answer.get('address_components'),
  37.         "formatted_address": answer.get('formatted_address'),
  38.         "latitude": answer.get('geometry').get('location').get('lat'),
  39.         "longitude": answer.get('geometry').get('location').get('lng'),
  40.         "accuracy": answer.get('geometry').get('location_type'),
  41.         "place_id": answer.get("place_id"),
  42.         "type": ",".join(answer.get('types'))
  43.     }
  44.  
  45.     output['input_string'] = latlng
  46.     output['status'] = result.get('status')
  47.  
  48.     return output
  49.  
  50.     """
  51.    # Results will be in JSON format - convert to dict using requests functionality
  52.    results = results.json()
  53.    #print(results)
  54.    # if there's no results or an error, return empty results.
  55.    if len(results['results']) == 0:
  56.        output = {
  57.            "formatted_address" : None,
  58.            "latitude": None,
  59.            "longitude": None,
  60.            "accuracy": None,
  61.            "google_place_id": None,
  62.            "type": None,
  63.            "postcode": None
  64.        }
  65.    else:
  66.        answer = results['results'][0]
  67.        output = {
  68.            "formatted_address" : answer.get('formatted_address'),
  69.            "latitude": answer.get('geometry').get('location').get('lat'),
  70.            "longitude": answer.get('geometry').get('location').get('lng'),
  71.            "accuracy": answer.get('geometry').get('location_type'),
  72.            "google_place_id": answer.get("place_id"),
  73.            "type": ",".join(answer.get('types')),
  74.            "postcode": ",".join([x['long_name'] for x in answer.get('address_components')
  75.                                  if 'postal_code' in x.get('types')])
  76.        }
  77.  
  78.    # Append some other details:
  79.    output['input_string'] = address
  80.    output['number_of_results'] = len(results['results'])
  81.    output['status'] = results.get('status')
  82.    if return_full_response is True:
  83.        output['response'] = results
  84.  
  85.    return output
  86.    """
  87.  
  88.  
  89. if __name__ == "__main__":
  90.     conn = psycopg2.connect("dbname=mehmed user=postgres password = '' host=localhost")
  91.     cur = conn.cursor()
  92.     return_full_response = False
  93.     api_key = os.environ["GOOGLE_API_KEY"] = "AIzaSyCXzdKgQIiAtBAltTkrN0OXDhl8PUg5dvg"
  94.     #gm = googlemaps.Client(key=api_key)
  95.  
  96.     cur.execute("SELECT latitude, longitude from geocoding")
  97.     latlng = cur.fetchall()
  98.     t = 0
  99.     x = []
  100.     s = []
  101.     s1 = ""
  102.     for l in latlng:
  103.         for a in l:
  104.             s.append(float(a))
  105.         s1 = str(s[0]) + ', ' + str(s[1])
  106.         print(s1)
  107.         x.append(get_google_results(str(s1), api_key, False))
  108.  
  109.         s = []
  110.         if t == 1:
  111.             break
  112.         t = t + 1
  113.  
  114.     df = pd.DataFrame.from_dict(json_normalize(x), orient='columns')
  115.  
  116.     #engine = create_engine('postgresql://localhost:5432')
  117.     #df.to_sql('forward', engine)
  118.     #sql.write_frame(df, 'forward', conn, flavor='postgresql')
  119.     df.to_csv('reverse_geocoding_API.csv', sep = ',')
  120.     print(df['formatted_address'].values)
  121.  
  122.  
  123.     """
  124.    print(df["accuracy"])
  125.    print(df["formatted_address"])
  126.    print(df["google_place_id"])
  127.    print(df["input_string"])
  128.    print(df["latitude"])
  129.    print(df["longitude"])
  130.    print(df["number_of_results"])
  131.    print(df["postcode"])
  132.    print(df["status"])
  133.    print(df["type"])
  134.    """
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement