2011-06-13 109 views
10

如何在用戶選擇某個選項時重置GoogleMap的界限?邊界已經被設置爲包括該地區的「大圖片」,當用戶選擇一個選項時我想放大到特定區域...並且需要通過重設邊界來實現。由於它們已經包括在內,所以擴展到包含經緯度將不起作用。重置Google Maps API v3上的界限

回答

11

您必須創建new bounds object,將地圖點添加到它,然後將邊界對象添加到地圖。

濃縮液:

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

我去除現有的標記,通過AJAX獲得點的更新陣列,將它們添加到地圖中,然後重置地圖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); 
    } 
}