0

What i am trying to do is locate user position on map every second.I know i can call a function with setInterval(function(),1000);

I am initializing map with

ionViewDidEnter() {
    this.map = leaflet.map("map").fitWorld();
    this.loadmap();
}

The problem is that I can't reach map from locate function.

function locate(){

var marker;

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

If i delete function locate(); this.map.locate works but because i want to locate user everysecond to track their location i need to call .locate everysecond so i tried to put it in function an call that function with setinterval every second but its not working.Is there any way to locate user without puting .locate inside a function and calling it?

Fruchtzwerg
  • 10,999
  • 12
  • 40
  • 49
rektandpepper
  • 81
  • 1
  • 11
  • Hum, sounds like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)… – ghybs Nov 01 '17 at 00:53

1 Answers1

0

Although your question in not totally clear, if I understand correctly, you are trying to call your locate function as first argument of setInterval, but then you get an error message saying that this.map is undefined or something like that?

In that case, you just need to realize that this refers to the context of the function caller. When you use setInterval (same for setTimeout), the context is no longer your class instance object (the one that has this.map), but the global context. The problem is explained here: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval#The_this_problem

There are several easy solutions, see Referencing "this" inside setInterval/setTimeout within object prototype methods

That being said, since you want to regularly track the user's position, why do not you just rely on the map.locate's watch option? If you are trying to workaround some issue (maybe Leaflet .locate watch option breaks .locate after changing tab Ionic 3?), there is a high chance you should fix that issue, rather than trying to workaround the symptoms.

ghybs
  • 47,565
  • 6
  • 74
  • 99
  • watch option is just not working.it places marker to users first place when user moves marker doenst move it stays initial position. – rektandpepper Nov 01 '17 at 13:09
  • You should investigate on `watch` option not working for you. It works fine for me on Chrome. – ghybs Nov 01 '17 at 13:36