Search code examples
javascriptionic-frameworkgeolocationleaflet

Leaflet .locate watch option breaks .locate after changing tab Ionic 3


I have one function called loadmap(){} where im creating map.Im loading this function with

 ionViewDidEnter() {
this.loadmap();


  }

Inside loadmap i have

  this.map = leaflet.map("map").fitWorld();

thats how i initialize map

This is how i remove map when user changes tab.

ionViewDidLeave(){

    this.map.remove();


  }

This is my .locate function:

var usermarker;


  this.map.locate({
    setView: true,
    maxZoom: 120,
    watch:true,
    enableHighAccuracy:true



  }).on("locationfound", e => {
    if (!usermarker) {
      usermarker = new L.marker(e.latlng).addTo(this.map);
  } else {
      usermarker.setLatLng(e.latlng);
  }
}).on("locationerror", error => {
  if (usermarker) {
      this.map.removeLayer(usermarker);
      usermarker = undefined;
  }
});

The problem is in first time .locate function works.but if i change tab and go back to map tab .locate function doesnt work.if i remove watch option it works.

Thanks


Solution

  • You have to call map.stopLocate() besides map.remove():

    Stops watching location previously initiated by map.locate({watch: true})

    Live demo: https://plnkr.co/edit/PKMPjfX3zD3QdWmEI0iX?p=preview (use the "Toggle map" button to simulate your changing tabs)

    That being said, it is true that Leaflet could automatically do this when using the remove map method. => Merged in PR Leaflet/Leaflet#5893