如何在Django GeoIP中通过纬度和经度获取地址?

8
4个回答

7
使用geopy,它可以处理多个地理编码器,包括googlev3。
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


1
我使用相同的代码,但当使用print(location.address)时出错了 Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'list' object has no attribute 'address' - Nids Barthwal
当调用reverse时,我得到的是相同的东西,即坐标列表。 - Kevin Parker

7
解决方案 - 调用此URL并解析其JSON。
http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=false

2

@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

2

您可以使用地图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

谢谢,但我想获得从纬度和经度(作为输入)获取“地址”(作为输出)。您的示例与我想要的相反。我使用了类似的方法使其工作 https://maps.googleapis.com/maps/api/geocode/json?latlng= - Ernest
1
请使用您的经纬度值,检查传入的JSON结果,而不是地址。您将在其中找到地址。 - super9

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接