Skip to content

Instantly share code, notes, and snippets.

@malwoodsantoro
Last active November 19, 2020 22:31
Show Gist options
  • Save malwoodsantoro/923bf1001559d2fd6fbb6a6d8cc0a5c9 to your computer and use it in GitHub Desktop.
Save malwoodsantoro/923bf1001559d2fd6fbb6a6d8cc0a5c9 to your computer and use it in GitHub Desktop.
Filter clusters using setData
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Display a map</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
<script src="https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/v1.12.0/mapbox-gl.css" rel="stylesheet" />
<style>
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
#filter {
display: block;
position: relative;
margin: 20px auto;
width: 50%;
height: 40px;
padding: 10px;
border: none;
border-radius: 3px;
font-size: 12px;
text-align: center;
color: #fff;
background: pink;
}
</style>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/@turf/turf@5/turf.min.js"></script>
<div id="map"></div>
<button id="filter">Filter clusters</button>
<script>
mapboxgl.accessToken = 'pk.eyJ1IjoibWFsLXdvb2QiLCJhIjoiY2oyZ2t2em50MDAyMzJ3cnltMDFhb2NzdiJ9.X-D4Wvo5E5QxeP7K_I3O8w';
var map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/mapbox/streets-v11', // style URL
center: [-122.4136, 37.7757], // starting position [lng, lat]
zoom: 9 // starting zoom
});
var randomGeojson = turf.randomPoint(100, {
bbox: [-122.6, 38, -122, 37]
});
map.on('load', function () {
map.addSource('data', {
type: 'geojson',
data: randomGeojson,
cluster: true
}).addLayer({
id: 'clusters',
type: 'circle',
source: 'data',
paint: {
'circle-radius': 20,
'circle-color': 'white'
}
}).addLayer({
id: 'cluster-label',
type: 'symbol',
source: 'data',
layout: {
'text-field': "{point_count}"
}
});
document.getElementById('filter').addEventListener('click', function () {
var sample = turf.sample(randomGeojson, 100);
map.getSource('data').setData(sample);
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment