我需要绘制地图上的一组坐标以响应用户的选择,当它发生时,我想平移地图以关注该点集。我怎样才能找到包含所有坐标的最小边界框(LatLngBounds)?如何在Google Maps JS API中获取仍包含一组纬度/经度坐标的最小LatLngBounds?
回答
除了Stack Overflow post which @Crescent Fresh pointed to above(使用v2 API)之外,您要使用的方法是LatLngBounds.extend()
。
这里有一个完整的例子,使用v3 API:
<!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>
截图:
.extend()的问题在于它是方向性的。它允许边界框增长,但不缩小。因此,如果您已经创建了一个包含所有标记的边界框,然后删除标记,则要缩小标记的唯一方法就是重新遍历所有标记。这对我来说很坦率地看起来没有效率。任何人都知道一种更好的方式,不需要用新的LatLngBounds再次查看所有标记? – 2011-01-06 19:57:37
@Andrew:测试删除的标记是否位于边框边界上是非常容易的......因此,只有在位于边界的标记被删除时,才可以简单地重新生成边界框......您拥有的标记越多,边框上的标记被删除的可能性就越小。如果你只有几个标记,操作将仍然非常快。 – 2011-01-06 21:03:32
@AndrewDeAndrade如果标记被移除,重新计算边界并不是无效的。他们提供的任何内置函数都可能完全是这样。另一种方法是将扩展边界的每个步骤存储在一个数组中,如果删除一个数组,则引用前一个数组元素。 – Frug 2014-08-06 17:59:44
- 1. 如何从google maps v3 api获取经度和纬度?
- 2. GoogleMaps API - 坐标(经度,纬度)地址
- 3. 经纬度坐标
- 4. 纬度和经度错误 - Google Maps API JS 3.0
- 5. 如何获取方法viewDidLoad中的纬度和经度坐标?
- 6. 如何在google map api v2中获取经度和纬度?
- 7. 如何从Nokia Maps API获取十进制经度/纬度?
- 8. Google Maps API - 具有重复经度和纬度的标记
- 9. CoreLocation ::获取经纬度坐标
- 10. 有没有办法使用google maps api返回经纬度坐标数组?
- 11. Google Maps API按经度/纬度移除标记
- 12. 如何获取与Google地图相同的Google Geocoder API几何值(经度和纬度)URL经纬度值
- 13. 如何通过Google Maps API检索经度和纬度?
- 14. 纬度和经度坐标之间的最小距离
- 15. 争夺纬度经度坐标的JavaScript
- 16. 获取纬度和经度html js
- 17. 如何在Python中从2个numpy数组中提取纬度/经度坐标?
- 18. 如何从MKMapItem中提取纬度/经度坐标
- 19. 3D坐标经度和纬度
- 20. 获取纬度/经度坐标当我有国家名称/ ISO与Android
- 21. 经度,纬度到XY坐标转换
- 22. 如何在Android应用上获取精确的经度和纬度坐标?
- 23. 从不使用Google API的地址获取经度和纬度
- 24. 纬度和经度UTM坐标
- 25. 随机纬度经度坐标
- 26. 从Google标记中获取纬度/经度
- 27. 获取基于给定名称的经度和纬度的API
- 28. Google Maps API - 获取地址的坐标
- 29. 获取经度和纬度
- 30. 如何显示地图并获取中心坐标 - 经度和纬度?
见http://stackoverflow.com/questions/2362337/how-to-set-the -google-map-zoom-level-depends-to-show-all-the-markers – 2010-07-30 16:02:06