Displaying your position in a Leaflet viewer

A colleague asked my whether it would be possible to view the current location of a user in a Leaflet-based GIS viewer. Luckily, this is very easy to do, as explained in this tutorial. All you need to add to the code of my previous example is the following code:

function onLocationFound(e) {
var radius = e.accuracy;
L.circle(e.latlng, radius).addTo(map);
map.on('locationfound', onLocationFound);
map.locate({setView: true, maxZoom: 8});

This does however require a secure http (i.e. https) connection, so make sure that your webserver is set up for using https.

Doing it this way will only show the position that you had when loading the page. It is possible to update the position continuously. This is done by adding the watch: true argument to the locate method. In its current form, this will however recenter the view and zoom to the defined zoom level, and draw a new circle and marker every time an update is received. This can be avoided this way:

var marker;
function onLocationFound(e) {
map.on('locationfound', onLocationFound);
map.locate({setView: false, watch: true});

Instead of creating a new marker, we only set the position. Re-centering the view and setting the zoom level is turned off now. Drawing the accuracy circle is turned off now, but could of course be enabled in the same day that I’ve done with the marker, by pre-defining a variable for it, setting the initial position to [0,0], and then setting the location and radius in the onLocationFound method.

Leave a comment

Het e-mailadres wordt niet gepubliceerd.