Map Live User Location using Leaflet.js
Last updated: December 11, 2022.
You can map the live location of a user by using the native HTML5 Geolocation API to get a user’s current location and the Leaflet.js library.
Setting up the HTML5 Geolocation API
To map the current position of a user requires getting their coordinates. These can be obtained using the HTML5 Geolocation API.
This also provides an accuracy measure in metres that can also be plotted to provide an indication of certainty about the user’s position.
const options = {
enableHighAccuracy: true,
// Get high accuracy reading, if available (default false)
timeout: 5000,
// Time to return a position successfully before error (default infinity)
maximumAge: 2000,
// Milliseconds for which it is acceptable to use cached position (default 0)
};
navigator.geolocation.watchPosition(success, error, options);
// Fires success function immediately and when user position changes
function success(pos) {
const lat = pos.coords.latitude;
const lng = pos.coords.longitude;
const accuracy = pos.coords.accuracy; // Accuracy in metres
}
function error(err) {
if (err.code === 1) {
alert("Please allow geolocation access");
// Runs if user refuses access
} else {
alert("Cannot get current location");
// Runs if there was a technical problem.
}
}
Note that attempting to access the user's current position requires the user's permission. This will be prompted automatically by the browser.
Mapping the position with Leaflet.js
Importing Leaflet
To start using it, Leaflet.js must be imported into your project.
The necessary files are a stylesheet and script, which should be imported in this order:
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css" integrity="sha256-kLaT2GOSpHechhsozzB+flnD+zUyjE2LlfWPgU04xyI=" crossorigin="" />
<script src="https://unpkg.com/leaflet@1.9.3/dist/leaflet.js" integrity="sha256-WBkoXOwTeyKclOHuWtc+i2uENFpDZ9YPdf5Hf+D7ewM=" crossorigin=""></script>
Alternatively, you can install Leaflet via npm:
npm install leaflet
The files will then be available to import locally from node_modules/leaflet/dist
.
Using Leaflet
To inject a map onto the page, you need to create an element into which it should be inserted.
Make sure the element has a width
set in CSS to determine the width of the map.
<style>
#map { height: 350px }
</style>
<body>
<div id="map"></div>
</body>
If you have imported Leaflet, it will now be available to you in JavaScript under the reference L
.
You can create the map by calling function stored on the L
object.
Plotting the user position on a map involves feeding user coordinates into a mapping service via Leaflet.
A popular option is OpenStreetMap, which is used in the example below:
const map = L.map('map');
// Initializes map
map.setView([51.505, -0.09], 13);
// Sets initial coordinates and zoom level
L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© OpenStreetMap'
}).addTo(map);
// Sets map data source and associates with map
let marker, circle, zoomed;
navigator.geolocation.watchPosition(success, error);
function success(pos) {
const lat = pos.coords.latitude;
const lng = pos.coords.longitude;
const accuracy = pos.coords.accuracy;
if (marker) {
map.removeLayer(marker);
map.removeLayer(circle);
}
// Removes any existing marker and circule (new ones about to be set)
marker = L.marker([lat, lng]).addTo(map);
circle = L.circle([lat, lng], { radius: accuracy }).addTo(map);
// Adds marker to the map and a circle for accuracy
if (!zoomed) {
zoomed = map.fitBounds(circle.getBounds());
}
// Set zoom to boundaries of accuracy circle
map.setView([lat, lng]);
// Set map focus to current user position
}
function error(err) {
if (err.code === 1) {
alert("Please allow geolocation access");
} else {
alert("Cannot get current location");
}
}