Google 地图正在改变地图的中心

Google Maps is changing the center of map

我在一个页面上有几个 Google 地图。一次只显示一个,您可以通过单击按钮从一张地图更改为另一张地图。由于某些地图在 Google 地图首次初始化地图时被隐藏,因此我需要 "refresh" 正在显示的地图,为此我需要获得地图的中心。我使用 map.getCenter() 但不知何故中心在到达那里之前发生了变化。

我已经调试了下面的代码,我知道它在哪里发生了变化,但为什么仍然是个谜。

function initMaps() {
    if ($('.gmap').length) {
        var $maps = $('.gmap'),
        myOptions = {
            zoom: 16,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            scrollwheel: false,
            mapTypeControlOptions: {
                mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'mapStyle']
            }
        },
        maps = {};

        $maps.each(function () {
            var latitude = parseFloat($(this).attr('data-latitude')),
                longitude = parseFloat($(this).attr('data-longitude')),
                mapNumber = $(this).attr('data-number'),
                baseLatLng = new google.maps.LatLng(latitude, longitude);
            myOptions.center = baseLatLng;
            maps[mapNumber] = new google.maps.Map(this, myOptions);
            var mapCustomType = new google.maps.StyledMapType(mapStyle, myOptions);
            maps[mapNumber].mapTypes.set('custom', mapCustomType);
            maps[mapNumber].setMapTypeId('custom');
        });

        $('.map').hide();
        $('.map:first').show();
        console.log(maps);  // Centers are the same
        changeMaps(maps);
    }
}

function changeMaps(maps) {
    console.log(maps); // Centers are the same
    $('.maps-list span').click(function () {
        console.log(maps); // Centers have changed !!!
        var $mapClass = $('.map-' + $(this).attr('class')),
            map = maps[parseInt($mapClass.find('.gmap').attr('data-number'))];
        $('.map').hide();
        $mapClass.show();
        refreshMap(map);
    });
}

function refreshMap(map) {
    google.maps.event.trigger(map, 'resize');
    map.setCenter(map.getCenter());
}

changeMaps() 函数中,我的第二张地图(最初隐藏的地图)的中心在按钮的单击事件期间发生变化,该按钮除了触发此函数外什么都不做)。我确实删除了几个变量并更改了一些 class 名称,以便代码更易于阅读,因此您可以忽略代码的任何其他问题。

我想知道为什么中心会发生变化,但如果您有一种更简洁的方式来完成所有这些,那也很好。

此代码不会有任何效果:

map.setCenter(map.getCenter());

getCenter() returns地图的当前center(调整地图大小时会发生变化),而不是初始设置的值。

您必须将初始值存储在另一个 属性 中,然后将中心设置为存储的值。

initMaps() 中:

myOptions.center = myOptions._center = baseLatLng;

refreshMap() 中:

map.setCenter(map._center);