Using my Google Geocoding API key with Python geocoder

Raphael Hernandes picture Raphael Hernandes · Jul 26, 2017 · Viewed 8.6k times · Source

I'm a beginner at Python and I've been working to geocode a database using Pandas and Geocoder on Jupyter.

Since the df is a little long (around 3000 rows), I'd like to use Google's Geocoding API.

I've already created a free key, but I have no idea what I'm supposed to do with it. Help?

By the way, my code looks like this:

import geocoder
import pandas as pd

geo = geocoder

df=pd.read_excel('hsp2.xlsx')

df['Coordinates']=df['Address'].apply(geo.google).apply(lambda x: x.latlng if x != None else None)

df.to_csv('output.csv', sep='|', encoding='iso8859_15')

Answer

Roman picture Roman · Aug 4, 2017

You need to set the environment variable before you import geocoder:

import os

os.environ["GOOGLE_API_KEY"] = "api_key_from_google_cloud_platform"

import geocoder

geo = geocoder.google(address)
latlong = geo.latlng

Note:

As Murmel mentioned in the comments, environment variables containing keys (and in general) should not be set inside of your code.
If you are deploying this somewhere then set up enviroment variables in your configuration file. Or even better, as a secret in something like Kubernetes.

Else set the environment variable in bash with
export GOOGLE_API_KEY=api_key_from_google_cloud_platform