主要使用了new google.maps.LatLngBounds()
<style>
html, body, #map-canvas {
height: 87%;
margin: 0px;
padding: 0px
}
</style>
<script src="http://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var map;
var markers = [];
var defaultZoom = 9
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(39.90403, 116.407526),
zoom: defaultZoom
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
//设置地图缩放
var i=markers.length;
var bounds = new google.maps.LatLngBounds();
while(i--){
bounds.extend(new google.maps.LatLng(markers[i].getPosition().lat()
,markers[i].getPosition().lng()));
}
map.fitBounds(bounds);
//地图缩放时触发,当地图的缩放比例大于默认比例时,恢复为默认比例
google.maps.event.addListener(map, 'zoom_changed', function () {
if (map.getZoom() > defaultZoom){
map.setZoom(defaultZoom);
}
});
}
// Show the new coordinates for the rectangle in an info window.
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
markers.push(marker);
}
// Sets the map on all markers in the array.
function setAllMap(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
setAllMap(null);
}
// Shows any markers currently in the array.
function showMarkers() {
setAllMap(map);
}
// Deletes all markers in the array by removing references to them.
function deleteMarkers() {
clearMarkers();
markers = [];
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>