Ways to get user's geo location

dhruvangg

Dhruvang Gajjar

Posted on April 19, 2021

Ways to get user's geo location

There are a lot of functionalities where you have to get the user's location.

Let's consider a simple scenario that you have to show the popup based on user's location. so you have to get the user's location to achieve the requirement.

There are 2 ways to get the user's location.

Using Geo IP API

With this approach, You will have to use IP database. Get User's IP address and match that IP address in the IP database, and get related address details. Here If you don't have a backend or database you can use 3rd party API. There are many APIs available.
Here is a list of Few IP API Providers:

  1. https://ip-api.com/
  2. https://ipapi.co/
  3. https://ipapi.com/

All have their own limitation and different pricing so check documentation, terms and conditions before use.

Usage
axios.get(`http://ip-api.com/json/`).then(res => {
    console.log(res.data)
}).catch(err => {
    console.error(err)
})
Enter fullscreen mode Exit fullscreen mode
Pros
  • User don't need user permission to get their location.
  • Instant and simple user's geo location place.
  • Free for limited requests
Cons
  • Less Accuracy of user's location
  • Some 3rd party APIs are paid for commercial use.

Using Geo Location API

The Geolocation API allows the user to provide their location to web applications if they so desire. For privacy reasons, the user is asked for permission to report location information. It returns only geographical coordinates of user's location once they allow.

Usage
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(position => {
        console.log(position.coords)
    });
} else {
    x.innerHTML = "Geolocation is not supported by this browser.";
}
Enter fullscreen mode Exit fullscreen mode

By above code, User would get the popup as per below screenshot.
Geo Location API

It will return geolocation data only if user allow the popup.

Pros
  • 100% Accurate Geo location
  • Instant
  • Available for free as It is native browser API.
Cons
  • Only return coordinates
  • Require 3rd party tool to convert coordinates to geo location
  • Available only in secure contexts (https)

You can use openstreetmap as tool to convert coordinates to geo location. It's an open source platform.

So that's all about user's Geo location. Let me know your views by commenting on this post.

I hope you found the article helpful. Feedbacks are greatly appreciated! 🙌

Have an amazing day!

🌎 Lets connect

💖 💪 🙅 🚩
dhruvangg
Dhruvang Gajjar

Posted on April 19, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related