**文書の過去の版を表示しています。**
markerClusterGroupを使用して、Leafletのマーカーをクラスター化する
markerClusterGroupを使用することで、Leafletの地図上にプロットしたマーカーのクラスタリングを行うことができる。
markerClusterGroupの読み込み
#Leafletの読み込み <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css" /> <script src="https://unpkg.com/leaflet@1.3.1/dist/leaflet.js" ></script> #MarkerClusterGroupの読み込み <script src="https://unpkg.com/leaflet.markercluster@1.3.0/dist/leaflet.markercluster.js"></script> <link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.3.0/dist/MarkerCluster.css" /> <link rel="stylesheet" href="https://unpkg.com/leaflet.markercluster@1.3.0/dist/MarkerCluster.Default.css" />
地図の描画
//地図を描画するDOM要素を選択し、デフォルトの緯度経度、縮尺を設定。 var map = L.map("map").setView([35.7,139.7],11); //地図データの取得元とZoom範囲を設定する。 var tile = L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png',{minZoom:2,maxZoom:18}).addTo(map);
マーカーの描画とクラスターグループの作成
markerClusterGroup
オブジェクトを作成する。
var markers = L.markerClusterGroup();
データの緯度経度の情報を元にマーカーを描画し、markerClusterGroupオブジェクトのレイヤーに追加する。
dataset.forEach(data => { var marker = L.marker([data.latitude, data.longitude]); markers.addLayer(marker); });
markerClusterGroupオブジェクトをmapオブジェクトのレイヤーに追加する。
map.addLayer(markers);