How to get geolocation of user using javascript (With & Without permission)

Article


author small image Siva Kishore G
Posted : 22 Jun 2022
Modified : 31 Jul 2023
Expert Developers
Geolocation using various methods

What is geolocation

Geolocation, geopositioning or geotracking is a way of locating the user's geological coordinates. This is usually done through GPS (global positioning system) on devices that are capable. Devices that are connected to the internet can also be tracked using their IP address. In this article learn various ways of implementing a geotracker using javascript.

Using Geolocation API

HTML5 exposes Geolocation API through which one can get the user's location. Since this is a privacy issue, browsers ask for user's permission at least for the very first time.

Upon calling navigator.geolocation, the user is presented with a permission dialog box and if accepted, then the location can be access using any of the two below

  1. geolocation.getCurrentPosition()

    Retrieves the current device's position

    navigator.geolocation.getCurrentPosition( result=>{
      // Open the map location using the lat and lng.
       window.open(`https://maps.google.com/?${result.coords.latitude},${result.coords.longitude}`)
    }, error=>{
      console.log("Error", error)
    })
  2. geolocation.watchPosition()

    Obtain locations whenever the position of the device changes. Used especially to track a device continuously

    navigator.geolocation.watchPosition( result=>{
      console.log(result.coords.latitude,result.coords.longitude)
    }, error=>{
      console.log("Error", error)
    })

Google Maps API

Using Google Maps api, we can get the address of the location using the latitude and longitude fetched from the Geolocation API. Import the script and use the code below on a secure (https) site to get the address.

<script src="https://maps.googleapis.com/maps/api/js?v=3&key={API_KEY}"></script>
function getAddress(lat,lng){
    var latlng = new google.maps.LatLng(lat, lng);
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'latLng': latlng },  (results, status) =>{
        if (status == google.maps.GeocoderStatus.OK) {
            console.log(results);
        }
    });
  }

IP address

Any device that is connected to the internet is allotted an IP address through which one can get a coarse location of the device. It depends upon how accurately the ISP (Internet Service Provider) updates their location.

With the advent of services like Netflix, Hulu etc which require the user's location to provide content accordingly, the ISPs are growingly concerned about their IP addresses being geolocated accurately. So, ISPs keep reaching out to most of the third party IP geolocation service providers.

Web Server(Nginx)

Servers like Ubuntu, CentOS are equipped with packages that can get the IP address of the user's device visiting the website. Lets consider a Nginx webserver which is serving a website behind a reverse proxy which means, the IP we get is something like 127.0.0.1 which is the local IP / localhost. But we require the real IP address of the user. Then add the following in the location block of the virtual host.

proxy_set_header X-Real-IP $remote_addr;
// Call this in an express app to get the real IP of the user
req.headers['x-real-ip']

One we get the IP address, use any of the IP geolocation provider methods to get the geological location

Blackhat

Blackhatters / Hackers are those whose intent is malicious and often produce various softwares or techniques to get the user's info mostly without the user's knowledge. It involves installing a piece of software that acts like a spy / bug constantly communicating with the hacker while reporting the user's activity or even worse turning one's device into a zombie.

Zombie devices act like a slave and do exactly what the hacker intends to do. These devices are the primarily used for DDOS (Distributed denial of service). So it's adviced not to download any unknown software or cracks ( Cracks are used to bypass security of a legitimate software).

Get user location without permission

Sneaky it may sound, a user's location can be tracked without their knowledge. As you guessed it, it's done by IP. We can get a coarse location of the user. There are many third party solutions paid / free exist. This can be achieved by calling a simple get request using javascript.

Third party services

These are some of the third party services that will fetch the geological location based on the IP address.

IP-API
Price Starts from
€ 13.30
Free Quota
Unlimited
@ 45 / minute

Implementation

// If no IP is supplied, it assumes the current IP address
fetch('http://ip-api.com/json/{ip}')
.then(response =>response.json())
.then(data => console.log(data))
.catch( err => console.log(err) )

