我想基于动态加载的标记来集中我的Google地图。我已经看到使用'bounds'并试图实现Fit to bounds,但是我无法将它正确地应用到我的地图上。这是代码:
var MapStart = new google.maps.LatLng(41.664723,-91.534548);
var markers;
var map;
var infowindow = new google.maps.InfoWindow({maxWidth: 650});
function initialize() {
markers = new Array();
var mapOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: MapStart
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
$("#map_list ul li").each(function(index) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng($(this).children(".marker_long").text(), $(this).children(".marker_lat").text()),
map: map,
animation: google.maps.Animation.DROP,
title : $(this).children(".marker_title").text(),
brief: $("div.infoWindow", this).html()
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(marker.brief);
infowindow.open(map, marker);
});
markers.push(marker);
});
}
答案 0 :(得分:2)
这很简单,在初始化方法中创建一个bounds对象,然后使用每个标记的位置扩展bounds对象。最后,在地图对象上调用map.fitBounds()以使地图居中并使地图适合您的标记:
function initialize() {
...
var bounds = new google.maps.LatLngBounds();
...
$("#map_list ul li").each(function(index) {
...
//extend the bounds to include each marker's position
bounds.extend(marker.position);
...
});
...
//now fit the map to the newly inclusive bounds
map.fitBounds(bounds);
...
}
//(optional) restore the zoom level after the map is done scaling
var listener = google.maps.event.addListener(map, "idle", function () {
map.setZoom(15);
google.maps.event.removeListener(listener);
});