Generating Geocodes Using Google Maps API | by Francis Adrian Viernes | Towards Data Science

Geocoding is the process of translating text addresses into geographic latitude and longitude coordinates which in turn make it easy to manipulate and analyze massive amounts of geospatial data.
For a data scientist, knowing the geocode makes it easy to plot it in visualization and create other features, such as distances and time differences between two points.
Unlike other types of data, geospatial data benefits greatly from visualization as it makes apparent the occurrence of patterns in neighborhoods or local networks.
As such, businesses profit from the use of it but not if the process involves manually getting the geocodes.
While this process can be done using the open-source package, OpenStreetMap, Google Maps API may produce more accurate data for a wider range of addresses.
In this article, let us examine how to get these geocodes through Python and Google Maps API to speed up our data projects.
The use of Google Maps API comes with a charge and data scientists need to be aware of the pricing before using it.
To use the google maps API, we need to generate our very own API key to use this.
You will see here your dashboard.
To create a new project, follow the GIF above. The option to do this is found in the upper right corner, with a “Select a Project” text. Name the project to better manage current and future projects that involve Google APIs.
Browse the API Library to enable the geocoding service. This is named the “Geocoding API”.
Once the Geocoding API service is enabled, go to the Credentials tab and choose “+Create Credentials”. Once the API key is created copy it to use in your Python code.
You can rename the API and restrict it to keep it safe. There is an edit option to do this under the “API Keys” table for each API key (the pencil sign).
To use the API Key, ensure that you have installed the googlemaps package:
pip install googlemaps
import googlemaps#Set Google MAPS API_Keyg_API = "API-Key Copied"gmaps_key = googlemaps.Client(key=g_API)
For our exercise, let us create fake addresses to use our codes:
from faker import Fakerimport pandas as pdfake = Faker()df = pd.DataFrame(data=[fake.address().replace('\n', " ") for i in range(100)], columns=["address"])# Create columns to store longitude and lattitudedf["longitude"] = Nonedf["latitude"] = Nonefor i in df.index:    geocode_obj = gmaps_key.geocode(df.loc[i, "address"])    try:        lat = geocode_obj[0]['geometry']['location']['lat']        lon = geocode_obj[0]['geometry']['location']['lng']        df.loc[i,'latitude'] = lat        df.loc[i,'longitude'] = lon    except:        lat = None        lon = None
Voila, we’re done!
Geocodes are important because they allow computers to understand our point of reference. That means, with geocodes, analysis and geospatial visualization (geovisualization) are made possible. In addition to that, geocodes are unique.
Using our method above is one of the fastest and surest ways to generate geocodes for our address objects. Some addresses, however, will occasionally result in “None” so manual checking is required for these. From experience, however, these seldom happen when the address variables are clean so we may want to look at how we generate our data before running the code above.
Check out my other articles related to this one:
Mapping Your Favorite Coffee Shop in the Philippines using Google Places API and Folium
Spatial Distance and Machine Learning
Let me know what you think!