gpt4 book ai didi

javascript - 使用标记使 Google map 以响应式调整大小为中心

转载 作者:行者123 更新时间:2023-12-03 23:44:48 24 4
gpt4 key购买 nike

我正在尝试让 Google map 在响应式调整大小时保持其中心位置。

我已经设法让 map 居中,但不知道如何将我的标记重新添加到 JS 中以使其也居中。我正在使用此处的代码进行 map 居中... Google maps responsive resize

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);
});

上面是我用来使 map 居中的代码。我也有下面的标记代码,但我不确定如何添加它以使其也保持其中心。

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 评论:您可能希望向 map 添加“空闲”事件处理程序以设置 mapCenter 变量。你可以这样实现:

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

文档中“空闲”事件的描述:

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

关于javascript - 使用标记使 Google map 以响应式调整大小为中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20517053/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com