Filter by marker type
HTML
<script src="https://api.mapbox.com/mapbox.js/v3.2.1/mapbox.js"></script>
<link rel="stylesheet" href="https://api.mapbox.com/mapbox.js/v3.2.1/mapbox.css">
<style>
.filter-ui {
background: #fff;
position: absolute;
top: 10px;
right: 10px;
z-index: 100;
padding: 10px;
border-radius: 3px;
}
</style>
<nav id='filters' class='filter-ui'></nav>
<div id='map'></div>
CSS
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
JavaScript
L.mapbox.accessToken = 'pk.eyJ1IjoidGFrdXRvc3V6dWtpbWFwYm94IiwiYSI6ImNrMjJlMXplcTE4a2czY3F3MWkxZHN4cWkifQ.CRcFM34KAOiPKIbscodOqA';
var map = L.mapbox.map('map')
.setView([37.77396, -122.4366], 12)
.addLayer(L.mapbox.styleLayer('mapbox://styles/mapbox/streets-v11'));
// https://docs.mapbox.com/mapbox.js/assets/data/sf_locations.geojson
var myFeatureLayer = L.mapbox.featureLayer('https://docs.mapbox.com/mapbox.js/assets/data/sf_locations.geojson')
.addTo(map);
// Find and store a variable reference to the list of filters.
var filters = document.getElementById('filters');
// Wait until the marker layer is loaded in order to build a list of possible
// types. If you are doing this with another featureLayer, you should change
// map.featureLayer to the variable you have assigned to your featureLayer.
myFeatureLayer.on('ready', function() {
// Collect the types of symbols in this layer. you can also just
// hardcode an array of types if you know what you want to filter on,
// like var types = ['foo', 'bar'];
var typesObj = {},
types = [];
var features = myFeatureLayer.getGeoJSON().features;
for (var i = 0; i < features.length; i++) {
typesObj[features[i].properties['marker-symbol']] = true;
}
for (var k in typesObj) types.push(k);
var checkboxes = [];
// Create a filter interface.
for (var i = 0; i < types.length; i++) {
// Create an an input checkbox and label inside.
var item = filters.appendChild(document.createElement('div'));
var checkbox = item.appendChild(document.createElement('input'));
var label = item.appendChild(document.createElement('label'));
checkbox.type = 'checkbox';
checkbox.id = types[i];
checkbox.checked = true;
// create a label to the right of the checkbox with explanatory text
label.innerHTML = types[i];
label.setAttribute('for', types[i]);
// Whenever a person clicks on this checkbox, call the update().
checkbox.addEventListener('change', update);
...