Geocoding with Google Maps API

The most popular method to convert addresses into coordinates is by using Google Maps API.

Although Google Maps provides paid services, it gives you $200 in free credits the first time you create the account.

To get access to the service, you need to create a new account on the Google Maps Platform. There is a great tutorial that helps you generate the API key.

GM_API_KEY = 'your_api_key' from geopy.geocoders import GoogleV3 geolocator = GoogleV3(api_key=GM_API_KEY)

OpenAI

GoogleV3 is the class implemented to use Google Maps v3 API. First, we can try to extract the location from a single address:

location = geolocator.geocode(address1) print('Latitude: '+str(location.latitude)+', Longitude: '+str(location.longitude))

OpenAI

image5.png

After we can try to extend this operation to then field unique_address that we have created previously.

def service_geocode(g_locator, address): location = g_locator.geocode(address) if location!=None: return (location.latitude, location.longitude) else: return np.NaN

OpenAI

We can use apply() to apply the function over all the rows of unique_address:

df['LAT_LON'] = df['unique_address'].apply(lambda x:service_geocode(geolocator,x)) df[['unique_address','LAT_LON']].head()

OpenAI

image3.png

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *