Skip to content

Instantly share code, notes, and snippets.

@jbranigan
Last active October 1, 2020 15:49
Show Gist options
  • Save jbranigan/4981614f1c6db0a2c94ba540f5ac1782 to your computer and use it in GitHub Desktop.
Save jbranigan/4981614f1c6db0a2c94ba540f5ac1782 to your computer and use it in GitHub Desktop.
Mapbox single country label and road filtering using iso_3166_1 and match
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Draw GeoJSON points</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
<script src="https://api.mapbox.com/mapbox-gl-js/v1.10.1/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/v1.10.1/mapbox-gl.css" rel="stylesheet" />
<style>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
</style>
</head>
<body>
<div id="map"></div>
<script>
mapboxgl.accessToken = 'pk.eyJ1IjoiamJyYW5pZ2FuIiwiYSI6ImNrYXIwZDhoejA2MHkyeG1zbnZkZDY4Z2oifQ.Xc8xWfKTr5xFOd7cNnXxqQ';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: [5.5045, 52.219],
zoom: 6.5
});
map.on('load', function() {
map.addSource('countries-geojson', {
'type': 'geojson',
'data': {
'type': 'FeatureCollection',
'features': []
}
});
map.addLayer({
'id': 'country',
'type': 'line',
'source': 'countries-geojson',
'layout': {},
'paint': {
'line-color': 'red',
}
});
const layers = map.getStyle().layers;
layers.forEach((layer) => {
const currentFilters = map.getFilter(layer.id);
if (layer.id.includes('label') || layer.id.includes('shield') || layer.id.includes('road')) {
if (currentFilters) {
map.setFilter(layer.id, ['all', currentFilters, ["match", ["get", "iso_3166_1"], ["NL"], true, false]]);
}
else {
map.setFilter(layer.id, ["match", ["get", "iso_3166_1"], ["NL"], true, false]);
}
}
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment