重置Google Maps API v3上的界限

时间:2011-06-13 16:00:43

标签: google-maps google-maps-api-3

当用户选择一个选项时,如何重置GoogleMap的界限?界限已经设置为包含该区域的“大图”,我想在用户选择选项时缩放到特定区域......并且需要通过重置边界来实现。扩展以包括纬度/长度将不起作用,因为它们已经包含在内。

1 个答案:

答案 0 :(得分:14)

您必须创建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获取更新的点数组,将它们添加到地图,然后重置地图边界。

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