googlemaps – Google Maps and Local Search APIs in Python

class googlemaps.GoogleMaps

An easy-to-use Python wrapper for the Google Maps and Local Search APIs.

Geocoding: convert a postal address to latitude and longitude

>>> from googlemaps import GoogleMaps
>>> gmaps = GoogleMaps()
>>> address = '10th St. & Constitution Ave. NW, Washington, D.C. 20560'
>>> lat, lng = gmaps.address_to_latlng(address)
>>> print lat, lng
38.892087 -77.025989

Reverse Geocoding: find the nearest address to (lat, lng)

>>> destination = gmaps.latlng_to_address(38.887563, -77.019929)
>>> print destination
200 6th St SW, Washington, DC 20024, USA

Local Search: find places matching a query near a given location

>>> local = gmaps.local_search('dinner ' + destination)
>>> print local['responseData']['results'][0]['title']
Cosmo Cafe

Directions: turn-by-turn directions, distance, time, etc. from point A to point B

>>> directions = gmaps.directions(address, destination)
>>> print directions['Directions']['Distance']['meters']
1026
>>> print directions['Directions']['Duration']['seconds']
115
>>> for step in directions['Directions']['Routes'][0]['Steps']:
...     print step['descriptionHtml']
Head <b>east</b> on <b>Constitution Ave NW</b> toward <b>9th St NW</b>
Turn <b>right</b> at <b>7th St NW</b>
Turn <b>left</b> at <b>Independence Ave SW</b>

This software is in no way associated with or endorsed by Google Inc. Use of the Google Maps API is governed by its Terms of Service: http://code.google.com/apis/maps/terms.html. Note in particular that you will need your own Google Maps API key to use this service, and that there are rate limits to the number of requests you can make.

GoogleMaps methods

GoogleMaps.__init__(api_key='', referrer_url='')

Create a new GoogleMaps object using the given api_key and referrer_url.

Parameters:
  • api_key (string) – Google Maps API key
  • referrer_url (string) – URL of the website using or displaying information from this module.

Google requires API users to register for an API key before using the geocoding service; this can be done at http://code.google.com/apis/maps/signup.html. If you are not geocoding, you do not need an API key.

Use of Google Local Search requires a referrer URL, generally the website where the retrieved information will be used. If you are not using Local Search, you do not need a referrer URL.

Geocoding

GoogleMaps.address_to_latlng(address)

Given a string address, return a (latitude, longitude) pair.

This is a simplified wrapper for geocode().

Parameter:address (string) – The postal address to geocode.
Return type:(float, float)
Raises GoogleMapsError:
 If the address could not be geocoded.
GoogleMaps.geocode(query, sensor='false', oe='utf8', ll='', spn='', gl='')

Given a string address query, return a dictionary of information about that location, including its latitude and longitude.

Interesting bits:

>>> gmaps = GoogleMaps()
>>> address = '10th St. & Constitution Ave. NW, Washington, D.C. 20560'
>>> result = gmaps.geocode(address)
>>> placemark = result['Placemark'][0]
>>> lng, lat = placemark['Point']['coordinates'][0:2]    # Note these are backwards from usual
>>> print lat, lng
38.892087 -77.025989
>>> details = placemark['AddressDetails']['Country']['AdministrativeArea']
>>> street = details['SubAdministrativeArea']['Locality']['Thoroughfare']['ThoroughfareName']
>>> city = details['SubAdministrativeArea']['Locality']['LocalityName']
>>> state = details['AdministrativeAreaName']
>>> zipcode = details['SubAdministrativeArea']['Locality']['PostalCode']['PostalCodeNumber']
>>> print ', '.join((street, city, state, zipcode))
Constitution Ave NW & 10th St NW, Washington, DC, 20004

More documentation on the format of the return value can be found at Google’s geocoder return value reference.

Parameters:
  • query (string) – Address of location to be geocoded.
  • sensor (string) – 'true' if the address is coming from, say, a GPS device.
  • oe (string) – Output Encoding; best left at 'utf8'.
  • ll (string) – lat,lng of the viewport center as comma-separated string; must be used with spn for Viewport Biasing
  • spn (string) – The “span” of the viewport; must be used with ll.
  • gl (string) – Two-character ccTLD for country code biasing.
