The Geolocation API comes in handy when building an application that requires access to the precise client location. Among other reasons, you can use location services to provide a custom experience for your clients, or when building an application that requires real time location access. One such application is a fitness app that needs precise, real time location data for tracking a user’s route when taking a walk or jogging.
Because of privacy and safety concerns, the Geolocation API requires permission before you can access user location data. In this day and age, where an extreme state of paranoia is necessary to have some level of privacy and safety online, you should request access to location data gently and responsibly for users to grant permission. Additionally, having possession of such location data comes with greater ethical, moral, and legal responsibility.
Therefore, knowing how to use the Geolocation API only is insufficient. Using it effectively and responsibly is just as important.
The main goal of this article is to introduce you to the main features of the Geolocation API and explain how you can use it effectively. We shall also go above and beyond to highlight your responsibility as a developer when using the Geolocation API and explore the extent of browser support.
Let us start with a brief introduction to the Geolocation API in the section below.
The Geolocation API is a built in API for accessing a client’s device location. Most recent versions of desktop browsers fully support this feature, but you cannot say the same about their mobile counterparts. You, therefore, need to have a fallback option if some browsers do not yet have full native support for this API.
The accuracy of the location data largely depends on the geolocation device used by the client’s device. The Geolocation API can retrieve location data from a GPS if a device has a GPS receiver. It can also infer user location from the IP address, WiFi, and Bluetooth MAC addresses, among others. The Geolocation API is agnostic of the technology the client’s device uses to access geolocation data.
There is no guarantee the geolocation information will be accurate, because this API can also use the IP address to infer user location in the absence of more accurate technologies, such as GPS receivers on the client’s device.
The browser exposes this API via the navigator.geolocation
property. However, as already mentioned, you need to tread with caution, because browser support for this API is far from universal. You should only access it after checking for its availability; this will ensure you have a fallback option in case the client is using a browser that doesn’t support the API.
One fallback option is to use a third party geolocation service:
if ("geolocation" in navigator) { // Access the API navigator.geolocation.getCurrentPosition(successCallback); } else { // Use a third-party geolocation service console.log("Browser does not support the Geolocation API"); }
Before we proceed to the next section, you should note that most or all browsers expose the Geolocation API only if your site is using the secure HTTPS protocol.
Now let’s learn how to access user location using the Geolocation API and some of the key considerations while doing so.
First, we’ll see how you can use the getCurrentPosition
method to access user location. The getCurrentPosition
method takes up to three arguments.
The first (and the only required) argument is a callback function invoked when the API receives the location data successfully. The API passes the device location data as an argument to the callback function.
The second is an optional callback function invoked when an error occurs, and the third argument is an object of options.
The code snippet below is an illustration of how you can use the getCurrentPosition
method to access location data:
const successCallback = (geolocation) => { console.log(geolocation); }; const errorCallback = (error) => { console.log(error); }; const geolocationOptions = { enableHighAccuracy: true, maximumAge: 10000, timeout: 5000, }; if ("geolocation" in navigator) { // Access the API navigator.geolocation.getCurrentPosition( successCallback, errorCallback, geolocationOptions ); } else { // Use a third-party geolocation service console.log("Browser does not support the Geolocation API"); }
That is all it takes to access your client’s device location using the getCurrentPosition
method of the Geolocation API.
However, there are a few best practices to know when using this method to access client location.
Do not attempt to access the Geolocation API immediately on page load. If you do, the API will instantly request the user for access to their location.
This provides for a poor user experience and will freak out some of your clients. Try to be extremely patient and gentle when asking for consent to get your clients to trust you with their location data.
It is good practice to present the user with an explanation of why you need their location data and how you intend to use it before the browser displays a prompt with a “this site wants to know your location” message.
Additionally, you can also include a link to your privacy policy and terms of service.
Be explicit about the need for location data in your call to action directive. For example, if you have a button or link with the text “show stores near me,” you can also provide an accompanying message like, “this service requires access to your location” beside the button or as a tooltip.
Therefore, it won’t be surprising if the browser asks the user to grant access to their location.
If a client is using a device with a GPS receiver like a mobile phone, the time it takes to access the location data, among other factors, depends on the atmospheric condition and location of the user. The GPS can take up to a minute or more to triangulate the device’s location.
You can decide what the acceptable waiting time is, and timeout the operation if it takes too long.
Furthermore, setting a timeout is equally useful if a user intentionally or unintentionally fails to respond to the permission request. You can then use an alternative third party geolocation service or show a nice message, like “The application took too long to access your location. Perhaps try again later.”
An error may occur, or a user can decline to grant access to location data. You can always pass another callback function as a second argument and use it to gracefully handle errors.
This is useful because browsers have features for disabling location lookup. If the user disables geolocation lookup in their browser or declines to grant permission, the second callback function passed to the getCurrentPosition
method will be invoked with the error object. You can then take appropriate action thereafter.
Sometimes accessing geolocation data once may not be sufficient, especially when the user is on the move. You will have to use the watchPosition
method to access location data whenever there is a change in the user’s location.
The watchPosition
method is similar to the getCurrentPosition
method. The first argument is a callback function invoked when the API receives location data, and it is also the only required argument. The second argument is also a callback function, but it is optional. It is invoked in case of an error. The third argument is an optional object.
Unlike the getCurrentPosition
method, the watchPosition
method returns a numeric ID that uniquely identifies the position watcher. You can use this ID to stop watching the user location with the clearWatch
method.
The first callback function you pass to the watchPosition
method is invoked multiple times to update client location if they are on the move or when more accurate geolocation data becomes available.
The code block below illustrates how you can use the watchPosition
method. It is very similar to the getCurrentPosition
method. The only difference is in the unique number ID the watchPosition
method returns:
const successCallback = (position) => { console.log(position); }; const errorCallback = (error) => { console.log(error); }; let geolocationID; if ("geolocation" in navigator) { // Access the API geolocationID = navigator.geolocation.watchPosition( successCallback, errorCallback ); } else { // Use a third-party geolocation service console.log("Browser does not support the Geolocation API"); }
That is all there is to the watchPosition
method of the Geolocation API. However, there are certain things you should take into consideration when using this method.
The goal of this article is to teach you how to use the Geolocation API in the best possible way. Therefore, all the considerations highlighted in the previous subsection also apply when using the watchPosition
method.
Additionally, you should take note of the following:
As highlighted above, watching user location necessitates multiple invocations of the watchPosition
method. This, by all means, is a computationally expensive operation. It requires computing resources to perform.
With the widespread use of mobile devices, you need to be mindful of the impacts of repeatedly invoking the watchPosition
method on your users in terms of performance. Similarly, a mobile device using a GPS receiver will listen for satellite signals when triangulating device location. Constantly watching user location can drain lots of battery power.
As mentioned above, watching user locations can be an expensive operation. You should use the watchPosition
method if you are sure doing so will improve the quality of service for your clients.
If you must watch user location, it is best to stop tracking if the geolocation information ceases to change. Make sure to stop watching when it is no longer necessary to watch user location. We shall highlight how to stop watching user locations in the next section.
If you start watching user location, then you certainly will have to stop watching at some point.
You can use the clearWatch
method to stop watching user location. The clearWatch
method takes the unique watch ID returned by the watchPosition
method as an argument:
// Start watching user location const geolocationID = navigator.geolocation.watchPosition( successCallback, errorCallback ); // Stop watching after 5 seconds setTimeout(function () { navigator.geolocation.clearWatch(geolocationID); }, 5000);
The code snippet above is an illustration of how you can use the clearWatch
method to stop watching user location.
Now that you know what the Geolocation API is and how to use it, let us look at your responsibilities as a developer.
When using this API, you are essentially asking users to trust you with their location. Such sensitive data comes with lots of responsibilities on your part.
Highlighted below are some of these responsibilities. They mainly center around data protection and privacy policy. It may not necessarily be an exhaustive list, but it covers most of the basics.
As you use the Geolocation API, it is your responsibility to comply with the relevant privacy and data protection laws within your jurisdiction. You should be aware that some data privacy and security legislation transcend territorial boundaries.
One fine example is the General Data Protection Regulation (GDPR) passed by the European Union. If your application is used by people in the EU, noncompliance with the GDPR will attract tough penalties irrespective of where you are in the world.
When you use the Geolocation API, you are asking users to grant access to sensitive data. Therefore, it is your responsibility to provide access to your terms of service and privacy policy.
Providing terms of service and privacy policy will inform the users of the privacy implications of using the service and help them make informed decisions.
Probably not many will read the terms of service and privacy policy, but you will have done your part as a developer. You can also go ahead and present the, “by using this service, you agree to our terms of service and privacy policy” message before the service becomes available.
You should be explicit in how you intend to use the geolocation data in your terms of service. You should also use the data for the specified purpose and discard it thereafter unless the user gave you express permission to do otherwise.
If you intend to persist the geolocation data in a database, you should give users the liberty and the means to delete or update the data if they so wish.
The responsibility of safeguarding the privacy of your clients lies squarely on your shoulders. One possible safeguard is to encrypt the data. Data encryption is crucial, especially if you intend to save the data to a database or the user has granted you express permission to transmit the data to a third party.
As already highlighted in the introduction section, some browsers, especially mobile browsers, have yet to implement some functionalities of the Geolocation API.
Support in mobile browsers notwithstanding, most recent versions of popular modern browsers support the Geolocation API. Your safest bet is to have a fallback option if your goal is to provide support for all browsers. One typical example of a fallback option is to use third-party geolocation services, which mostly rely on the less accurate IP addresses to infer geolocation data.
The image below shows the browser support for the Geolocation API according to caniuse.
As mentioned in the subsections above, the Geolocation API will likely always be your first choice if you want to access your client’s location data in the browser. For privacy reasons, the browser needs user permission before granting your application access to user location data.
The location data is only as accurate as the geolocation technology the client’s device uses. The Geolocation API is agnostic of the underlying geolocation technology used by the device. It can use GPS, IP address, Bluetooth, and WiFi MAC addresses, among others, to infer user geolocation. Therefore the location may not always be accurate. Mobile devices with GPS receivers tend to provide more accuracy.
When using the Geolocation API, there are best practices that you need to follow. They will increase your chances of getting access to user location data and build confidence in your clients about their safety and privacy. It will also increase the possibility of adopting your product and services.
You are responsible for providing privacy and data protection after gaining access to the clients’ location data. Most countries have privacy and data protection legislation that may apply to you. Failure to comply with them will land you in trouble.
Hopefully, you enjoyed reading this article. Do you have more tips on how to effectively and responsibly use the Geolocation API? Let me know in the comments section below.
Debugging code is always a tedious task. But the more you understand your errors, the easier it is to fix them.
LogRocket allows you to understand these errors in new and unique ways. Our frontend monitoring solution tracks user engagement with your JavaScript frontends to give you the ability to see exactly what the user did that led to an error.
LogRocket records console logs, page load times, stack traces, slow network requests/responses with headers + bodies, browser metadata, and custom logs. Understanding the impact of your JavaScript code will never be easier!
Hey there, want to help make our blog better?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowCompare Prisma and Drizzle ORMs to learn their differences, strengths, and weaknesses for data access and migrations.
It’s easy for devs to default to JavaScript to fix every problem. Let’s use the RoLP to find simpler alternatives with HTML and CSS.
Learn how to manage memory leaks in Rust, avoid unsafe behavior, and use tools like weak references to ensure efficient programs.
Bypass anti-bot measures in Node.js with curl-impersonate. Learn how it mimics browsers to overcome bot detection for web scraping.
2 Replies to "What you need to know while using the Geolocation API"
You can use the IP geolocation API such as https://www.ip2location.com because it is less intrusive.
In the world, https://ipstack.com/ provides one of the top IP to geolocation APIs and global IP database services.