Cod*_*eef 5 javascript google-maps google-maps-api-3 fitbounds
我在调用fitBounds()之后直接调用了getBounds(),我认为当地图重新定位并缩放以适应边界时,我会得到一个有效的边界.不幸的是,getBounds()返回nil.
重现的代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<style>
#map {
width: 800px;
height: 400px;
}
</style>
</head>
<body>
<div id='map'></div>
<script>
var myLatlng1 = new google.maps.LatLng(-38.397, 150.644);
var myLatlng2 = new google.maps.LatLng(-34.897, 150.844);
var myLatLngBounds = new google.maps.LatLngBounds(myLatlng1, myLatlng2);
var myOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(0, 0),
zoom: 0
}
var map = new google.maps.Map(document.getElementById("map"), myOptions);
map.fitBounds(myLatLngBounds);
console.log(map.getMapTypeId());
console.log(map.getZoom());
console.log(map.getBounds());
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
有什么我想念的吗?我无法在文档中找到有关这种情况的任何内容.我得到的最近是关于getBounds的说明:
如果尚未初始化地图(即mapType仍为null),或者尚未设置居中和缩放,则结果为null.
请注意,getZoom也会返回undefined.fitBounds()没有设置这个值吗?
编辑 我已根据Marcelo的建议更新了默认缩放和中心的代码.
正如@CrazyEnigma建议的那样,您可以在bounds_changed触发事件后获取边界:
map.fitBounds(myLatLngBounds);
google.maps.event.addListener(map, 'bounds_changed', function() {
console.log(map.getMapTypeId());
console.log(map.getZoom());
console.log(map.getBounds());
});
Run Code Online (Sandbox Code Playgroud)
以上将打印以下内容到您的控制台:
roadmap
6
Object
Run Code Online (Sandbox Code Playgroud)
请注意,如果您只想getBounds做一次,那么应该替换addListener为addListenerOnce(Thanks,@ Tomas).
| 归档时间: |
|
| 查看次数: |
9133 次 |
| 最近记录: |