Search code examples
javascriptgeolocationleafletmaps

Leafletjs show my location marker instead of hardcoded location


I am trying out Leaflet.js and I have a map with a marker like this:

var marker = new L.marker([5.897818, -1.120009],{
    draggable: true,
    autoPan: true
}).addTo(mymap);

This is showing ok but I want it to appear on my current location instead of the above hardcoded location.

How do I do this?


Solution

  • What you need is to tap into the Geolocation API and use the results of that to create a marker.

    var mymap = L.map('mapid').setView([51.505, -0.09], 13);
    
    navigator.geolocation.getCurrentPosition(position => {
      const { coords: { latitude, longitude }} = position;
      var marker = new L.marker([latitude, longitude], {
        draggable: true,
        autoPan: true
      }).addTo(mymap);
    
      console.log(marker);
    })
    

    There's some issue using the API with Stackoverflow, so here's a link to a working JSFiddle.