How to get Address from Latitude & Longitude in Django GeoIP?

别说谁变了你拦得住时间么 提交于 2020-07-17 08:25:29

问题


I cannot see anything in their API to do this: https://docs.djangoproject.com/en/dev/ref/contrib/gis/geoip/#geoip-api

Or should I just use Google API for Reverse Geocoding?


回答1:


Solution - call this URL and parse it's JSON.

http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=false



回答2:


Use geopy, it can handle multiple geocoders including 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

install with pip:

pip install geopy

infos found on: https://github.com/geopy/geopy




回答3:


You can use maps API. I've included a snippet which I use to calculate marathon start points converted into a PointField using Postgis with Django. This should set you on your way.

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



回答4:


@rawsix answer seems smart for a django user. Note however that the location returned by geolocator.reverse(query) is a list and not a Location object; so attempting to retrieve attribute address from it would result in an error.

Usually, the first item in that list has the closest address information. so u can simply do:

 location = location[0]
 address = location.address

Additionally, instead of passing a string latitude and longitude to the reverse method, you can use a tuple and it must be the latitude before the longitude. You can do:

 from geopy.geocoders import GoogleV3()
 geocoder = GoogleV3()
 location_list = geocoder.reverse((latitude, longitude))
 location = location_list[0]
 address = location.address


来源:https://stackoverflow.com/questions/12942894/how-to-get-address-from-latitude-longitude-in-django-geoip

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!