Search code examples
leafletangular-leaflet-directive

How to Calculate the distance between two markers in leaflet using distanceTo() method?


I need your help to calculate the distance between two markers using distanceTo() method. I tried to implement that in Angular, but the following error has occurred in the console:

Here's the code:

display() {

    let from_select = $('#from_station option:selected').val();
    let to_select = $('#to_station option:selected').val();

    let filteredStations1 = this.stationsNames.filter( function(currentStation1:any) {
      return currentStation1.name == from_select;
    })

    let filteredStations2 = this.stationsNames.filter( function(currentStation2:any) {
      return currentStation2.name == to_select;
    })

    let from = JSON.parse(filteredStations1[0].loc_stringify);
    let to = JSON.parse(filteredStations2[0].loc_stringify);

    console.log(from.distanceTo(to));
  
  }

The error:

ERROR TypeError: from.distanceTo is not a function
    at AddEditTripComponent.display (main.js:1125)
    at AddEditTripComponent_Template_button_click_16_listener (main.js:1174)
    at executeListenerWithErrorHandling (vendor.js:58037)
    at wrapListenerIn_markDirtyAndPreventDefault (vendor.js:58072)
    at HTMLButtonElement.<anonymous> (vendor.js:76806)
    at ZoneDelegate.invokeTask (polyfills.js:9646)
    at Object.onInvokeTask (vendor.js:71332)
    at ZoneDelegate.invokeTask (polyfills.js:9645)
    at Zone.runTask (polyfills.js:9414)
    at ZoneTask.invokeTask [as invoke] (polyfills.js:9727)

Solution

  • You want to call the function distanceTo of a object that you get from JSON.prase, this object don't have the function distanceTo. You need first to create a Marker or a LatLng Object.

    var fromLatLng = L.latLng(from);
    var toLatLng = L.latLng(to);
    
    var dis = fromLatLng.distanceTo(to);
    console.log(dis);