我有一张包含多个位置的地图。位置根据显示的页面在运行时确定(它们是我们经销商的位置,因此它们根据经销商ID而变化。(标记显示正常,但现在我想将地图居中,以便将其缩放为包括所有标记的中心和基于显示的标记居中。我该怎么做?现在,手动设置缩放和中心。这是我的代码到目前为止:
<script type="text/javascript">
function initialize() {
var locations = [
<?php
$loc = '';
$i = 1;
foreach ($coordinates as $c) {
$loc .= '["' . $c->company . '", ' . $c->latitude . ', ' . $c->longitude . '], ';
$i++;
}
echo substr($loc, 0, -2);
?>
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
答案 0 :(得分:6)
创建包含所有标记位置的google.maps.LatLngBounds对象,然后使用google.maps.Map对象的fitBounds
方法:
var bounds = new google.maps.LatLngBounds();
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
//Extends bounds to contain marker position
bounds.extend( marker.getPosition() );
.....
}
map.fitBounds( bounds );