【问题标题】:Google Maps fitBounds is not working properly谷歌地图 fitBounds 无法正常工作
【发布时间】:2011-03-25 09:03:15
【问题描述】:
我对 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);
一些图标将显示在视口/可见区域之外。
还有什么想法?
提前致谢。
【问题讨论】:
标签:
javascript
google-maps
google-maps-api-3
fitbounds
【解决方案1】:
检查您的谷歌地图对象是否在您指定的区域正确显示。
您的 google 地图对象的某些部分可能溢出到它的容器之外,并且标记位于该区域中,而您看不到它们存在。
【解决方案2】:
考虑以下示例,它将在美国东北部生成 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>
多次刷新此示例,没有任何标记超出视口。有时,当隐藏在控件后面时,有时会从顶部略微剪掉一个标记:
fitBounds() 总是在LatLngBounds 对象和视口之间留出很小的间距,这也毫无价值。这在下面的屏幕截图中清楚地显示了,其中红色边界框代表传递给 fitBounds() 方法的 LatLngBounds:
您可能也有兴趣查看以下有关该主题的 Stack Overflow 帖子:
【解决方案3】:
向我们显示患者的链接。您在国家/地区阵列中有多少个国家/地区?整个世界?你的界限是否越过了反子午线?
country.lat 和 country.lng 是每个国家/地区的一个点,这不足以定义国家/地区的边界框。那是某种“国家中心”吗?
如果是这种情况,并且您在最东部国家/地区的质心以东或在最西部国家/地区的质心以西有标记,那么这些标记当然会超出您定义的范围.
map.fitBounds() 方法工作正常。 :-)
马塞洛。