javascript - 谷歌地图 fitBounds 无法正常工作

标签 javascript google-maps google-maps-api-3 fitbounds

我对 googlemaps fitBounds 函数有疑问。

for (var i = 0; i < countries.length; i++) {
 var country = countries[i];
 var latlng = new google.maps.LatLng(parseFloat(country.lat), parseFloat(country.lng));
 mapBounds.extend(latlng); 
}

map.fitBounds(mapBounds);

一些图标将显示在视口(viewport)/可见区域之外。

还有想法?

提前致谢。

最佳答案

考虑以下示例,它将在美国东北部生成 10 个随机点,并应用 fitBounds() 方法。

<!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 USA
     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>

多次刷新此示例,没有任何标记超出视口(viewport)。最多,有时标记隐藏在控件后面时会从顶部略微剪掉:

Google Maps LatLngBounds.extend() Demo

fitBounds() 总是在 LatLngBounds 对象和视口(viewport)之间留出一小段空白也是毫无意义的。下面的屏幕截图清楚地显示了这一点,其中红色边界框表示传递给 fitBounds() 方法的 LatLngBounds:

fitBounds Padding

fitBounds Padding

您可能还有兴趣查看以下有关该主题的 Stack Overflow 帖子:

关于javascript - 谷歌地图 fitBounds 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3407723/

相关文章:

objective-c - 在 Google Map API 中默认显示标记的标题

javascript - 谷歌地图信息窗口关闭不起作用

google-maps - Google map API [方向 API] 航点限制?

javascript - 正则表达式不适用于 javascript

javascript - 在 javascript 库中的导出类之外声明函数是实现私有(private)函数的好习惯吗?

javascript 精确匹配字符串

javascript - 尝试移动两个 div 的 onkeydown 时出现问题

java - 使用 gmaps v2 for android 开始虚拟之旅

javascript - 为数百万个点生成热图层

android - 地理编码器,在 Android 中获取国家/地区,getFromLocation 零结果