Showing and hiding groups of markers with Mapbox/LeafletJS
I'm using MapboxJS to build a map.
I currently give it a geoJson object of all my markers, which show up with no problem.
As each point has a category, I'd like to add a control layer with checkboxes for each category, so users can show/hide each category.
I've tried loading each marker individually into a layer but I'm getting mapbox errors.
How should I approach this?
Thanks in advance.
Mei
Answers
In the end I managed to write something myself.
I created a global variable to hold the categories I wanted to use, and added a category property to the geoJson object. I also had a global for all the markers.
I then used L.control to add a div, wnd looped through the categories to create checkboxes.
I added an event listener to those inputs, which looped through each marker and either added or removed them from the map (each marker is a layer), depending on what was the checkbox's value.
Details are on the blogpost http://meigwilym.com/custom-marker-controls-with-mapbox-and-leafletjs/
I don't know if this is the best method, but it's the only thing I can get working.
I haven't played with mapbox, but with leafletjs, most of what you need is in http://leafletjs.com/examples/layers-control.html
The code from that page is as follows:
var littleton = L.marker([39.61, -105.02]).bindPopup('This is Littleton, CO.'), denver = L.marker([39.74, -104.99]).bindPopup('This is Denver, CO.'), aurora = L.marker([39.73, -104.8]).bindPopup('This is Aurora, CO.'), golden = L.marker([39.77, -105.23]).bindPopup('This is Golden, CO.'); var cities = L.layerGroup([littleton, denver, aurora, golden]); var grayscale = L.tileLayer(mapboxUrl, {id: 'MapID', attribution: mapboxAttribution}), streets = L.tileLayer(mapboxUrl, {id: 'MapID', attribution: mapboxAttribution}); var map = L.map('map', { center: [39.73, -104.99], zoom: 10, layers: [grayscale, cities] }); var baseMaps = { "Grayscale": grayscale, "Streets": streets }; var overlayMaps = { "Cities": cities }; L.control.layers(baseMaps, overlayMaps).addTo(map);
Based on that code, all you'd need to change is to have multiple elements added to the overlayMaps variable, each with a set of markers.
So you could have:
var myMarkers = L.layerGroup([ L.marker([39.75,-105.1]), L.marker([39.76,-105.3]) ]);
and then you'd modify the definition of overlayMaps in the above code like so:
var overlayMaps = { "Cities": cities, "My Markers": myMarkers };