javascript - Google Maps JS API - 如何使用 fitBounds 进行响应式 map ?

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

我正在尝试在响应式网站的 map 中显示特定区域。 我希望它在加载时通​​过放大和缩小来显示相同​​的区域,无论窗口大小如何。 经过一番研究,我明白我需要使用 Google Maps JS API 的 fitBounds 函数,但无法让它工作。到目前为止,这是我的代码:

<div id="map"></div><!--css rules to make it a 16/9 responsive box-->
<script src="https://maps.googleapis.com/maps/api/js?key=mykey" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
    var mapOptions = {
        center: new google.maps.LatLng(x, y), //any coordinates I put here don't matter, as I need the map to adjust using bounds, right?
        zoom: 11
    };
    var bounds = google.maps.LatLngBounds(
        new google.maps.LatLng(x, y), //SW coordinates here
        new google.maps.LatLng(x, y) //NE coordinates here
    );
    var map = new google.maps.Map(document.getElementById("map"), mapOptions);
    map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, "resize", function() {
    var bounds = map.getBounds();
    google.maps.event.trigger(map, "resize");
    map.fitBounds(bounds);
});
</script>

map 似乎只是显示选项中的中心位置,并忽略了 fitBounds 调用。我错过了什么/做错了什么?

最佳答案

在 map 有机会调整大小之前,您当前正在检索 map 的边界

您需要为 map 调整大小事件添加一个额外的处理程序,然后将 fitBounds 代码移入其中。仍然将 map 调整大小的触发器保留在窗口调整大小处理程序中。

编辑

您需要将 map 变量移到初始化函数之外,以便 map 监听器可以全局访问它

关于javascript - Google Maps JS API - 如何使用 fitBounds 进行响应式 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28649025/

相关文章:

javascript - 来自 Promise.each 的未处理拒绝

ios - 两个函数在 Swift 中调用

javascript - 带有 JSP 的 Google map 上的多个标记

javascript - 替代 HTML/Javascript 侧边栏小工具?

javascript - 我们还需要付出所有努力来为 NPM 预编译软件包吗?

javascript - Google map javascript api bug android 浏览器(Jelly bean 及之前版本)

google-maps-api-3 - Google map API 营业地点

javascript - 在 Javascript 中使用 Django 变量与 Google API 一起使用

c# - 如何在asp.net中使用jquery实现文件上传进度条?

javascript - 使用 angular-google-maps 无法将点击事件绑定(bind)到用于显示单个窗口的标记