Recently a friend asked me to help in a project, the project was to get postal code of any location in response to coordinates given , I gave him the following code;;
import json
import time
import urllib.error
import urllib.parse
import urllib.request
import pandas as pd
import requests
import logging
import time
Coordinates = []
Coordinates = pd.read_csv("D:/Tutorials/Geocoding/Long_Lat_B7.csv")
print(Coordinates.head(5))
Latitude = Coordinates['LAT'].tolist()
Longitude = Coordinates['LONG'].tolist()
Siteid = Coordinates['RF Site ID'].tolist()
Base_url = "https://maps.googleapis.com/maps/api/geocode/json?latlng="
# To return postal code
url_extension = "&result_type=postal_code&key=Put Your google maps key here"
# to return the standard geo coding data set uncomment this line and comment the above line
#url_extension = "&key=Put Your google maps key here"
out_df = pd.DataFrame(columns=['RF Site ID','Lat','Long','Formatted Address','Province','country','City','postcode'])
print(out_df.size)
List_lenght = len(Longitude) -1
Output = list(range(0,List_lenght))
print(List_lenght)
for num in range(0, List_lenght) :
lat_url = Latitude[num]
lat_url= str(lat_url)
long_url= Longitude[num]
long_url= str(long_url)
RF_Site_id=Siteid[num]
time.sleep(1) # Sleep for 1 seconds
Total_url =Base_url+lat_url+','+long_url+url_extension
results = requests.get(Total_url)
results = results.json()
# resultslenght = len(results) - 1
#for resultnum in results :
print(RF_Site_id)
print(num)
if len(results['results']) == 0:
print("skipping "+RF_Site_id)
else:
answer = results['results'][0]
formatted_address = str(answer.get('formatted_address'))
# compound_code = answer.get('compound_code')
# print(compound_code)
formatted_address = str(answer.get('formatted_address'))
# debugging check to print the below line
print(formatted_address)
Province = str([x['long_name'] for x in answer.get('address_components')
if 'administrative_area_level_1' in x.get('types')])
country = ([x['long_name'] for x in answer.get('address_components')
if 'country' in x.get('types')])
# debugging check to print the below line
print(country)
City = str([x['long_name'] for x in answer.get('address_components')
if 'locality' in x.get('types')])
# debugging check to print the below line
print(City)
postcode = str([x['long_name'] for x in answer.get('address_components')
if 'postal_code' in x.get('types')])
print(postcode)
print('\n')
out_df = out_df.append({'RF Site ID' : RF_Site_id ,'Lat' : lat_url, 'Long' : long_url , 'Formatted Address' : formatted_address, 'Province' : Province , 'country': country ,'City' : City,'postcode' : postcode},
ignore_index = True)
print(out_df.size)
print(out_df.head())
out_df.to_csv("D:/Tutorials/Geocoding/Output_B7.csv")
Comments
Post a Comment