Javascript 如何在Google Maps JS API中获得仍然包含一组Lat/Long坐标的最小LatLngBounds?
我需要在地图上绘制一组坐标以响应用户的选择,当它发生时,我希望平移地图以聚焦于这组点。如何找到包含所有坐标的最小边界框(LatLngBounds)?除了(使用v2 API)之外,您希望使用的方法是 下面是一个完整的示例,使用:Javascript 如何在Google Maps JS API中获得仍然包含一组Lat/Long坐标的最小LatLngBounds?,javascript,google-maps,google-maps-api-3,Javascript,Google Maps,Google Maps Api 3,我需要在地图上绘制一组坐标以响应用户的选择,当它发生时,我希望平移地图以聚焦于这组点。如何找到包含所有坐标的最小边界框(LatLngBounds)?除了(使用v2 API)之外,您希望使用的方法是 下面是一个完整的示例,使用: Google Maps LatLngBounds.extend()演示 var map=new google.maps.map(document.getElementById('map'),{ mapTypeId:google.maps.mapTypeId.TERRAI
Google Maps LatLngBounds.extend()演示
var map=new google.maps.map(document.getElementById('map'),{
mapTypeId:google.maps.mapTypeId.TERRAIN
});
var markerBounds=new google.maps.LatLngBounds();
var随机点,i;
对于(i=0;i<10;i++){
//在东北美洲生成10个随机点
randomPoint=新的google.maps.LatLng(39.00+(Math.random()-0.5)*20,
-77.00+(数学随机数()-0.5)*20);
//为每个随机点绘制一个标记
新的google.maps.Marker({
位置:随机点,
地图:地图
});
//使用每个随机点扩展markerBounds。
扩展标记边界(随机点);
}
//最后,markerBounds将是要包含的最小边界框
//我们的10个随机点
//最后,我们可以调用Map.fitBounds()方法将映射设置为适合
//我们的markerBounds
地图边界(markerBounds);
截图:
请参见.extend()的问题在于它是定向的。它允许边界框增长,但不允许收缩。因此,如果已经创建了一个包含所有标记的边界框,然后删除了一个标记,则使其收缩的唯一方法是再次重复所有标记。坦率地说,这对我来说似乎效率低下。有谁知道一种更好的方法,不需要用新的LatLngBounds再次查看所有标记吗?@Andrew:很容易测试删除的标记是否位于边界框上。。。因此,只有在删除位于边界上的标记时,才能简单地重新生成边界框。。。标记越多,删除边框上的标记的可能性就越小。如果您只有几个标记,操作仍然会非常快。@AndrewDeAndrade如果删除标记,重新计算边界并不是低效的。他们提供的任何内置函数可能都会做到这一点。另一种方法是将扩展边界的每个步骤存储在数组中,如果删除了一个数组元素,请参考前面的数组元素。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps LatLngBounds.extend() Demo</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 400px; height: 300px;"></div>
<script type="text/javascript">
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.TERRAIN
});
var markerBounds = new google.maps.LatLngBounds();
var randomPoint, i;
for (i = 0; i < 10; i++) {
// Generate 10 random points within North East America
randomPoint = new google.maps.LatLng( 39.00 + (Math.random() - 0.5) * 20,
-77.00 + (Math.random() - 0.5) * 20);
// Draw a marker for each random point
new google.maps.Marker({
position: randomPoint,
map: map
});
// Extend markerBounds with each random point.
markerBounds.extend(randomPoint);
}
// At the end markerBounds will be the smallest bounding box to contain
// our 10 random points
// Finally we can call the Map.fitBounds() method to set the map to fit
// our markerBounds
map.fitBounds(markerBounds);
</script>
</body>
</html>