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);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="robots" content="noindex">
<title>Get the user's location using the GPS with Leaflet geolocate control | NPM example</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div id="map"></div>
<script type="module" src="./main.js"></script>
</body>
</html>
#map {position: absolute; top: 0; right: 0; bottom: 0; left: 0;}
Replace YOUR_MAPTILER_API_KEY_HERE with your own API key. Make sure to secure the key before you publish it.