Google Mapで複数座標を動的に表示する際、
座標群の中心を地図の中心に設定し、
座標群すべてが表示される縮尺にしたいという場合どうしたらいいか。
最初、プログラム側で座標群の中心を取得し、
中心から最も離れた座標と中心との距離を図り、
その距離を元に縮尺を決めるということを考えていたがなかなかうまく行かず、
あれ、もともとGoogle Mapにその機能あったかもしれないとひらめき、
探したら見事にあった。
この関数を使えば簡単に解決できた。
function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 6,
center: { lat: 35.681099, lng: 139.767084 },
});
var bounds = new google.maps.LatLngBounds();
// Add some markers to the map.
const markers = locations.map((location, i) => {
bounds.extend(new google.maps.LatLng(location.lat, location.lng));
const position = {lat: location.lat, lng: location.lng};
const icon = {url: '/images/red-dot.png'};
const marker = new google.maps.Marker({
position,
icon,
});
return marker;
});
map.fitBounds(bounds);
}
const locations = [
@foreach($locations as $location)
@if($location['lat'] != '' && $location['lng'] != '')
{ lat: {{$location['lat']}},
lng: {{$location['lng']}},
},
@endif
@endforeach
];
window.onload = function () {
initMap();
}