Using my google geocoding API with python geocoding
I am a beginner in Python and I have been working on geocoding a database with Pandas and Geocoder in Jupyter.
Since the df is a bit longer (about 3000 lines), I would like to use the Google Geocoding API.
I already created a free key, but I have no idea what I should 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')
source to share
You need to set the environment variable before importing 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 your code.
If you are deploying this somewhere, then set up environment variables in the config file. Or better yet, as a secret in something like Kubernete.
Else set environment variable in bash with
export GOOGLE_API_KEY=api_key_from_google_cloud_platform
source to share
There are basically 2 options:
-
passing the API key as an environment variable:
GOOGLE_API_KEY=YOUR-API-KEY-HERE python your_program.py
-
passing the API key as an argument:
geocoder.google('some address', key='YOUR-API-KEY-HERE')
More details
-
You are using a python library called geocoder , which itself is a wrapper around several geocoding services.
-
If you look at the geocoder pypi page , you can (ignoring rendering issues) find the docs for the geocoder. In your case, you probably want to look at some of the google-related docs .
-
For basic use, these seams work even without the KEY API, but you can specify one using 2 options:
-
Environment Variable : As Roman has already shown . This approach is intended to be used to avoid having an API key in your code - for security reasons. (You probably want to upload your code to the public repository, but without exposing your API key to everyone.)
-
Parameter "Key": You can also provide your API key by specifying it using a parameter
key
, for example:geocoder.google('some address', key='YOUR-API-KEY-HERE')
-
source to share
I agree with Roman's answer . You can use this and work. I'm a little scared if I use a geocoder in a loop then google will definitely block my IP, so I go through the hub code and find that the geocoder is getting the google api key from os.environ.get('GOOGLE_API_KEY')
. You can see that in the picture:
source to share