Google Maps APIで複数のマーカーをまとめる方法
2024/01/13
Google Maps APIでマーカーを複数表示し、近隣のエリアごとにまとめて表示させたかった。調べたところGoogle公式でAPIが用意されていた。以下に作成方法のメモ。
サンプル
https://taitan916.info/sample/clusterer/
事前準備
マーカーの表示と自動ズームが入ったマップの作成に関しては以前の記事のものを使用した。
https://taitan916.info/blog/?p=2403
ライブラリの読み込み
以下でライブラリを読み込んでおく。
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js"></script>
JavaScript部分
<script>
var mapData = [
{ 'name':'大阪城', 'x':'34.687315', 'y':'135.526201'},
{ 'name':'通天閣', 'x':'34.644885', 'y':'135.494516'},
{ 'name':'道頓堀', 'x':'34.668548', 'y':'135.502715'},
{ 'name':'京都タワー', 'x':'34.987574', 'y':'135.759362'},
];
var minLat = 999;
var maxLat = 0;
var minLng = 999;
var maxLng = 0;
var currentWindow = null;
var latlng = new google.maps.LatLng(mapData[0].x, mapData[0].y);
var myOptions = {
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//マーカークラスタリング用の配列
var clusterer = [];
for (var key in mapData){
var marker_data = makeMarker(mapData[key]);
//マーカー情報をクラスタリング用の配列に突っ込む
clusterer.push(marker_data);
}
//マップにマーカークラスターを追加
var markerCluster = new MarkerClusterer(map, clusterer, {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
autoZoom( maxLat, minLat, maxLng, minLng );
function makeMarker( mapData ){
if( !mapData ) return false;
if(mapData.x < minLat) minLat = mapData.x;
if(mapData.x > maxLat) maxLat = mapData.x;
if(mapData.y < minLng) minLng = mapData.y;
if(mapData.y > maxLng) maxLng = mapData.y;
var marker = new google.maps.Marker({
position : new google.maps.LatLng(mapData.x,mapData.y),
map: map
});
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', function() {
if( currentWindow ) currentWindow.close();
infoWindow.setContent(mapData.name);
infoWindow.open(map,marker);
currentWindow = infoWindow;
});
return marker;
}
function autoZoom( maxLat, minLat, maxLng, minLng ){
if( !maxLat || !minLat || !maxLng || !minLng ) return false;
var sw = new google.maps.LatLng(maxLat,minLng);
var ne = new google.maps.LatLng(minLat,maxLng);
var bounds = new google.maps.LatLngBounds(sw, ne);
map.fitBounds(bounds);
}
</script>
コメントを入れてある部分が以前の記事のソースとは異なる部分になる。
リファレンス
https://developers.google.com/maps/documentation/javascript/marker-clustering?hl=ja
関連記事
-
-
androidでgeolocationを使うとtimeoutになる
Geolocation APIを用いて現在地をGoogleMapに表示させるとい ...
-
-
Advanced Custom FieldsでGoogleMapの使用する方法
Advanced Custom FieldsでGoogleMapを使用したかった ...
-
-
GoogleMapAPIでジオコーディングできない場合の対応方法
住所から経度緯度を取得するジオコーディングをGoogleMapAPIを用いて行お ...
-
-
GoogleMapAPIでマップ自体を移動し中心地の経度緯度を取得
GoogleMapでマップ自体をドラッグして移動した後、中心地の経度緯度を取得し ...
-
-
Google Maps APIでリアルタイムに現在地のマーカーを更新する方法
GoogleMapAPIを使って現在地を取得してその場所にマーカーを設置、その後 ...