【问题标题】:Google map in responsive map doesn't center map响应式地图中的谷歌地图不居中地图
【发布时间】:2014-11-21 14:17:46
【问题描述】:

我对谷歌地图有疑问。我将它嵌入到响应式网络中。一切都很好,地图的行为很敏感,但是当我更改窗口大小时,例如在手机上打开页面时,它只是从地图中切出,当它调整大小时,但我需要它来使地图居中。我需要这些位置仍然可见,但我不知道该怎么做。有人可以帮我吗?希望我的问题可以理解。谢谢。

API 调用:

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>

JS代码:

function initialize() {
    var myLatlng = new google.maps.LatLng(48.652645, 21.083107);
    var mapOptions = {
        zoom: 11,
        center: myLatlng
    }
    var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    setMarkers(map, beaches);
}

var beaches = [
    ['xxxx'],
    ['xxxx']
];

function setMarkers(map, locations) {
    for (var i = 0; i < locations.length; i++) {
        var beach = locations[i];
        var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
        var marker = new google.maps.Marker({
            position: myLatLng,
            map: map
        });
    }
}

google.maps.event.addDomListener(window, 'load', initialize);

【问题讨论】:

  • 我能理解你的问题,但你的代码在哪里?
  • 对不起。我已经编辑了我的问题。

标签: google-maps google-maps-api-3


【解决方案1】:
  1. 创建一个bounds 全局变量。
  2. 添加标记时扩展边界对象。
  3. 在调整窗口大小时,触发地图调整大小并使地图适合边界对象。

全局变量:

var bounds = new google.maps.LatLngBounds();

setMarkers 函数中扩展边界:

for (var i = 0; i < locations.length; i++) {
    var beach = locations[i];
    var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
    var marker = new google.maps.Marker({
        position: myLatLng,
        map: map
    });

    bounds.extend(myLatLng);
}

将此添加到您的 initialize 函数中:

window.addEventListener("resize", resizeUI);

创建调整大小函数:

function resizeUI() {

    google.maps.event.trigger(map, 'resize');
    map.fitBounds(bounds);
}

未经测试,但你明白了......

【讨论】:

  • 非常感谢。它仍然不起作用,因为控制台说地图没有在 resizeUI 函数中定义。
  • 在你的函数之外定义var map;
猜你喜欢
  • 2013-03-19
  • 2013-03-03
  • 2018-02-05
  • 2012-12-05
  • 2015-11-17
  • 2018-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多