Skip to main content

Geolocation

You can use Geolocation API to determine the location of the user. You can then use that location, for example, to center the map around it using the setCenter() method.

function success(pos) {
const center = [pos.coords.longitude, pos.coords.latitude];
map.setCenter(center);
}

function error() {
status.textContent = 'Unable to retrieve your location';
}

function geoFindMe() {
if (!navigator.geolocation) {
status.textContent = 'Geolocation is not supported by your browser';
} else {
status.textContent = 'Locating…';
navigator.geolocation.getCurrentPosition(success, error);
}
}

Try clicking on the top-left control in the example below to pinpoint your current location on the map.