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.
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
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)
})
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)
})
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);
}
});
}
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.
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
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).
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.
These are some of the third party services that will fetch the geological location based on the IP address.
// 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);
})
// 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);
})
// 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);
})
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.
// 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)
})
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.
There are many advantages of using geolocation now-a-days such as,
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.
Do you want to access your webcamera remotely? Then this article is for you.
Calendar Picker / Appointment Setter JS CSS Library. Inspired by Calendly.
Create a local file sharing server with realtime sync feature using Socket IO.
Most beautiful Navbars designed with tailwind css. Fully responsive templates.
Most beautiful dashboards designed with bootstrap 5. Inspired mostly from dribble and other sources.
Most commonly used HTML email templates. Welcome email, sign up, password reset etc.
Checkout our most downloaded payment page ui designed with bootstrap.
Detect user's inactivity and auto logout after certain timeout using various JS features.
Keep the user engaged and gain recurring website traffic. Includes templates.
How to get a user's location using Javascript and other techniques available today.
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.