0
votes

I'm trying to fathom how to show / hide MapBox Markers based on a dynamic toggle list.

At the moment, I have a MapBox map and I can successfully add a bunch of Markers to it with this code;

for (var i = 0; i < markers.length; i++) {
    var la = markers[i]['lat'];
    var lo = markers[i]['long'];
    var siteName = markers[i]['Site Name']
    var siteType = markers[i]['Site Type']
    var siteAddr = markers[i]['Address']
    var colour = markers[i]["Colour"];

    new mapboxgl.Marker({
    "color":colour
    })
    .setLngLat([lo,la])
    .setPopup(new mapboxgl.Popup()
    .setHTML("<b>" + siteName + "</b><br>(" + siteType + ")<br>" + siteAddr )).addTo(map);
}

This all works fine and I get a nice map.

I then took inspiration from this example and tried to show/hide markers based on siteType, like is shown in here; https://docs.mapbox.com/mapbox-gl-js/example/filter-markers/

The problem I have is that the example is based around using Layers, and my map uses Markers.

I've been faffing around trying various things, but ultimately I'm not even sure on what strategy to adopt, let alone the code needed to support it.

Is show/hide Markers with a toggle list possible, or do I have to use layers to achieve this? If possible, how? And how, with Layers, do you customise individual locations so they can have individual popups? I'm not after somebody spoon feeding me code (although I wouldn't say no!), mainly I'm after a suggestion / discussion around a strategy I can adopt to meet my goal.

Thanks!

1

1 Answers

0
votes

Markers and layers behave completely differently.

With layers, you manage the layer as a whole. You can hide/show the layer by toggling its visibility, or hide/show individual elements by modifying the filter.

With markers, you manage each marker individually. You could hide/show a marker by using CSS (eg, changing its opacity to 0), but more often, you simply remove the marker with Marker.remove() and add it again later.