Get user's geo location using JavaScript

Get user's geo location using JavaScript

Use of Geo location and Geo IP API

ยท

2 min read

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. ip-api.com
  2. ipapi.co
  3. 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)
})
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.";
}

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