简体   繁体   中英

Mapbox - Cannot trigger marker click with "element".click() after clicking on map

I've currently implemented custom markers on the map using the following code:

// extend mapboxGL class so we can edit the click function
    class CustomMarker extends mapboxgl.Marker {
      // new method onClick, sets _handleClick to a function you pass in
      onClick(handleClick) {
        this._handleClick = handleClick;
        return this;
      }

      // the existing _onMapClick was there to trigger a popup
      // but we are hijacking it to run a function we define
      _onMapClick(e) {
        const targetElement = e.originalEvent.target;
        const element = this._element;

        if (this._handleClick && (targetElement === element || 
        element.contains((targetElement)))) {
          this._handleClick();
        }
      }
    };

    const el1 = document.createElement('div');
    el1.id = "marker1";                                                
    el1.style.marginTop = '-'+(36/2)+'px';
    // make a marker and add it to the map
    new CustomMarker(el1)
    .onClick(() => { //when clicked, define the following function
        console.log(1+1);
        })
        .addTo(map);

I have then added a html button to navigate between markers(ie next and previous) which then calls something like document.getElementByID("marker1").click() once clicked.

This button works normally and triggers the marker click, however when I click on the mapbox map once (a single click anywhere on the map), document.getElementByID("marker1").click() does not seem to get called when I click the html button. If I drag the map or double click to zoom in after however, the html button starts to work again. Does anyone know why this is happening?

Something very confusing you have made. Actually MapBox Marker does not have click event, but its Element does. So to make things work, you need to use the following:

marker.getElement().addEventListener('click', function(event: PointerEvent) {
  event.stopPropagation(); // to prevent map click event from triggering as well
  ...
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM