以谷歌地图为中心,使用标记调整响应大小

Centering Google Maps on responsive resize with marker

本文关键字:调整 响应 谷歌地图 为中心      更新时间:2024-06-13

我正试图让谷歌地图在响应调整大小时保持其中心。

我已经设法使地图居中,但无法解决如何将我的标记添加回JS以使其也居中。我正在使用这里的代码进行地图居中。。。谷歌地图响应调整

var map; //<-- This is now available to both event listeners and the initialize() function
function initialize() {
    var mapOptions = {
        center: new google.maps.LatLng(LAT,LNG),
        zoom: 10,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: false,
        scrollwheel: false,
        keyboardShortcuts: false,
    };
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, "resize", function() {
    var center = map.getCenter();
    google.maps.event.trigger(map, "resize");
    map.setCenter(center); 
});

我用来将地图居中的代码在上面。我也有下面的标记代码,但我不知道如何添加它以使它也保持中心。

var marker = new google.maps.Marker({
        position: new google.maps.LatLng(LAT,LNG),
        map: map,
        title: 'Title',
        animation: google.maps.Animation.DROP,
        })
    }

有人能帮忙吗?

这里是获得想要做的事情的第一步:

var map; //<-- This is now available to both event listeners and the initialize() function
var mapCenter; // Declare a variable to store the center of the map
var centerMarker; // declare your marker
function initialize() {
    var mapOptions = {
        center: new google.maps.LatLng(LAT,LNG),
        zoom: 10,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: false,
        scrollwheel: false,
        keyboardShortcuts: false,
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    // Create a new marker and add it to the map
    centerMarker = new google.maps.Marker({
        position: new google.maps.LatLng(LAT,LNG),
        map: map,
        title: 'Title',
        animation: google.maps.Animation.DROP
    });
    mapCenter = map.getCenter(); // Assign the center of the loaded map to the valiable
}

google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, "resize", function() {
    // Here you set the center of the map based on your "mapCenter" variable
    map.setCenter(mapCenter); 
});

编辑:基于@Chad Killingsworth评论:您可能需要在映射中添加一个"空闲"事件处理程序来设置mapCenter变量。你可以这样实现:

google.maps.event.addListener(map,'idle',function(event) {
    mapCenter = map.getCenter();
});

文档中"空闲"事件的描述:

当地图在平移或缩放后变为空闲时,会触发此事件。