2015-09-30 91 views
7

按照一個例子,你可以看到plunker她http://plnkr.co/edit/lJHyP3dhT3v8aHVdt3D3?p=preview自動縮放的地圖,以適應所有標記

無論任何變焦值,而initializitng地圖提供的,我想自動縮放地圖,讓所有的標記是在視圖內。這裏是我的代碼

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

回答

10

您需要

  • 創建數組

  • 推陣列中所有的標誌

  • 一旦所有的標記被添加到陣列中,創建一個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

相關問題