mapboxにはclusterという非常に便利な機能があります。
マップ上に配置した情報を、ズームアウトすることで自動的にいい感じにまとめてくれるんです。
いい感じにまとめてくれた情報を引き出すためには、
map.addSource('populations', {
cluster: true, // clusterあり
:
clusterProperties: { // cluster化したときに使用する
'sump': ['+', ['get', 'p50']], // properties['p50']を合計したものがsumpに入る
:
map.addLayer({
id: 'cluster-point',
type: 'circle',
source: 'populations',
filter: ['has', 'sump'], // cluster化しているときにのみ持っている
:
map.on('click', 'cluster-point', (e) => { // cluster化した点をクリックした
const coordinates = wrapCoodinate(e);
const props = e.features[0].properties;
new mapboxgl.Popup()
.setLngLat(coordinates)
.setHTML( `合成数${props['point_count']}<br>総人口${props['sump']}<br>` )
.addTo(map);
});
:
function wrapCoodinate(e){ // 位置を合わせるための処理
const coordinates = e.features[0].geometry.coordinates.slice();
// Ensure that if the map is zoomed out such that
// multiple copies of the feature are visible, the
// popup appears over the copy being pointed to.
while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
}
return coordinates;
}
こんな感じで、cluster化したときに使用するプロパティがe.features[0].properties
に入っています。
また、いくつのポイントがクラスター化したのかはpoint_count
に自動的に入るようです。