我想根据动态加载的标记将我的 Google 地图居中。我已经看到了“边界”的使用并尝试实现“适合边界”,但我无法将其正确应用到我的地图上。这是代码:
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);
});
}
这很简单,在初始化方法中创建一个边界对象,然后用每个标记的位置扩展该边界对象。最后,在地图对象上调用 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);
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)