1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Mapbox GL JS クラスター化したポイントの情報を得る

Posted at

mapboxにはclusterという非常に便利な機能があります。
image.png image.png
マップ上に配置した情報を、ズームアウトすることで自動的にいい感じにまとめてくれるんです。

いい感じにまとめてくれた情報を引き出すためには、

    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に自動的に入るようです。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?