自动缩放地图以适合所有标记

时间:2015-09-30 08:18:29

标签: leaflet markerclusterer

举个例子,你可以看到她的http://plnkr.co/edit/lJHyP3dhT3v8aHVdt3D3?p=preview

无论在初始化地图时提供什么缩放值,我都想自动缩放地图,以便所有标记都在视图内。这是我的代码

var tiles = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
        maxZoom: 18,
        attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors, Points &copy 2012 LINZ'
    }),
    latlng = L.latLng(-37.82, 175.24);

var map = L.map('map', {center: latlng, zoom: 10, layers: [tiles]});

var markers = L.markerClusterGroup();

for (var i = 0; i < addressPoints.length; i++) {
    var a = addressPoints[i];
    var title = a[2];
    var marker = L.marker(new L.LatLng(a[0], a[1]), { title: title });
    marker.bindPopup(title);
    markers.addLayer(marker);
}

map.addLayer(markers);

var group = new L.featureGroup(markers);

map.fitBounds(group.getBounds());

1 个答案:

答案 0 :(得分:13)

你需要

  • 创建一个数组

  • 将所有标记推送到数组

  • 将所有标记添加到数组后,创建featureGroup
  • 将您的标记数组添加到featureGroup,然后缩放到其边界。

以下是已修改代码

var markerArray = []; //create new markers array

for (var i = 0; i < addressPoints.length; i++) {
    var a = addressPoints[i];
    var title = a[2];
    var marker = L.marker(new L.LatLng(a[0], a[1]), { title: title });
    marker.bindPopup(title);
    markers.addLayer(marker);

    markerArray.push(marker); //add each markers to array

    if(i==addressPoints.length-1){//this is the case when all the markers would be added to array
        var group = L.featureGroup(markerArray); //add markers array to featureGroup
        map.fitBounds(group.getBounds());   
    }
}

这是工作plunk