This example shows how to extend mapboxGL's Marker
class to add custom functionality on click.
MapboxGL has a very convenient Marker
class that can be used to quickly get markers on the map with a few lines of code (versus the more complex method of adding sources and layers). They behave a bit differently from the rest of the map features because they are actually HTML elements overlaid on the map canvas.
The stock markers are great, and they are SVG so you can color them by passing in a color
option! However, the only interactivity you can easily set up is a popup. When you google 'clickable markers', the examples you find are all using symbol
layers with queryRenderedFeatures
.
I wanted to trigger navigation in a single page app using the stock Markers and determined a simple extension of the class would help me accomplish this. You can also see these markers in action at https://paintthetown.chriswhong.com
Marker
already has an internal method _onMapClick
which is used by the popup functionality. The extension does two things:
-
Adds the method
onMapClick
which takes a function and can be chained with other methods. -
Overrides
_onMapClick
to trigger_handleClick
if it exists.
Some CSS is used to set the pointer to a cursor on hover, and to change the fill.
What would the TypeScript version of this look like?