What needs to be kept in mind when using this API
Before diving into this API, let’s examine some of the minor things that we need to keep in mind as a developer when working with this API. This will prevent us from falling into traps imposed by this API.
- When using this API, browser compatibility plays a huge role. Some older browsers don't support this API. So we need to explicitly handle this problem as there is a chance that one of our users may be using an older browser. In that case, our website breaks down for that specific user as their browser doesn’t support this API. And of course, that’s not what we want. So every time we use this API, we have to provide an extra if-check in our code that simply checks if the browser supports this API or not, and if it is not supported, this API is ignored merely, and our website does not break down for that user.
- When we write code, there are more chances of getting errors rather than success. We have to handle that error explicitly on our own not to hamper our website’s other contents, and the user gets better feedback of why this error happened. There are various errors associated with this API which we need to handle.
We’ll see the above two points in action and learn how to tackle them when we make our web application ‘Location Finder’ using all the core concepts of Geolocation API.
Concepts
We can integrate the Geolocation API in our web application using Navigator.geolocation property that returns a Geolocation object. This object has all the core properties that give our website access to the location of the user’s device. Also, this Navigator.geolocation property causes the user’s browser to ask the user for permission regarding location access. If the user grants the permission, then the browser utilizes its functionality to its full potential to find out the device’s location.
Now this Navigator.geolocation property again contains two methods:
- getCurrentPosition()
- watchPosition()
getCurrentPosition() method:
This method is used to retrieve the user’s current location. This method simply returns the GeolocationPositon object that contains all the information about the user’s location in a successful scenario. If some kind of error occurs, this method returns a GeolocationPositionError object that contains an error code specifying the type of error that occurred that halts the execution of this API.
The GeolocationPositon object will look like this if we log it in our developer console in our web browser.

The latitude, longitude and accuracy properties are always returned. Other properties will be returned if available based on device type.
- coords.latitude: Returns the latitude of the current location in decimal format. This property is always returned.
- coords.longitude: Returns the longitude of the current location in decimal format. This property is always returned.
- coords.accuracy: Returns how accurate the position is. This property is always returned.
- coords.altitude: Returns the altitude in meters above the mean sea level. It is returned only if available.
- coord.altitudeAccuracy: Returns the accuracy of altitude of the current position. Returned only if available.
- coord.heading: Returns where the user is heading as degrees clockwise from North. Returned only if available.
- coord.speed: Returns the speed in meters per second. Returned only if available.
- timestamp: Returns the date/ time of the response. Returned only if available.
The GeolocationPositonError object will look like this if we log it in our developer console in our web browser.

- PERMISSION_DENIED: This property has an error code 1 as its value which signifies the user denied permission to share their location.
- POSITION_UNAVAILABLE: This property has an error code 2 as its value which signifies the user’s location information is unavailable.
- TIMEOUT: This property has an error code 3 as its value which signifies the request to get the user location timed out.
- UNKNOWN_ERROR: This property has an error code 4 as its value which signifies an unknown error has occurred.
The getCurrentPosition() method takes two functions as arguments. The first function will be executed if the process is successful, and the second one will only be executed if some error has occurred.
watchPosition() method:
This method returns the current position of the user. It continues watching the changes encountered(if any) to return the updated position as the user moves like the GPS in a car or smartphone.
This method is useful in GPS-enabled devices as it keeps track of the device’s movement in real-time.
The clearWatch() method is used to stop the watchPosition() method.
The watchPosition() method returns a similar object as the getCurrentPosition() method such that the object returned by it also contains coords property which in turn contains the latitude, longitude, altitude, etc. We can say that both methods have similar properties. Just the difference is that the watchPosition() method always keeps an eye on the device’s position and updates the corresponding object based on changes encountered. We can say that watchPosition() is more dynamic and getCurrentPosition() is static.
Understanding By Example
Let’s make a web application named ‘Location Finder’ that shows the user’s current location. The current location would simply mean the latitude and longitude of the user’s area. If we plot this latitude and longitude on a map, we get the user’s place, such as where they live, i.e, country, state, city, etc. But for this, we need to integrate Google’s Map API to plot this latitude and longitude on it, which is obviously beyond the scope of this article.
The Location Finder app will look like this where the user clicks the button to know their current location in terms of latitude and longitude:

