Introduction
Nowadays, the most application requires you to know the user's location, like delivery app or eCommerce websites. So today, this article describes how you get the user's location with user consent in Javascript.
Today, most delivery websites want to give ease of use and automatically put some fields in the address. So for that, you want to know the user's location according to the longitude and latitude. This is possible. So let's start this article on how we can get the Longitude and Latitude of the visited user using Geolocation API.
GeoLocation API
The Navigator.geolocation is a read-only property that returns the Geolocation object that can be used to locate the user's position. This is only available when the user approves it.
Browser Support
It is always better to first check with the browser whether it supports the Geolocation Web API. So below is the code to check this.
if (window.navigator.geolocation) {
// code
} else {
alert('Sorry, your browser does not support geolocation API')
}
The getCurrentPosition method returns the user coordinates, which take the two arguments success and error
navigator.geolocation.getCurrentPosition(successCallback,failureCallback);
if (window.navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
alert('Sorry, your browser does not support geolocation API')
}
SuccessCallback
function showPosition(position) {
alert("Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude);
}
FailureCallback ( Error Handling)
function showError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
alert("User not accept the request for Geolocation.")
break;
case error.POSITION_UNAVAILABLE:
alert("Location information is unavailable.")
break;
case error.TIMEOUT:
alert("The request timed out")
break;
case error.UNKNOWN_ERROR:
alert("An error occurred")
break;
}
}
Output
First, Browser asks the user to give permission to access their location then only it can get the coordinates.
The other properties that getCurrentPosition returns, if available, are Latitude, Longitude always returned, and other properties -
altitude |
The altitude in meters above the mean sea level |
altitudeAccuracy |
The altitude accuracy of the position |
heading |
The heading as degrees clockwise from North |
speed |
The speed in meters per second |
timestamp |
The date/time of the response |
These are returned only if available.
Pro Tip - Geolocation is much more accurate for devices with GPS, like smartphones.
Conclusion
So this is the small code API through which you can get the user coordinates in terms of latitude and longitude with the user's permission.