Web APIs

Geolocation API

The Geolocation API provides a way for web applications to retrieve the geographic location of the user's device. This allows for location-aware services such as mapping, navigation, and location-based content.

Introduction

The Geolocation API is accessed via the global navigator.geolocation object. It allows you to request the user's current position, either once or by watching for changes to their position.

Getting the User's Location

To get the user's current location, you can use the getCurrentPosition() method. This method asynchronously retrieves the device's location. It takes up to three arguments:

navigator.geolocation.getCurrentPosition(successCallback, errorCallback, options)

Success Callback

The success callback function receives a single argument: a GeolocationPosition object. This object contains the position information.

Key properties of GeolocationPosition:

GeolocationCoordinates Properties

Error Callback

The error callback function receives a single argument: a GeolocationPositionError object.

Key properties of GeolocationPositionError:

Options Object

The options object can include the following properties:

Example: Getting Current Location


function showPosition(position) {
    const lat = position.coords.latitude;
    const lon = position.coords.longitude;
    document.getElementById("location-info").innerHTML = `
        

Latitude: ${lat}

Longitude: ${lon}

Accuracy: ${position.coords.accuracy} meters

`; } function showError(error) { let message = "An unknown error occurred."; switch (error.code) { case error.PERMISSION_DENIED: message = "User denied the request for Geolocation."; break; case error.POSITION_UNAVAILABLE: message = "Location information is unavailable."; break; case error.TIMEOUT: message = "The request to get user location timed out."; break; case error.UNKNOWN_ERROR: message = "An unknown error occurred."; break; } document.getElementById("location-info").innerHTML = `

Error: ${message}

`; } function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition, showError, { enableHighAccuracy: true, timeout: 5000, maximumAge: 0 }); } else { document.getElementById("location-info").innerHTML = "

Geolocation is not supported by this browser.

"; } }

Click the button to get your location.

Watching for Location Changes

The watchPosition() method is similar to getCurrentPosition(), but it registers a handler function that is called automatically each time the device's location changes.

This is useful for applications that need to track a user's movement over time.

navigator.geolocation.watchPosition(successCallback, errorCallback, options)

The callbacks and options are the same as for getCurrentPosition(). To stop watching, you need to call clearWatch() with the ID returned by watchPosition().

Example: Watching Location Changes


let watchId = null;

function showWatchingPosition(position) {
    const lat = position.coords.latitude;
    const lon = position.coords.longitude;
    document.getElementById("watch-location-info").innerHTML = `
        

Latitude: ${lat}

Longitude: ${lon}

Accuracy: ${position.coords.accuracy} meters

`; } function showWatchingError(error) { let message = "An unknown error occurred."; switch (error.code) { case error.PERMISSION_DENIED: message = "User denied the request for Geolocation."; break; case error.POSITION_UNAVAILABLE: message = "Location information is unavailable."; break; case error.TIMEOUT: message = "The request to get user location timed out."; break; case error.UNKNOWN_ERROR: message = "An unknown error occurred."; break; } document.getElementById("watch-location-info").innerHTML = `

Error: ${message}

`; } function startWatching() { if (navigator.geolocation) { if (watchId === null) { watchId = navigator.geolocation.watchPosition(showWatchingPosition, showWatchingError, { enableHighAccuracy: true, timeout: 10000, maximumAge: 5000 }); document.getElementById("start-watch-btn").textContent = "Stop Watching"; document.getElementById("watch-location-info").innerHTML = "

Watching for location changes...

"; } else { stopWatching(); } } else { document.getElementById("watch-location-info").innerHTML = "

Geolocation is not supported by this browser.

"; } } function stopWatching() { if (watchId !== null) { navigator.geolocation.clearWatch(watchId); watchId = null; document.getElementById("start-watch-btn").textContent = "Start Watching"; document.getElementById("watch-location-info").innerHTML = "

Location watching stopped.

"; } }

Click the button to start watching your location.

Privacy Considerations

The Geolocation API requires user permission before it can access their location. Browsers will typically display a prompt to the user asking for permission. It's important to inform users why you need their location and how you will use it to build trust.

Always handle location data responsibly and consider anonymizing or aggregating data where possible.

Browser Support

The Geolocation API is widely supported by modern web browsers. However, always check specific browser documentation for the latest compatibility information.

Supported browsers include Chrome, Firefox, Safari, Edge, and Opera.

Common Use Cases