我正在尝试让Google地图在响应时调整其中心位置。
我已经设法将地图放到中心,但无法弄清楚如何将我的标记添加回JS以使其成为中心。我正在使用此处的代码进行地图居中... 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);
});
我用来将地图居中的代码在上面。我也有下面的标记代码,但我不确定如何添加它以使其保持其中心。
var marker = new google.maps.Marker({
position: new google.maps.LatLng(LAT,LNG),
map: map,
title: 'Title',
animation: google.maps.Animation.DROP,
})
}
有人可以帮忙吗?
答案 0 :(得分:8)
这是获得您想要做的第一步:
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();
});
doc:'/ p>中'idle'事件的描述
在平移或缩放后地图变为空闲时会触发此事件。