2010-07-30 20 views

回答

12

除了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> 

截图:

Google Maps LatLngBounds.extend() Demo

+0

.extend()的问题在于它是方向性的。它允许边界框增长,但不缩小。因此,如果您已经创建了一个包含所有标记的边界框,然后删除标记,则要缩小标记的唯一方法就是重新遍历所有标记。这对我来说很坦率地看起来没有效率。任何人都知道一种更好的方式,不需要用新的LatLngBounds再次查看所有标记? – 2011-01-06 19:57:37

+1

@Andrew:测试删除的标记是否位于边框边界上是非常容易的......因此,只有在位于边界的标记被删除时,才可以简单地重新生成边界框......您拥有的标记越多,边框上的标记被删除的可能性就越小。如果你只有几个标记,操作将仍然非常快。 – 2011-01-06 21:03:32

+0

@AndrewDeAndrade如果标记被移除,重新计算边界并不是无效的。他们提供的任何内置函数都可能完全是这样。另一种方法是将扩展边界的每个步骤存储在一个数组中,如果删除一个数组,则引用前一个数组元素。 – Frug 2014-08-06 17:59:44

相关问题