2011-04-27 97 views
7

我需要对地址进行地址解析以显示在Google地图上的纬度,经度对,但我需要在Django中执行此服务器端。我只能找到对JavaScript V3 API的参考。我如何从Python做到这一点?如何从Python中获取地址的坐标

回答

11

我建议使用Py-Googlemaps。要使用它很简单:

from googlemaps import GoogleMaps 
gmaps = GoogleMaps(API_KEY) 
lat, lng = gmaps.address_to_latlng(address) 
+0

是否有可能获得与此库的工作了API密钥使用谷歌的服务?我生成了一个JavaScript v3 API密钥,但它似乎没有工作。 – powerj1984 2013-04-23 14:57:42

+2

刚刚结束使用此代替:http://code.xster.net/pygeocoder/wiki/Home – powerj1984 2013-04-23 15:02:00

+0

OP的回购:https://github.com/googlemaps/google-maps-services-python – 2016-11-06 12:19:00

0

下面是谷歌地图API V3(基于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 

的参数和其他信息的完整列表,请参阅official documentation

6

我会强烈建议使用geopy。它将返回经纬度,之后您可以在Google JS客户端中使用它。

>>> from geopy.geocoders import Nominatim 
>>> geolocator = Nominatim() 
>>> location = geolocator.geocode("175 5th Avenue NYC") 
>>> print(location.address) 
Flatiron Building, 175, 5th Avenue, Flatiron, New York, NYC, New York, ... 
>>> print((location.latitude, location.longitude)) 
(40.7410861, -73.9896297241625) 

此外,您可以专门定义要使用GoogleV3类作为geolocator

>>> from geopy.geocoders import GoogleV3 
>>> geolocator = GoogleV3()