2 javascript google-maps google-maps-api-3 responsive-design
我正在尝试让Google地图在响应时调整其中心位置.
我已经设法将地图放到中心,但无法弄清楚如何将我的标记添加回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);
});
Run Code Online (Sandbox Code Playgroud)
我用来使地图居中的代码在上面.我也有下面的标记代码,但我不知道如何添加它以使其保持其中心.
var marker = new google.maps.Marker({
position: new google.maps.LatLng(LAT,LNG),
map: map,
title: 'Title',
animation: google.maps.Animation.DROP,
})
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮忙吗?
这是获得您想要做的第一步:
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);
});
Run Code Online (Sandbox Code Playgroud)
编辑:基于@Chad Killingsworth评论:您可能希望向地图添加"空闲"事件处理程序以设置mapCenter变量.你可以这样做:
google.maps.event.addListener(map,'idle',function(event) {
mapCenter = map.getCenter();
});
Run Code Online (Sandbox Code Playgroud)
来自doc的'idle'事件的描述:
平移或缩放后地图变为空闲时会触发此事件.