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

后端 未结 4 1222
遇见更好的自我
遇见更好的自我 2021-02-06 08:39

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 Geocodi

4条回答
  •  花落未央
    2021-02-06 08:49

    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
    

提交回复
热议问题