2011-06-13 18 views
10

¿Cómo puedo restablecer los límites de un mapa de Google cuando el usuario selecciona una opción? Los límites ya han sido configurados para incluir una 'gran imagen' del área, quiero acercarme a un área específica cuando el usuario selecciona una opción ... y necesito hacerlo restableciendo los límites. La ampliación para incluir los lat/longs no funcionará, ya que están incluidos.Restablecer límites en la API de Google Maps v3

Respuesta

11

Tienes que crear un new bounds object, agregar los puntos del mapa a él, y luego agregar los límites del objeto al mapa.

solución condensada:

//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); 

Mi solución completa para la eliminación de los marcadores existentes, consiguiendo una serie actualizada de los puntos a través de AJAX, agregarlos al mapa, y luego restablecer las límites de mapas.

<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); 
    } 
} 

Cuestiones relacionadas