谷歌地图正在改变地图的中心

Google Maps is changing the center of map

本文关键字:地图 改变 谷歌地图      更新时间:2023-09-26

我在一个页面上有几个谷歌地图。一次只显示一个地图,您可以通过单击按钮从一个地图切换到另一个地图。由于当谷歌地图首次初始化地图时,某些地图是隐藏的,我需要"刷新"正在显示的地图,为此我需要获取地图的中心。我使用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()函数中,我的第二个地图(一开始隐藏的那个)的中心在按钮的单击事件期间发生变化,该按钮除了触发此功能外什么都不做)。我确实删除了几个变量并更改了一些类名,以便代码更易于阅读,因此您可以忽略代码的任何其他问题。

我想知道为什么中心会改变,但如果你有更干净的方式来做这一切,那也很棒。

此代码不会有任何影响:

map.setCenter(map.getCenter());

getCenter()返回地图的当前center(当您调整地图大小时会更改),而不是最初设置的值。

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

initMaps()

myOptions.center = myOptions._center = baseLatLng;

refreshMap()

map.setCenter(map._center);