我在他们的API中没有找到任何相关内容:https://docs.djangoproject.com/en/dev/ref/contrib/gis/geoip/#geoip-api。或者我应该使用Google API进行反向地理编码吗?
from geopy.geocoders import GoogleV3
geolocator = GoogleV3()
location = geolocator.reverse("52.509669, 13.376294")
print(location.address)
>>> Potsdamer Platz, Mitte, Berlin, 10117, Deutschland, European Union
使用pip进行安装:
pip install geopy
infos found on: https://github.com/geopy/geopy
http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=false
@rawsix的回答对于Django用户来说似乎很聪明。
但是请注意,geolocator.reverse(query)
返回的位置是一个列表而不是Location
对象;因此,尝试从中检索属性address
将导致错误。
通常,该列表中的第一项具有最接近的地址信息。所以你可以简单地这样做:
location = location[0]
address = location.address
此外,在调用reverse方法时,不再需要将经度和纬度作为字符串传递,可以使用元组,并且必须先传递latitude
,后传递longitude
。示例如下:
from geopy.geocoders import GoogleV3()
geocoder = GoogleV3()
location_list = geocoder.reverse((latitude, longitude))
location = location_list[0]
address = location.address
您可以使用地图API。我包含了一个片段,用于使用Postgis和Django将马拉松起点转换为PointField进行计算。这应该可以帮助您入门。
import requests
def geocode(data):
url_list = []
for item in data:
address = ('%s+%s' % (item.city, item.country)).replace(' ', '+')
url = 'http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false' % address
url_list.append([item.pk, url])
json_results = []
for url in url_list:
r = requests.get(url[1])
json_results.append([url[0], r.json])
result_list = []
for result in json_results:
if result[1]['status'] == 'OK':
lat = float(result[1]['results'][0]['geometry']['location']['lat'])
lng = float(result[1]['results'][0]['geometry']['location']['lng'])
marathon = Marathon.objects.get(pk=result[0])
marathon.point = GEOSGeometry('POINT(%s %s)' % (lng, lat))
marathon.save()
return result_list