我需要将地址地理编码为在谷歌地图上显示的纬度,经度对,但我需要在Django中执行此服务器端。我只能找到对Javascript V3 API的引用。我如何从Python中完成它?
答案 0 :(得分:14)
我建议使用Py-Googlemaps。使用它很容易:
from googlemaps import GoogleMaps
gmaps = GoogleMaps(API_KEY)
lat, lng = gmaps.address_to_latlng(address)
答案 1 :(得分:11)
我强烈建议您使用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
类作为地理定位器来明确定义您要使用Google服务
>>> from geopy.geocoders import GoogleV3
>>> geolocator = GoogleV3()
答案 2 :(得分:5)
Google数据API for Maps有一个REST-ful API - 而且他们已经建立了Python library。
答案 3 :(得分:0)
以下是适用于Google Maps 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。
答案 4 :(得分:0)
Python包googlemaps
似乎非常能够进行地理编码和反向地理编码。
最新版本的googlemaps套餐位于:https://pypi.python.org/pypi/googlemaps