Javascript 如何以编程方式更改 Google 地图的缩放级别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12458456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change the zoom level of Google maps programmatically?
提问by Aquarius_Girl
function displayMapAndClick ()
{
var latlng = new google.maps.LatLng (29.0167, 77.3833);
var myOptions =
{
zoom:zm,
center:latlng,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map (document.getElementById ("map"), myOptions);
directionsDisplay.setMap (map);
}
Where zm
is a global variable set to default 7
.
zm
全局变量在哪里设置为 default 7
。
Now, I wish to change the zoom level of this map thorough this program.
现在,我希望通过此程序更改此地图的缩放级别。
What is the way to do that without re-initializing the map?
在不重新初始化地图的情况下,有什么方法可以做到这一点?
OR is reinitializing compulsory?
或者是强制重新初始化?
回答by Alexander
Use the setZoom()
method from the google.maps.Map
class.
使用类中的setZoom()
方法google.maps.Map
。
var mapOptions = {
/* Initial zoom level */
zoom: 8
...
};
map = new google.maps.Map(..., mapOptions);
/* Change zoom level to 12 */
map.setZoom(12);
回答by publicJorn
In addition to Alexanders' sollution: I had the same problem, but the above didn't work for me in all browsers because sometimes the map.setZoom() is executed before the map is done loading.
除了 Alexanders 的解决方案:我遇到了同样的问题,但上述内容在所有浏览器中都不适用于我,因为有时在地图加载完成之前执行 map.setZoom()。
Wrapping the function like this will make it work always:
像这样包装函数将使其始终工作:
...
map = new google.maps.Map(..., mapOptions);
/* Change zoom level to 12 */
google.maps.event.addListenerOnce(map, 'bounds_changed', function() {
map.setZoom(12);
});