Getting User Location using JavaScript's Geolocation API

Updated onbyAlan Morel
Getting User Location using JavaScript's Geolocation API

The JavaScript Geolocation API allows a standardized way for you to request a user's location. This location can be determined using GPS, WiFi, or their IP geolocation, across most devices. You can use this information for a number of things including rich map experiences, better social features, and integrating with third-party services.

In this tutorial, we'll become familiar with JavaScript's Geolocation API, learn how to use it and request the user for their location.

How cool is it to be alive when GPS is freely available to all?

Location Sources

As mentioned before, the Geolocation API uses some or all of the following methods for pinpointing a user's location, each with varying degrees of accuracy. Here are those location sources:

  • Global Positioning System (GPS): This method is valid mostly on mobile devices, and is the most accurate method of them all, some phones can be accurate to within 1 foot, or 30 centimeters.
  • WiFi: This method is available to most mobile devices, even those that do not have a GPS chip inside. This method is accurate to within roughly 10 to 100 meters, depending on the WiFi coverage.
  • IP Geolocation: This method is restricted by region and is the least accurate method by far, hence it is only used as a last-resort method to get a general location on the user.

The browser will attempt to use any or all three of the methods to ensure the most accurate location within a timely fashion.

Using the Geolocation API

The main entrance point to using the Geolocation API is the provided navigator.geolocation object. In this object we have the following methods that we can use:

  • getCurrentPosition(): This determines the user's current location. This returns an object containing the latitude, longitude, accuracy in meters, and many other bits of information.
  • watchPosition(): This listens in on the user for any changes in location. It then calls a function whenever the location changed.
  • clearWatch(): This method removes any handler attached on a watchPosition() call, so the user is no longer being tracked when their location changes.

Before we can use any of this, though, we need to request permission from the user. Let's learn how to do that.

Requesting User Permission

You trust us, right? ;)

You must request user permission to access their location data because it is highly sensitive personal information. If the user is cool with you reading the location, then they will make that clear and you're good to go. Likewise, if they user declines, your application will not be granted access to their location information.

To be fair, the browser will automatically request permission but if the user declines, you'll have to handle that in the logic of your application.

Getting User Location

At this point, hopefully the user has accepted our request to access their location. If so, you can move on to actually getting that data. This is how to request the current position of the user:

JAVASCRIPT
navigator.geolocation.getCurrentPosition(function(position) { const latitude = position.coords.latitude; const longitude = position.coords.longitude; const altitude = position.coords.altitude; const accuracy = position.coords.accuracy; const altitudeAccuracy = position.coords.altitudeAccuracy; const heading = position.coords.height; const speed = position.coords.speed; const timestamp = position.timestamp; // work with this information however you'd like! });

That's literally it. You now have access to the user's latitude, longitude, altitude in meters relative to sea level, the accuracy in meters, the accuracy of the altitude in meters, the direction the device is moving in degrees relative to direct north, and the speed in meters per second.

Don't forget that errors can certainly occur. Here is a better set up for working with the Geolocation API:

JAVASCRIPT
function locationSuccess(position) { const latitude = position.coords.latitude; const longitude = position.coords.longitude; const altitude = position.coords.altitude; const accuracy = position.coords.accuracy; const altitudeAccuracy = position.coords.altitudeAccuracy; const heading = position.coords.height; const speed = position.coords.speed; const timestamp = position.timestamp; // work with this information however you'd like! } function locationError(error) { const code = error.code; const message = error.message; // read the code and message and decide how you want to handle this! } navigator.geolocation.getCurrentPosition(locationSuccess, locationError);

The same set up can be done using watchPosition().

Conclusion

As you hopefully saw, working with the Geolocation API is extremely simple. The API has matured over the years, has widespread browser support, and is stable enough to use in your applications. Have fun with this cool feature and use it to improve your application wherever applicable. Thank you for reading!

Resources

Recommended Tutorial »
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.