0

I'm trying to implement Azure Maps and I'm running into an issue. I'm creating and removing layers at run time, and every time I set a new layer I add the event 'mouseup' on that layer to be able to click on markers, like this:

map.events.add('mouseup', layer, this.onMarkerClick);

When I switch layers, I try to remove the events like this:

map.events.remove('mouseup', layer, this.onMarkerClick);

But when this line is called, nothing seems to happen and the event callback keeps being called when I click a marker. This means that, after switching layers a few times, the onMarkerClick callback gets called multiple times per click.

I tried calling map.events.remove in multiple location in the code, before and after removing the layer itself. Saving the layer to a property and using that in the remove function. Saving the ID in a string property and using it the get the layer from the map and then using that in the remove function. None seemed to work, no matter how I call map.events.remove, the event keeps getting triggered.

Does anyone know what to do? I've tried looking for code examples of maps.events.remove being used for a situation similar to mine but I can't seem to find any...

1 Answers1

0

I believe the issue is with how the callback function is referenced. If the callback functions are like the following, it is difficult to remove the reference:

function onMarkerClick(e) {
}

However, if you modify it to the following, it works better:

var onMarkerClick = (e) => {
}

I've come across this in many different web apps in the past (even when not using Azure Maps), particularly those that use frameworks like React and Angular.

rbrundritt
  • 16,570
  • 2
  • 21
  • 46
  • Here is a thread that shows a similar issue occurring in non-Azure Maps apps: https://stackoverflow.com/questions/10444077/javascript-removeeventlistener-not-working – rbrundritt Apr 21 '23 at 15:56
  • Thanks for the information! I've tried putting the functions inside of private properties and in public vars inside the class, but this doesn't seem to help. I have an inkling that this might have something to do with how Dispatch function of the NgRX Store. Since the Add and Remove functions are being called within a Dispatch their context might have completely changed? Also, when removing and adding a new layer (I used the same LayerID though...) the events still get called. So my current fix is to add a flag if the events are set, and just not setting them again. – Teun Ververs Apr 24 '23 at 12:15