Login

Retrieve Latitude & Longitude for an Address from Google Geocoder V3

Author:
whardeman
Posted:
October 25, 2010
Language:
Python
Version:
1.2
Tags:
google geocode
Score:
-1 (after 1 ratings)

Very simple python class for querying Google Geocoder. Accepts a human-readable address, parses JSON results and sets lat and lng. (Full JSON results are stored to results property of GoogleLatLng for access to other attributes.)

This could easily be expanded to include the XML output option, etc.

Requires PycURL and simplejson.

Example:

>>> location = "1600 Amphitheatre Parkway, Mountain View, CA 94043"
>>> glatlng = GoogleLatLng()
>>> glatlng.requestLatLngJSON(location)
>>> print "Latitude: %s, Longitude: %s" % (glatlng.lat, glatlng.lng)
Latitude: 37.422782, Longitude: -122.085099`

Do not forget the usage limits, which include request rate throttling, otherwise, Google might ban you.

===

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import sys
import pycurl, urllib
import simplejson as json

class GoogleLatLng:
    """
    Send an address to Google Geocoder API and get JSON output back.
    Parse to retrieve latitude and longitude.
    There is a 24-hour usage limit, currently this is 2500 requests 
    but this could change in the future. Check Google's Terms of Use
    before employing this technique.
    """
    def __init__(self):
        self.lat = ""
        self.lng = ""
        self.results = ""

    def parseResults(self, buff):
        self.results = json.loads(buff)
        try:
                self.lat = self.results['results'][0]['geometry']['location']['lat']
                self.lng = self.results['results'][0]['geometry']['location']['lng']
        except:
                print >> sys.stderr, "An error occurred.\nQuery results: %s" % self.results

    def requestLatLngJSON(self, location):
        location = urllib.quote_plus(location)
        c = pycurl.Curl()
        c.setopt(c.URL, 'http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=%s' % location)
        c.setopt(c.WRITEFUNCTION, self.parseResults)
        c.perform()
        c.close()

More like this

  1. Google Geocode Lookup by tonyskyday 8 years ago
  2. Save Geolocation for an Address based model on save() by publicFunction 1 year, 11 months ago
  3. Get Latitude and Longitude from google maps by b23 7 years, 7 months ago
  4. Google v3 geocoding for Geodjango admin site by samhag 2 years, 8 months ago
  5. YUI Loader as Django middleware by akaihola 7 years, 2 months ago

Comments

pjwalmsley (on April 14, 2014):

For those getting the following error:

(23, 'Failed writing body (0 != 1044)') pycurl

The callback function ParseResults must return. You can return "None" to resolve the error.

#

Please login first before commenting.