13

How can I reset the bounds of a GoogleMap when user selects an option? Bounds have already been set to include a 'big picture' of the area, I want to zoom to a specfic area when the user selects an option...and need to do so by resetting the bounds. Extending to include the lat/longs won't work, as they are already included.

Kara
  • 6,115
  • 16
  • 50
  • 57
Sam Grant
  • 432
  • 2
  • 7
  • 19

1 Answers1

15

You have to create a new bounds object, add the map points to it, and then add the bounds object to the map.

Condensed solution:

 //Create new bounds object
 var bounds = new google.maps.LatLngBounds();
 //Loop through an array of points, add them to bounds
 for (var i = 0; i < data.length; i++) {
      var geoCode = new google.maps.LatLng(data[i][1], data[i][2]);
      bounds.extend(geoCode); 
  }
  //Add new bounds object to map
  map.fitBounds(bounds);

My complete solution for removing existing markers, getting an updated array of points via ajax, adding them to the map, and then resetting the map boundries.

<script type="text/javascript">

var map;
var markers = [];

$(document).ready(function () {
    initialize();
    setInterval(function () {
        setMarkers();
    }, 3000);
});

google.maps.visualRefresh = true;
function initialize()
{
    var mapOptions = {
        zoom: 2,
        center: new google.maps.LatLng(45, -93),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    setMarkers();
}

function setMarkers()
{
    removeMarkers();

    var bounds = new google.maps.LatLngBounds();

    $.ajax({
        url: "/Your/Url?variable=123",
        dataType: "json",
        success: function (data) {
            //Data returned is made up of string[3]
            if (data != null) {
                //loop through data
                for (var i = 0; i < data.length; i++) {
                    var geoCode = new google.maps.LatLng(data[i][1], data[i][2]);
                    var marker = new google.maps.Marker({
                        position: geoCode,
                        map: map,
                        title: data[i][0],
                        content: '<div style="height:50px;width:200px;">' + data[i][0] + '</div>'
                    });

                    var infowindow = new google.maps.InfoWindow();
                    google.maps.event.addListener(marker, 'click', function () {
                        infowindow.setContent(this.content);
                        infowindow.open(map, this);
                    });

                    markers.push(marker);
                    bounds.extend(geoCode);
                }
            }
            map.fitBounds(bounds);
        }
    });
}

function removeMarkers()
{
    for (var i = 0; i < markers.length; i++) {
        markers[i].setMap(null);
    }
}

Mason240
  • 2,924
  • 3
  • 30
  • 46