IPAPI
Price Starts from
$ 12.00
Free Quota
30,000 Requests / mo
@ 1000 / day

Implementation

fetch('https://ipapi.co/{ip}/json/')
.then(response =>response.json())
.then(data => console.log(data))
.catch( err => console.log(err) )

ipbase
Price Starts from
$ 9.99
Free Quota
150 Requests / mo

Implementation

axios.get('https://api.ipbase.com/v2/info?ip={ip}&apikey={key}')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })

IPWHOIS
Price Starts from
$ 10.99
Free Quota
10,000 Requests / mo

Implementation

// Assumes current IP if no IP is supplied to the endpoint
fetch('http://ipwho.is/{ip}')
.then(response =>response.json())
.then(data => console.log(data))
.catch( err => console.log(err) )

IPGEOLOCATION
Price Starts from
$ 15.00
Free Quota
30,000 Requests / mo
@ 1K / day

Implementation

// This will only give the IP address of the client. Forward this to the server to get the geolocation.
fetch('https://api.ipgeolocation.io/getip')
.then(response =>response.json())
.then(data => console.log(data))
.catch( err => console.log(err) )
// Requires an API key and hence needs to be on the server side.
axios.get("https://api.ipgeolocation.io/ipgeo?apiKey={API_KEY}&ip={SUPPLIED_FROM_WEBSITE}")
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})

IPSTACK
Price Starts from
$ 7.99
Free Quota
100 Requests / mo

Implementation

// Requires an API key and hence needs to be on the server side.
axios.get("https://api.ipstack.com/134.201.250.155?access_key={YOUR_ACCESS_KEY}")
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})

APIIP
Price Starts from
$ 4.79
Free Quota
5,000 Requests / mo

Implementation

// Requires an API key and hence needs to be on the server side.
axios.get("https://apiip.net/api/check?ip=67.250.186.196&accessKey={YOUR_ACCESS_KEY}")
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})

FingerprintJS

This is a premium library which is basically used to remember the device irrespective of the browser, location, OS and technology used. They claim they are upto 99% accurate. This can be used for fraud detection, understanding traffic and improve user experience.

Price Starts from
$ 200 / month
No Free Quota
100K API Calls

Implementation

// Initialize the agent at application startup.
const fpPromise = import('https://openfpcdn.io/fingerprintjs/v4')
  .then(FingerprintJS => FingerprintJS.load())

// Get the visitor identifier when you need it.
fpPromise
  .then(fp => fp.get())
  .then(result => {
    // This is the visitor identifier:
    const visitorId = result.visitorId
    console.log(visitorId)
  })

How to hide your IP address

Privacy is a growing concern now a days. It's the big companies that pay handsomely to know the user's data in bulk so that they can feed it to their AI machines and maximize their profits. For example, see how youtube predicts the next videos we might want to watch based on similar activity across the globe. It's a new norm for the streaming services to capture data, analyze and suggest.

Advertisers and marketing agencies are the best fit for data usage. They want to show the users the right Ad based on the user's internet activity. It may sound like a privacy intrusion but it is not illegal (yet). So, it's very important to hide certain activities of ours to keep our privacy safe. it's a common thing among hackers to hide their IP or even spoof ip (assume someone else's IP address). Few techniques exists today for browsing anonymously.

  • VPN (Virtual Private Network)
  • Proxy Sites
  • TOR

Conclusion

There are many advantages of using geolocation now-a-days such as,

  • Parenting / Child Safety
  • Store locator
  • Access Stolen device
  • Fraud detection.
  • KYC
  • Spam filtering.
  • Location based services like Netflix, Hulu and game servers etc.

It all boils down to how we should implement it and what is the limit when considering not invading one's privacy. Whenever a data breach happens with major companies, it's best to change all the passwords of any online account one has.



Post a comment

I promise, I keep it clean *

Comments

Alert SVG Cookie Consent

This website uses cookies and similar technologies, to enhance your browsing experience and provide personalized recommendations. By continuing to use our website, you agree to our Privacy policy.