Map.fitBounds()
Map.fitBounds()はMapクラスのメソッドです。指定した境界がちょうどよく見えるように、地図のビューポート(位置座標とズーム値)を変更してくれます。
構文
パラメータ
bounds
LatLngBounds | LatLngBoundsLiteral
境界をLatLngBounds、またはLatLngBoundsLiteralで指定する。
padding
number
上下左右の余白の幅をピクセル単位の数値で指定する。この余白がとられるように、キャンパスのビューポートが調整される。
返り値
返り値はありません。
デモ
メソッドを実行すると、あらかじめ用意しておいた境界が全て収まるように、位置座標とズーム値が調整されます。境界には分かりやすいように、色を付けてあります。
var map = new google.maps.Map( mapDiv, {
center: new google.maps.LatLng( 35, 139 ) ,
zoom: 15 ,
} ) ;
// メソッドを実行
var latLngBounds = new google.maps.LatLngBounds(
new google.maps.LatLng( 35.2199, 136.9851 ) ,
new google.maps.LatLng( 37.7892, 140.4898 )
) ;
map.fitBounds( latLngBounds, 10 ) ;
サンプルコード
<!DOCTYPE html>
<html>
<head>
<style>
#map-canvas {
width: 600px ;
height: 600px ;
}
</style>
</head>
<body>
<div id="map-canvas"></div>
<p><button id="method">メソッドを実行</button><button id="reset">リセット</button></p>
<p><textarea id="response"></textarea></p>
<script src="//maps.googleapis.com/maps/api/js?key={APIキー}"></script>
<script>
function initialize() {
var mapDiv = document.getElementById( "map-canvas" ) ;
var responseTextarea = document.getElementById( "response" ) ;
responseTextarea.value = "" ;
// Map
var map = new google.maps.Map( mapDiv, {
center: new google.maps.LatLng( 43.0686601740126, 141.35075529999995 ) ,
zoom: 15 ,
} ) ;
// LatLngBounds
var latLngBounds = new google.maps.LatLngBounds(
new google.maps.LatLng( 33.35929104,134.93065664 ) ,
new google.maps.LatLng( 36.95102297,141.68730977 )
) ;
// LatLngBoundsを可視化
new google.maps.Rectangle( { map: map, bounds: latLngBounds, fillColor: "red", } ) ;
// Method
document.getElementById( "method" ).onclick = function () {
var response = map.fitBounds( latLngBounds ) ;
try{ response = typeof response == "object" ? JSON.stringify( response ) : response ; }catch(e){}
responseTextarea.value = response ;
console.log( response ) ;
}
}
// Reset
document.getElementById( "reset" ).onclick = initialize ;
initialize() ;
</script>
</body>
</html>