Google Maps API Tutorial Google Maps API Tutorial
Back to Home Page

Example of Zooming the Map to Fit Overlays for Google Maps API

View Example


The key is to use map.fitBounds function, where the boundary is a rectangle covering all the overlay points.

Source Code

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Google Map API V3: Zoom Map to Fit Markers</title>
<script type="text/javascript" src=""></script>
<style type="text/css">
body { margin: 20; padding: 20 }
	width: 740px;
	height: 400px;
<script type="text/javascript">
      function initialize() {
        var mapOptions = {
          center: new google.maps.LatLng(37.286172, -121.80929),
          zoom: 8,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        var map = new google.maps.Map(document.getElementById("map_canvas"),

        var myLatlng1 = new google.maps.LatLng(37.286172, -121.80929);
        var marker1 = new google.maps.Marker({
            position: myLatlng1,
            map: map,
            title: 'Marker 1'

        var myLatlng2 = new google.maps.LatLng(37.186172, -121.80929);
        var marker2 = new google.maps.Marker({
            position: myLatlng2,
            map: map,
            title: 'Marker 2'

        var myLatlng3 = new google.maps.LatLng(37.486172, -121.80929);
        var marker3 = new google.maps.Marker({
            position: myLatlng3,
            map: map,
            title: 'Marker 3'

        var myLatlng4 = new google.maps.LatLng(37.286172, -121.63929);
        var marker4 = new google.maps.Marker({
            position: myLatlng4,
            map: map,
            title: 'Marker 4'

        var bounds = new google.maps.LatLngBounds();
<body onload="initialize()">
<div id="map_canvas"></div>