[英]Center a Google Map based on Markers
I would like to center my Google Map based on dynamically loaded markers. 我想基于动态加载的标记将Google Map居中。 I have seen the use of 'bounds' and tried to implement Fit to bounds, but I haven't been able to apply it correctly to my map. 我已经看到了'bounds'的用法,并尝试实现“适合边界”,但是我无法将其正确地应用于地图。 Here is the code: 这是代码:
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);
});
}
This is easy, in your initialize method create a bounds object, and then extend the bounds object with each marker's position. 这很容易,在您的initialize方法中创建一个bounds对象,然后使用每个标记的位置扩展bounds对象。 Finally, call map.fitBounds() on your map object to center and fit your map to your markers: 最后,在地图对象上调用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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.