Returns:

geocoder return value dictionary

Return type:

dict

Raises GoogleMapsError:
 

if there is something wrong with the query.

More information on the types and meaning of the parameters can be found at the Google HTTP Geocoder site.

Reverse Geocoding

GoogleMaps.latlng_to_address(lat, lng)

Given a latitude lat and longitude lng, return the closest address.

This is a simplified wrapper for reverse_geocode().

Parameters:
  • lat (float) – latitude
  • lng (float) – longitude
Returns:

Closest postal address to (lat, lng), if any.

Return type:

string

Raises GoogleMapsError:
 

if the coordinates could not be converted to an address.

GoogleMaps.reverse_geocode(lat, lng, sensor='false', oe='utf8', ll='', spn='', gl='')

Converts a (latitude, longitude) pair to an address.

Interesting bits:

>>> gmaps = GoogleMaps()
>>> reverse = gmaps.reverse_geocode(38.887563, -77.019929)
>>> address = reverse['Placemark'][0]['address']
>>> print address
200 6th St SW, Washington, DC 20024, USA
>>> accuracy = reverse['Placemark'][0]['AddressDetails']['Accuracy']
>>> print accuracy
8
Parameters:
  • lat (float) – latitude
  • lng (float) – longitude
Returns:

Reverse geocoder return value dictionary giving closest address(es) to (lat, lng)

Return type:

dict

Raises GoogleMapsError:
 

If the coordinates could not be reverse geocoded.

Keyword arguments and return value are identical to those of geocode().

Directions

GoogleMaps.directions(origin, destination, **kwargs)

Get driving directions from origin to destination.

Interesting bits:

>>> gmaps = GoogleMaps()
>>> start = '10th St. & Constitution Ave. NW, Washington, D.C. 20560'
>>> end   = '200 6th St SW, Washington, DC 20024, USA'
>>> dirs  = gmaps.directions(start, end) 
>>> time  = dirs['Directions']['Duration']['seconds']
>>> dist  = dirs['Directions']['Distance']['meters']
>>> route = dirs['Directions']['Routes'][0]
>>> for step in route['Steps']:
...    print step['Point']['coordinates'][1::-1]
...    print step['descriptionHtml']
[38.892090000000003, -77.025989999999993]
Head <b>east</b> on <b>Constitution Ave NW</b> toward <b>9th St NW</b>
[38.892060000000001, -77.021969999999996]
Turn <b>right</b> at <b>7th St NW</b>
[38.887560000000001, -77.021979999999999]
Turn <b>left</b> at <b>Independence Ave SW</b>
Parameters:
  • origin (string) – Starting address
  • destination (string) – Ending address
  • kwargs – You can pass additional URL parameters as keyword arguments, but this functionality is not documented.
Returns:

Dictionary containing driving directions.

Return type:

dict

Raises GoogleMapsError:
 

If Google Maps was unable to find directions.

Installation

It’s as easy as:

sudo easy_install googlemaps

Not got root? googlemaps plays nice with virtualenv.

You can also download the source from sourceforge.net; googlemaps.py packs all this delicious functionality into a single, self-contained module that can be used as a script for command-line geocoding.

easy_install is available from PyPI if you don’t have it already.

Notes

You will need your own Google Maps API key to use the geocoding functions of this module. There are rate limits to the number of requests per day from a single IP address. If you make too many requests, or you use an invalid API key, or something else is wrong with your request, a GoogleMapsError will be raised containing a status code and brief description of the error; more information can be found at the linked reference.

All of the data returned by this module is in JSON-compatible format, making it easy to combine with other web services.

Information

Author:John Kleint
Version:1.0
License:Lesser Affero General Public License v3
Source:http://py-googlemaps.sourceforge.net
Python Versions:
 2.3 - 2.6+

This software comes with no warranty and is in no way associated with Google Inc. or the Google Maps™ mapping service. Google does not approve or endorse this software. GOOGLE is a trademark of Google Inc.