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()