Geocoding with the Google Maps API
import requests
import folium
You're going to have to get an API key if you don't aready have one by going to the Google Geocoder API. After that we need to contruct our URL to send the request.
The first part of the URL will appear as such, go ahead try clicking on it and see what happens.
https://maps.googleapis.com/maps/api/geocode/json?address=time+square+new+york+city&key
When making a request you should have an API key, but be careful not to make too many requests, you might hit a query limit.
api_key= # Place key here
url="https://maps.googleapis.com/maps/api/geocode/json?address=time+square+new+york+city&key="
r = requests.get(url+api_key)
Now that we have the response object r we should check the status code. It looks like we have a 200, which is good. For more information on status code you can refer to status codes.
r.status_code
Now we're going to use Requests built in JSON decoder.
rjson=r.json()
rjson
Now all we need to do is access the information we want from the JSON and do something with it. In this case I'm going to make a simple map with a marker for Time Square.
lat = rjson['results'][0]['geometry']['location']['lat']
lng = rjson['results'][0]['geometry']['location']['lng']
address = rjson['results'][0]['formatted_address']
map_1 = folium.Map(location=[lat, lng],
zoom_start=14,
tiles='Stamen Toner')
folium.Marker([lat, lng], popup=address).add_to(map_1)
map_1
Well that's all folks! Geocoding can be pretty easy, but when dealing with large batches of data and funky addresses, it can quickly become a headache. For more information on usage limits go to Usage Limits. Always make sure to validate the data or at least be aware that it may not aways be accurate.