Get the user’s location using the GPS with Leaflet geolocate control

This tutorial shows how to use the geolocate control with Leaflet to get the user’s location using the GPS or the browser location.

Unlock the power of GPS and Leaflet geolocate control to access your user’s location effortlessly and enhance your application’s functionality.

NPM module setup


npm install --save @maptiler/leaflet-maptilersdk leaflet
import { MaptilerLayer, MapStyle } from '@maptiler/leaflet-maptilersdk';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';

const key = 'YOUR_MAPTILER_API_KEY_HERE';

// but this is going to be superseded by the `geolocate: true` options
const map = L.map('map').setView([0, 0], 1);
const mtLayer = new MaptilerLayer({
  apiKey: key,
  style: MapStyle.STREETS, // optional
  geolocate: true //set the initial view to the user's location
}).addTo(map);

Replace YOUR_MAPTILER_API_KEY_HERE with your own API key. Make sure to secure the key before you publish it.

Get the user's location using the GPS with Leaflet geolocate control

Geolocate control

Examples

Get user location using GPS and Leaflet geolocate control.

Was this helpful?