GoogleMaps API -address to coordinates (latitude,longitude)

后端 未结 3 1398
被撕碎了的回忆
被撕碎了的回忆 2021-02-02 15:54

This is driving me crazy. I have deleted this key 1000 times so far. Yesterday it worked like a charm, today not anymore Here is the python code:

from googlemaps         


        
相关标签:
3条回答
  • 2021-02-02 15:57

    Did some code golfing and ended up with this version. Depending on your need you might want to distinguish some more error conditions.

    import urllib, urllib2, json
    
    def decode_address_to_coordinates(address):
            params = {
                    'address' : address,
                    'sensor' : 'false',
            }  
            url = 'http://maps.google.com/maps/api/geocode/json?' + urllib.urlencode(params)
            response = urllib2.urlopen(url)
            result = json.load(response)
            try:
                    return result['results'][0]['geometry']['location']
            except:
                    return None
    
    0 讨论(0)
  • 2021-02-02 16:04

    Since September 2013, Google Maps API v2 no longer works. Here is the code working for API v3 (based on this answer):

    import urllib
    import simplejson
    
    googleGeocodeUrl = 'http://maps.googleapis.com/maps/api/geocode/json?'
    
    def get_coordinates(query, from_sensor=False):
        query = query.encode('utf-8')
        params = {
            'address': query,
            'sensor': "true" if from_sensor else "false"
        }
        url = googleGeocodeUrl + urllib.urlencode(params)
        json_response = urllib.urlopen(url)
        response = simplejson.loads(json_response.read())
        if response['results']:
            location = response['results'][0]['geometry']['location']
            latitude, longitude = location['lat'], location['lng']
            print query, latitude, longitude
        else:
            latitude, longitude = None, None
            print query, "<no results>"
        return latitude, longitude
    

    See official documentation for the complete list of parameters and additional information.

    0 讨论(0)
  • 2021-02-02 16:08

    Although Google deprecated the V2 calls with googlemaps (which is why you're seeing the broken calls), they just recently announced that they are giving developers a six-month extension (until September 8, 2013) to move from the V2 to V3 API. See Update on Geocoding API V2 for details.

    In the meantime, check out pygeocoder as a possible Python V3 solution.

    0 讨论(0)
提交回复
热议问题