- Author:
- whardeman
- Posted:
- October 25, 2010
- Language:
- Python
- Version:
- 1.2
- 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
- Template tag - list punctuation for a list of items by shapiromatron 9 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months, 1 week ago
- Serializer factory with Django Rest Framework by julio 1 year, 4 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
- Help text hyperlinks by sa2812 1 year, 5 months ago
Comments
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.