javascriptleafletgeopositioning

Javascript leafletjs get user position for distance calc


I'm currently trying to create a map application, so far the map loads and the custom information and icons work flawlessly. I'd, however, like to show the user how far away (distance) to the marker on the map.

This code is working, but I'd like the "from" variable to be the users current position instead of a predetermined position.

var onePlace = L.marker([63, 20], {icon: thisIcon}).bindPopup('My text'),
    theOtherPlace = L.marker([65, 20], {icon: thatIcon}).bindPopup('My text');

var to = onePlace.getLatLng();
var from = theOtherPlace.getLatLng();
var distance = from.distanceTo(to);

To set the users position on the map I use the code from their quickstart guide whick looks something like this

    primaryMap.locate({
    });

    primaryMap.on('locationfound', positionFound);
    primaryMap.on('locationerror', positionNotFound);

    function positionFound(e) { 

    var myPosition = L.marker(e.latlng, {
    }).addTo(primaryMap);
}    
    function positionNotFound(e) {
    alert(e.message);
}

But how to get the position that I set here in a later stage is what I'm struggling with.

Basically, what I want is this

var myPos = [??].getLatLng();
var to = onePlace.getLatLng();
var distance = myPos.distanceTo(to);

Sorry for the strange formatting on some of the code, first time posting.

Anyway, if someone could help me out here I'd be incredibly thankful. Been stuck on this one problem for forever and can't seem to find anything helpful in the documentation (probably just don't quite understand it as I'm rather new to this).

Thanks in advance!

UPDATE:

jsfiddle: https://jsfiddle.net/xcyniic/98sy6zxb/27/ Maybe this can help shed some light on what I'm doing / have done wrong.


Solution

  • You get the latlng from the locationfound event.

    primaryMap.on('locationfound', positionFound);
    function positionFound(e) { 
       var myPos = e.latlng;
       var to = onePlace.getLatLng();
       var distance = myPos.distanceTo(to); 
    }
    

    Update

    To get the pos value outside you have to create the variable outside and test if it is not null;

    var myPos = null;
    primaryMap.on('locationfound', positionFound);
    function positionFound(e) { 
       myPos = e.latlng;
       calcDistances();
    }
    
    
    function calcDistances(){
       if(myPos){
          var to = onePlace.getLatLng();
          var distance = myPos.distanceTo(to); +
    
          var to2 = twoPlace.getLatLng();
          var distance = myPos.distanceTo(to2); 
    
          //...
       }
    }
    

    I think that you are thinking wrong. The locationfound event is not called immediately, it is a async service. So you have to calc the distance after the event is called and the user position is found.