Currently Available: Need a skilled Software Developer for your next project?
Categories
Laravel

Managing Event Scope in Custom Mapbox Controls

When you add buttons to a custom control on a Mapbox GL JS map, the browser handles clicks on those buttons as DOM events, while Mapbox handles clicks on the map through its own event system. If you keep those two systems separate, a button click will not trigger unrelated map behavior, and you will know exactly which listeners to remove later.

A custom control follows Mapbox’s IControl specification. When you add the control, Mapbox calls its onAdd method with the map instance, and onAdd returns the control’s HTML element. When you remove the control, Mapbox calls its onRemove method so you can clean up. You attach ordinary DOM listeners to the control’s buttons, and you register map.on listeners when the control needs to respond to map events. Because these two APIs handle different event systems, stopping a DOM event does not always cancel Mapbox behavior.

Attach control actions to their DOM elements

Attach a DOM listener directly to the element the user clicks. For example, a reset button can call flyTo from its own click handler without listening for map clicks:

class ResetControl {
  onAdd(map) {
    this._map = map;
    this._container = document.createElement('div');
    this._container.className = 'mapboxgl-ctrl';

    this._button = document.createElement('button');
    this._button.type = 'button';
    this._button.textContent = 'Reset view';
    this._container.appendChild(this._button);

    this._onButtonClick = () => {
      map.flyTo({ center: [0, 0], zoom: 2 });
    };

    this._button.addEventListener('click', this._onButtonClick);
    return this._container;
  }

  onRemove() {
    this._button.removeEventListener('click', this._onButtonClick);
    this._container.remove();
    this._map = undefined;
  }
}

Mapbox’s IControl specification defines how Mapbox adds and removes the control. The mapboxgl-ctrl class gives the container default control styling, though the API reference does not say that it isolates events. When you set the button’s type to button, you prevent the browser from submitting a surrounding HTML form when a user clicks it.

That click handler listens for a browser DOM event. As MDN explains, the browser sends a DOM event along a path of elements through capture and bubble phases. You register Mapbox listeners separately on the map object. In Mapbox’s own examples, gesture handlers use map.on('click', ...) to respond to map clicks, while the marker example attaches a standard DOM listener to the marker element. Pick where you attach the listener based on what the user actually clicks.

Use Mapbox listeners for map behavior

When a control needs to update as the map moves, register a listener on the map itself. Mapbox’s Evented capabilities give Map methods like on and off to register and remove listeners. The IControl specification does not give the control those methods. Store a reference to your callback so onRemove can unregister it:

class MapStatusControl {
  onAdd(map) {
    this._map = map;
    this._container = document.createElement('div');
    this._container.className = 'mapboxgl-ctrl';

    this._onMove = () => {
      this._container.textContent = <code>Zoom: ${map.getZoom().toFixed(1)};
    };

    map.on('move', this._onMove);
    this._onMove();
    return this._container;
  }

  onRemove() {
    this._map.off('move', this._onMove);
    this._container.remove();
    this._map = undefined;
  }
}

This control listens for the map’s move event and updates its text with the current zoom level. If you want to respond to interactions with a specific map layer or featureset, use Mapbox’s addInteraction API, which lets you target handlers and later remove them with removeInteraction. Mapbox documents addInteraction as available starting in GL JS v3.9.0. If you run an earlier version, use supported event methods such as map.on, and check the documentation for the version you have installed.

In both examples, you keep a reference to the callback function so you can remove the listener during cleanup. You pass the same function to removeEventListener that you passed to addEventListener, and you pass the same function to off that you passed to on. If you remove a control without unregistering its map listener, Mapbox keeps calling that listener even after the control’s DOM element is gone.

Stop the event that matches the unwanted behavior

When you call stopPropagation() on a DOM event, you stop the browser from passing that event further along its path through elements. It does not cancel the browser’s default action, and it does not stop other listeners on the same element. Call preventDefault() instead when you want to cancel a default browser action, such as following a link. As MDN notes, use stopImmediatePropagation() only when you also need to block later listeners attached to the same DOM target.

Mapbox map events also have a preventDefault() method, which controls Mapbox’s own behavior. In Mapbox’s draggable-point example, the map event handler calls preventDefault() to stop the map’s default drag behavior. That call does something different from calling preventDefault() on a browser DOM event, and neither method stops DOM propagation.

If clicking a control triggers both its own action and a map handler, calling stopPropagation() once might not fix the problem. Log both the control’s DOM callback and the relevant map.on or interaction callback in the GL JS version you use, so you can see which event fires and which behavior you need to stop.

What I'm building

Delegate tasks. Get software.

Give Vroni a GitHub issue, bug report, spec, or rough idea. It reads the repo, plans the change, writes code, runs checks, and works toward a review-ready pull request.

Take a look at vroni.com

Email updates

Usually a new article and a few links I found interesting.

No spam. Unsubscribe with one click.

Leave a Reply

Your email address will not be published. Required fields are marked *