This tutorial uses JavaScript’s GeoLocation API to get users’ locations. This API call returns location coordinates and other geolocation details.
The following quick example has a function getLatLong() that uses the GeoLocation API. It calls the navigator.geolocation.getCurrentPosition(). This function needs to define the success and error callback function.
On success, it will return the geolocation coordinates array. The error callback includes the error code returned by the API. Both callbacks write the response in the browser console.
The user’s location is privacy-sensitive information. We need to be aware of it before working on location access. Since it is sensitive, the browser and the underlying operating system will not give access to the user’s location information by default.
Important! The user has to,
In an earlier article, we have seen how to get geolocation with country by IP address using PHP.
function getLatLong() {
// using the JavaScript GeoLocation API
// to get the current position of the user
// if checks for support of geolocation API
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function(currentPosition) { console.log(currentPosition)},
function(error) { console.log("Error: " + error.code)}
);
} else {
locationElement.innerHTML = "JavaScript Geolocation API is not supported by this browser.";
}
}
The below code is an extension of the quick example with Geo Location API. It has a UI that has control to call the JavaScript function to get the user’s current position.
The HTML code has the target to print the location coordinates returned by the API.
The JavaScript fetch callback parameter includes all the geolocation details. The callback function reads the latitude and longitude and shows them on the HTML target via JavaScript.
<!DOCTYPE html>
<html>
<head>
<title>Get User Location from Browser with JavaScript</title>
<link rel='stylesheet' href='style.css' type='text/css' />
<link rel='stylesheet' href='form.css' type='text/css' />
</head>
<body>
<div class="phppot-container">
<h1>Get User Location from Browser with JavaScript</h1>
<p>This example uses JavaScript's GeoLocation API.</p>
<p>Click below button to get your latitude and longitude
coordinates.</p>
<div class="row">
<button onclick="getLatLong()">Get Lat Lng Location
Coordinates</button>
</div>
<div class="row">
<p id="location"></p>
</div>
</div>
<script>
var locationElement = document.getElementById("location");
function getLatLong() {
// using the JavaScript GeoLocation API
// to get current position of the user
// if checks for support of geolocation API
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
displayLatLong, displayError);
} else {
locationElement.innerHTML = "JavaScript Geolocation API is not supported by this browser.";
}
}
/**
* displays the latitude and longitude from the current position
* coordinates returned by the geolocation api.
*/
function displayLatLong(currentPosition) {
locationElement.innerHTML = "Latitude: "
+ currentPosition.coords.latitude
+ "<br>Longitude: "
+ currentPosition.coords.longitude;
}
/**
* displays error based on the error code received from the
* JavaScript geolocation API
*/
function displayError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
locationElement.innerHTML = "Permission denied by user to get location."
break;
case error.POSITION_UNAVAILABLE:
locationElement.innerHTML = "Location position unavailable."
break;
case error.TIMEOUT:
locationElement.innerHTML = "User location request timed out."
break;
case error.UNKNOWN_ERROR:
locationElement.innerHTML = "Unknown error in getting location."
break;
}
}
</script>
</body>
</html>
In the above example script, we have a function for handling errors. Including the function when getting user location via the browser is essential. Because, by default, the user’s permission settings will be disabled.
So most of the time, when this script is invoked, we will get errors. So we should have this handler declared and passed as a callback to the getCurrentPosition function. On error, JavaScript will call this error handler.
Following is the output format returned by the JavaScript geolocation API. We will predominantly use latitude and longitude from the result. ‘speed’ may be used when getting the dynamic location of the user. We will see about that also at the end of this tutorial.
{
coords = {
latitude: 30.123456,
longitude: 80.0253546,
altitude: null,
accuracy: 49,
altitudeAccuracy: null,
heading: null,
speed: null,
},
timestamp: 1231234897623
}
We can get the user’s location by passing the latitude and longitude like below. There are many different service providers available, and below is an example using Google APIs.
const lookup = position => {
const { latitude, longitude } = position.coords;
fetch(`http://maps.googleapis.com/maps/api/geocode/json?latlng=${latitude},${longitude}`)
.then(response => response.json())
.then(data => console.log(data)); //
}
Here is an exciting part of the tutorial. How will you get a user’s dynamic location, that is, when he is on the move?
We should use another function of GeoLocation API to get dynamic location coordinates on the move. The function watchPosition() is used to do this via JavaScript.
To test this script, run it in a mobile browser while moving in a vehicle to get the user’s dynamic location.
I have presented the code part that is of relevance below. You can get the complete script from the project zip; it’s free to download below.
var locationElement = document.getElementById("location");
function getLatLong() {
// note the usage of watchPosition, this is the difference
// this returns the dynamic user position from browser
if (navigator.geolocation) {
navigator.geolocation.watchPosition(displayLatLong,
displayError);
} else {
locationElement.innerHTML = "JavaScript Geolocation API is not supported by this browser.";
}
}