LatLngBounds.extend()
LatLng.extend()はLatLngBoundsクラスのメソッドです。自身の境界に、新しく位置座標を追加します。境界の外の位置座標を追加すれば、境界が必要最低限に拡張します。
構文
パラメータ
point
追加する位置座標をLatLngクラス、またはLatLngLiteralオブジェクトで指定する。
返り値
LatLngBounds
位置座標を追加した後のLatLngBounds。
デモ
メソッドを実行すると、位置座標を境界に追加します。分かりやすいように、境界に色を付け、位置座標の位置にはマーカーを設置してあります。
var latLngBounds = new google.maps.LatLngBounds(
new google.maps.LatLng( 35.2199, 136.9851 ) ,
new google.maps.LatLng( 37.7892, 140.4898 )
) ;
var latLng = new google.maps.LatLng( 39.4160,141.0116 ) ;
// メソッドを実行
latLngBounds.extend( latLng ) ;
サンプルコード
<!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( 35, 139 ) ,
zoom: 8 ,
} ) ;
// LatLngBounds
var latLngBounds = new google.maps.LatLngBounds(
new google.maps.LatLng( 35.2199, 136.9851 ) ,
new google.maps.LatLng( 37.7892, 140.4898 )
) ;
// LatLng
var latLng = new google.maps.LatLng( 39.4160,141.0116 ) ;
// LatLngBounds、LatLngを可視化
var rectangle = new google.maps.Rectangle( { map: map, bounds: latLngBounds, } ) ;
new google.maps.Marker( { map: map, position: latLng, } ) ;
// fit bounds
var latLngBounds2 = new google.maps.LatLngBounds() ;
latLngBounds2.union( latLngBounds ) ;
latLngBounds2.extend( latLng ) ;
map.fitBounds( latLngBounds2 ) ;
// Method
document.getElementById( "method" ).onclick = function () {
var response = latLngBounds.extend( latLng ) ;
try{ response = typeof response == "object" ? JSON.stringify( response ) : response ; }catch(e){}
responseTextarea.value = response ;
console.log( response ) ;
rectangle.setBounds( latLngBounds ) ;
}
}
// Reset
document.getElementById( "reset" ).onclick = initialize ;
initialize() ;
</script>
</body>
</html>