GeoDjango: Getting accurate device location with geoip2

1.6k views Asked by At

I am trying to get the users device location. But the geoip2 returns a location far away from users location (almost 20km-25km). When I connect my device through a mobile network it shows a different location when I connect my device with the wifi

First I am getting the users ip

def get_ip(request):
    xff = request.META.get('HTTP_X_FORWARDED_FOR')
    
    if xff:
        ip = xff.split(',')[0]
    else:
        ip = request.META.get('REMOTE_ADDR', None)
    return ip

But this gets the users private ip and the private ip is not in the country or city datasets so the geoip2 throws an error.

So I try to get the public ip address through a website

def get_ip(request):
    
    from requests import get
    ip = get('https://api.ipify.org').text
    
    if ip:
        return ip

Now i use geoip2 to get the users location data

def home(request,):
....
....
....
....
    from django.contrib.gis.geoip2 import GeoIP2
    g = GeoIP2()
    ip = get_ip(request)
    print(ip)

    country = g.country(ip)
    city = g.city(ip)
    print(country, city)
    lat, long = g.lat_lon(ip)
    print(lat, long)
...
...
...
    

Can you please suggest a better way or proper way to get the accurate location of the user?

1

There are 1 answers

2
Zahid Wadiwale On

Firstly you need to understand that geoip2 uses .dat/csv files which are nothing but a files containing ranges of IP address according to country/city/latitude-longitude. These files need to be updated on timely bases to have more sort of accurate data. Secondly if you do it using localhost the first code it will return this 127.0.0.1 IP address because you are getting your remote IP.

def home(request):
    xff = request.META.get('HTTP_X_FORWARDED_FOR')
    if xff:
        ip = xff.split(',')[0]
        country = g.country(ip)
        city = g.city(ip)
        lat, long = g.lat_lon(ip)
    else:
        ip = request.META.get('REMOTE_ADDR', None)
        country = 'Your Country Name'
        city='Your City'
        lat,long = 'Your Latitude','Your Longitiude'
    print(country, city)
    print(lat, long)

This code will work with localhosts also so you wont get the IP error. And to get accurate locations update your dat/csv files