HOW TO GET A USERS LOCATION USING JAVASCRIPT
Detecting the location of a user’s device has become a significant way to make users get access to different contents from the same website or application.
The contents displayed in the application could vary according to the location it detects to provide personalized content for each specified user.
By getting a user’s location, you can determine his country’s currency, language, etc., and then use the information to provide contents that fit that area without breaching their privacy laws.
For example, an application might need to detect the user’s location to know which language to display to its user, or it may need to suggest nearby gas stations or restaurants for its user, and it can only do this by detecting the exact location of its user at that moment.
There are different ways to detect a user’s location using JavaScript
Geolocation API
Get current position function
watchPosition function
clearWatch functionUsing Ip geolocation APIs
Using google maps API
Geolocation API
The javaScript geolocation API is one of the various means of accessing a user’s geographical position.
This API provides access to a device’s location using its GPS, Wi-Fi, IP address, etc.
But for this to work, the API launches a request to access the user’s location. If the user grants permission, you’ll gain access to all data associated with its location, like its longitude, latitude, speed, etc.
You can access the geolocation API by calling window.navigator.geolocation. This grants the app or website access to the location of the device.
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
This code checks if the browser supports geolocation. If supported, it runs the get current position method else; it displays an error message to the user.
If the getCurrent position method is successful, it writes the coordinates of the object in the manner specified in the parameter and then outputs it in the HTML document.
Different methods in the geolocation API can be used to determine the user’s location.
Get current position function
The getCurrentPosition method mainly returns the longitude and latitude of a user’s position.
// Write code here
const successMessage = (position) => {
console.log(position);
};
const errorMessage = (error) => {
console.log(error);
};
navigator.geolocation.getCurrentPosition(successMessage, errorMessage);
When you run this code, you’ll get a popup in your browser telling you to either allow or block the script from accessing your location.
When you click on allow, open up your developer console and see that the successMessage returns the device’s coordinates and timestamp.
It should be something like this:
1. GeolocationPosition {coords: GeolocationCoordinates, timestamp: 1674050273983}
1. coords: GeolocationCoordinates
1. accuracy: 8636.326773021921
2. altitude: null
3. altitudeAccuracy: null
4. heading: null
5. latitude: 6.5568768
6. longitude: 3.3456128
7. speed: null
8. [[Prototype]]: GeolocationCoordinates
2. timestamp: 1674050273983
3. [[Prototype]]: GeolocationPosition
watchPosition function
The watchPosition method is another exciting way as it returns the current position of its user and continues to update the position even as the user moves e.g. tracking device in a vehicle.
This method does this by installing a handler that is called whenever the position of the user’s device changes.
Below is the syntax of the code
const id = navigator.geolocation.watchPosition(successMessage, errorMessage);
clearWatch function
This method puts a stop to the watchPosition method.
By just calling its function and inputting the id of the watchPosition method you’ll be able to stop the watchPosition from functioning.
Below is its code syntax:
navigator.geolocation.clearWatch(id);
Using google maps API
Using the API provided by google maps, developers can now display user location in google Maps.
To use this method, you must first get an API key from google. After getting the key, you can now use the Google Maps API to plot the map using the user’s location.
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<div id="locationInfo"></div>
<script>
var div = document.getElementById("locationInfo");
function getLocationInfo() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, console.log);
} else {
div.innerHTML = "The Browser Does not Support Geolocation";
}
}
function showPosition(position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
// You need to enter your API Key here
var api_key = "";
var img_url = `https://maps.googleapis.com/maps/api/staticmap?center=${lat},${lon}&zoom=14&size=400x300&sensor=false&key=${api_key}`;
div.innerHTML = `<img src='${img_url}'>`;
}
getLocationInfo();
</script>
</body>
</html>
In this code, you use the geolocation function to get the current position of your device and then pass a parameter inside the function if it returns TRUE.
The showPosition parameter passed into the getCurrent Position function collects the latitude and longitude coordinates of the device.
Immediately after that, you create a variable called API key and then pass your google maps API key inside as a string. Then you create a variable containing the URL of your IMG from the API itself.
In the end, you make your div element display the URL, which shows the position of the user’s device.
Ip geolocation APIs
Another way developers can identify a user’s location is by using API services available on the internet, Either free or paid.
Here is a list of websites you can get geolocation APIs
Source: softwareTestingHelp
Conclusion
In this tutorial, you learned how to use various methods to get a users location like the javascript geolocation API, and Google maps API, which can detect the user’s location via google maps, and also outlined a few websites from which you can get geolocation APIs from.
You can use this API to build different apps, like a weather app or even a tracker.