Let’s write some HTML code for this in the index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Geolocation API</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<h1>Location Finder</h1>
<div class="container-content">
<button class="btn">Get Your Location</button>
<div class="location" id="show-location">Your Location</div>
<div class="info">
<h3>No location to show. Click this button to know your location.</h3>
</div>
</div>
</div>
</body>
<script src="script.js"></script>
</html>
Let’s write some CSS inside style.css file:
body {
background-color: rgba(230, 211, 158, 0.959);
}
.container {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
.container-content {
display: flex;
justify-content: flex-start;
align-items: center;
flex-direction: column;
width: 50%;
height: 300px;
background-color: rgb(247, 219, 197);
border: 2px solid rgb(233, 118, 118);
border-radius: 12px;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
position: relative;
}
.container h1 {
font-size: 60px;
color: brown;
}
.info h3 {
font-size: 30px;
text-align: center;
margin-top: 55px;
color: rgb(233, 118, 118);
}
.btn {
width: 40%;
height: 40px;
background-color: rgb(144, 144, 196);
border: 2px solid rgb(155, 99, 78);
color: rgb(77, 18, 18);
font-weight: bold;
font-size: 25px;
margin-top: 30px;
border-radius: 30px;
cursor: pointer;
}
.btn:hover {
background-color: brown;
color: white;
}
.location {
position: absolute;
margin: 20px;
padding: 25px;
width: 50%;
background-color: palevioletred;
top: 75px;
border: 2px solid white;
border-radius: 12px;
font-weight: bold;
font-size: 30px;
text-align: center;
line-height: 1.4;
color: white;
display: none;
}
We’ll manipulate the HTML elements and CSS classes dynamically using javaScript to show the location in the UI in successful circumstances and an error message in the UI if an error occurs.
Now comes the best part that is implementing Geolocation API using javaScript inside script.js file:
const showLoc = document.getElementById("show-location");
const getLoc = document.querySelector(".btn");
const info = document.querySelector(".info");
getLoc.addEventListener("click", locationHandler);
function locationHandler() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function (position) {
console.log(position);
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
console.log(latitude, longitude);
console.log(`https://www.google.com/maps/@${latitude},${longitude}`);
showLoc.innerHTML += `<br>Latitude: ${latitude}<br>Longitude: ${longitude}`;
showLoc.style.display = "block";
info.style.display = "none";
},
function (error) {
console.log(error);
info.removeChild(info.firstChild);
switch (error.code) {
case error.PERMISSION_DENIED:
info.innerHTML = "<h3>You denied the request for Geolocation.</h3>";
break;
case error.POSITION_UNAVAILABLE:
info.innerHTML = "<h3>Location information is unavailable.</h3>";
break;
case error.TIMEOUT:
info.innerHTML = "<h3>The request to get location timed out.</h3>";
break;
case error.UNKNOWN_ERROR:
info.innerHTML = "<h3>An unknown error occurred.</h3>";
break;
}
}
);
}
}
Let’s analyze the above javaScript code line by line:
if (navigator.geolocation) {
// Your code goes here...
}
This line of code checks if the Geolocation API exists or not. If it does not exist then, this if-statement will not be executed at all. This is the point I showed you earlier to keep in mind.
if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function1, function2)
}
Now we are using the getCurrentLocation() method, which takes two functions as arguments. One will be executed in a success case, and the second one will be executed in case of error.
Let’s see the implementation of these functions inside of it. You can also implement these functions outside and simply pass its name inside the getCurrentLocation() method. But I’m implementing it inside of it.
function (position) {
console.log(position);
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
console.log(latitude, longitude);
showLoc.innerHTML += `<br>Latitude: ${latitude}<br>Longitude: ${longitude}`;
showLoc.style.display = "block";
info.style.display = "none";
},
The above code is the implementation of the first function. Here as we know, we get the GeolocationPositionObject by default. I named it simply as position, but you can name it as per your choice. This object has all the properties we discussed earlier, and here we are using the latitude and longitude properties and displaying them in the UI.
function (error) {
console.log(error);
info.removeChild(info.firstChild);
switch (error.code) {
case error.PERMISSION_DENIED:
info.innerHTML = "<h3>You denied the request for Geolocation.</h3>";
break;
case error.POSITION_UNAVAILABLE:
info.innerHTML = "<h3>Location information is unavailable.</h3>";
break;
case error.TIMEOUT:
info.innerHTML = "<h3>The request to get location timed out.</h3>";
break;
case error.UNKNOWN_ERROR:
info.innerHTML = "<h3>An unknown error occurred.</h3>";
break;
}
}
The above code is the implementation of the second function, which handles all the errors that occurred. This function simply takes the properties specified in the error object discussed earlier and displays them accordingly in our UI.
For example, if the user denies permission to share a location, our app will show this message in the UI.

If the location of the user isn’t available, then it shows this message:

Of course, in a successful case, the user gets their current location:

This shows my location. Yours will be different.
Frequently asked questions
Which property is like the GPS in the car?
The current position of the user is returned by watchPosition(). It updates the user’s position as they move, just like the GPS installed in a car. The WatchPosition() method is stopped by the clearWatch() method.
What does getCurrentPosition() returns?
It returns the GeolocationPosition object which contains all the information regarding the device’s current location in case of successful fetching of location. If somehow an error occurs then it will return the GeolocationPositionError object which contains the information regarding what type of error has been encountered and what causes this error to happen.
How can we check the browser’s compatibility for Geolocation API?
We can check by putting the navigator.geolocation property inside an if-check. If it exists, then it proceeds further; otherwise, this API is ignored.
Key takeaways
If you have made it thus far, you will indeed establish a firm grip on this topic. To briefly summarize this, we started with introducing this Geolocation API in a nutshell, and then we examined the specific use-cases where this Geolocation API comes to the fore, and then we dived deep into all its core concepts. And finally, we made a web application using all the core concepts discussed earlier.
So, this web application is just the tip of the iceberg. You can make any type of awesome web application using the concepts discussed in this article. Just explore and code. And for exploration, our posts might be the destination for you. So keep a closer eye on our future posts.