Search code examples
pythongeolocation

How to get user current location with lat and long


I followed geocoder for a while to get the user's current location and info, and alone with lat long value.

The code I am tried.

import geocoder
myloc = geocoder.ip('me')
print(myloc.latlng)
print(geocoder.ipinfo())

Getting the info value is okay. But lat long value seems different. It's showing an almost 8~9km distance location. Seems runtime is also a bit lengthy. Is there any other way to get close enough lat long value and runtime also faster?


Solution

  • You need to understand how IP geolocation works to know why you don't get a precise result.

    1- IP Geolocation use your public IP address to locate you. Most of the times this address is allocated to you by your internet provider.

    It's not your computer's or your home's IP, but the IP of one of your Internet provider's equipment (their exit-point to the Internet, the IP of a router somewhere inside their infrastructure, or anything else).

    2- There is no location information attached to an IP address, and depending on the Geolocation API you are using, the result can be more or less precise. I use Abstract Geolocation because it's free, accurate and works in real-time: https://www.abstractapi.com/ip-geolocation-api you need to create an account to get your API key, which takes only a few seconds.

    3- Geocoder may be slow sometimes. Calling an API is as simple as going through Geocoder, so you could do without it and get a faster response:

    import requests
    import json
    
    response = requests.get("https://ipgeolocation.abstractapi.com/v1/?api_key=YOUR_API_KEY")
    data = json.loads(response.content)
    print(data)
    

    This will show lots of information about your IP address, and you can optionally add an ip_address parameter to get info about another IP.