happygostacie
happygostacie

Reputation: 173

Extracting lat/lon from geocode result list with Python (Google Maps API)

I'm attempting to use the Google Maps API with the GoogleMaps Python library to geocode latitude/longitude when provided with whole or part of an address (in this example, I'm using city/state, but I also have datasets with just zip codes that I'll need to use this for down the line).

 import googlemaps
 gmaps = googlemaps.Client(key=[insert API key here])
 geocode_result = gmaps.geocode('Sacramento, CA')
 print(geocode_result)

Result:[{u'geometry': {u'location_type': u'APPROXIMATE', u'bounds': {u'northeast': {u'lat': 38.685507, u'lng': -121.325705}, u'southwest': {u'lat': 38.437574, u'lng': -121.56012}}, u'viewport': {u'northeast': {u'lat': 38.685507, u'lng': -121.325705}, u'southwest': {u'lat': 38.437574, u'lng': -121.56012}}, u'location': {u'lat': 38.5815719, u'lng': -121.4943996}}, u'address_components': [{u'long_name': u'Sacramento', u'types': [u'locality', u'political'], u'short_name': u'Sacramento'}, {u'long_name': u'Sacramento County', u'types': [u'administrative_area_level_2', u'political'], u'short_name': u'Sacramento County'}, {u'long_name': u'California', u'types': [u'administrative_area_level_1', u'political'], u'short_name': u'CA'}, {u'long_name': u'United States', u'types': [u'country', u'political'], u'short_name': u'US'}], u'place_id': u'ChIJ-ZeDsnLGmoAR238ZdKpqH5I', u'formatted_address': u'Sacramento, CA, USA', u'types': [u'locality', u'political']}]

My issue is that I'm not sure how to extract the appropriate lat/lon values from this list. I've tried parsing through the list using the following code (taken from the answer to this question on SO):

import operator
thirditem=operator.itemgetter(3)(geocode_result)
print(thirditem)

When I run this, I get an IndexError saying the index is out of range. I've run it through the debugger also, but I get the same error without any additional information. I've googled around and looked through other SO questions, but i'm still not sure where the issue is.

As a side note, I've also tried to use the code examples in this tutorial, but I get a "0" as my answer when I try to run it, which is unfortunately even less helpful than an IndexError.

My goal is to be able to parse the appropriate lat/lon values from here and insert them dynamically into this basemap script. Values are currently hard-coded, but eventually I'd like to be able to use a variable for the values llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat, lat_0, and lon_0:

map = Basemap(projection='merc',
          # with high resolution,
          resolution= 'h',
          # And threshold 100000
          area_thresh = 100000.0,
          # Centered on these coordinates
          lat_0=37, lon_0=119,
          #and using these corners to specify the lower left lon/lat and upper right lon/lat of the graph)
          llcrnrlon=-130, llcrnrlat=30,
          urcrnrlon=-110, urcrnrlat=45)

I'm SUPER new to all this, so there could be an easy answer that I'm just not seeing. Any help is welcome! Thanks.

Upvotes: 2

Views: 7841

Answers (1)

happygostacie
happygostacie

Reputation: 173

I was able to ask some of my fellow devs for help, and I am answering my own question on here in the hopes that it will help others who are also struggling with the same problem.

Geocoded results return a JSON object, which in Python is treated like a dictionary that only contains a single object (the result). Therefore, in order to extract the appropriate lat-lon values, you need to use "geocode_result[0]["geometry"]["location"]["lat"]", with [0] being the first object in the array (the result).

I wrote this function to use in my Basemap script to extract the lat/lon values from a location passed in as a parameter.

def geocode_address(loc):
    gmaps = googlemaps.Client(key=[insert your API key here])
    geocode_result = gmaps.geocode(loc)
    lat = geocode_result[0]["geometry"]["location"]["lat"]
    lon = geocode_result[0]["geometry"]["location"]["lng"]
    #test - print results
    print (lat,lon)

When I test it out using Sacramento, CA as the loc:

geocode_address('Sacramento, CA')

This is my result:

Result: 38.5815719, -121.4943996

Upvotes: 11

Related Questions