且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用标记在响应式调整大小时将 Google 地图居中

更新时间:2023-02-05 23:16:33

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

Here is a first step to get what you want to do:

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 变量.你可以这样实现:

Based on @Chad Killingsworth comment: You may want to add an 'idle' event handler to the map to set the mapCenter variable. You can achieve this like this:

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

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

Description of the 'idle' event from the doc:

当地图在平移或缩放后空闲时会触发此事件.

This event is fired when the map becomes idle after panning or zooming.