14
13

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 5 years have passed since last update.

【Google Maps JavaScript API v3】すべてのマーカーを地図の中に収める【LatLngBounds】

Last updated at Posted at 2016-05-17

デモ:http://mo49.tokyo/qiita/20160517/bounds.html

var locations = [
   ['東京タワー', 35.658581, 139.745433],
   ['スカイツリー', 35.789966, 139.821961],
   ['東京ドーム', 35.705471, 139.751801],
   ['ランドマークタワー', 35.454948, 139.631429]
];

var map = new google.maps.Map(document.getElementById('map'));
var bounds = new google.maps.LatLngBounds();
var infoWindow = new google.maps.InfoWindow();
var marker;

for (var i = 0; i < locations.length; i++) {
  marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
    map: map
  });
  // 地図表示領域をマーカー位置に合わせて拡大
  bounds.extend (marker.position);

  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      infoWindow.setContent('観光スポット名:' + '<br>' + locations[i][0]);
      infoWindow.open(map, marker);
    }
  })(marker, i));
}

// 引数に指定した矩形領域を地図に収める
map.fitBounds (bounds);

参考
LatLngBoundsクラスの解説
fitBounds() - Mapクラスのメソッド
GoogleMap v3 マーカー位置にあわせて表示領域を自動調整する

14
13
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
14
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?