2016-08-17 83 views
1

我正在使用Leaflet和Leaflet.draw來創建地圖。當我在地圖上繪製矩形(作爲用戶)時,以下代碼寫出矩形的LatLng邊界。如何編輯Leaflet中的彈出窗口

// add the newly drawn items to a layer 
    map.on('draw:created', function (e) { 
     var type = e.layerType, 
      layer = e.layer; 

     // binds things upon creation 
     if (type === 'rectangle') { 
      var bounds = layer.getBounds(); 
      layer.bindPopup(bounds.getNorthWest().toString() + "NW" + bounds.getSouthEast().toString() + "SE"); 
     } 

     drawnItems.addLayer(layer); 
    }); 

我想在矩形被用戶編輯時更新它。我認爲應該使用'draw:edited'事件和'_popup.SetContent'更新這樣的內容,但LatLng不會更新。

// update LatLng when edited 
    map.on('draw:edited', function (e) { 
     var type = e.layerType, 
      layer = e.layer; 

     // update popup 
     if (type === 'rectangle') { 
      var bounds = layer.getBounds(); 
      layer._popup.SetContent(bounds.getNorthWest().toString() + "NW" + bounds.getSouthEast().toString() + "SE"); 
     } 
    }); 

添加第二個代碼塊也意味着我只能編輯有史以來創建的第一個矩形。所以這顯然不起作用,但我不知道爲什麼。

回答

2

我想通了。對於draw:edited事件,我需要使用eachLayer方法遍歷e.layers中的每個圖層,然後instanceof來檢查圖層類型。我還綁定了一個新的彈出窗口,而不是編輯舊的彈出窗口。

下面的代碼,其中也有在彈出一個換行符,以使其更易於閱讀:

// update LatLng value 
    map.on('draw:edited', function (e) { 
     var layers = e.layers; 

     layers.eachLayer(function (layer) { 
      // do whatever you want to each layer, here update LatLng 
      if (layer instanceof L.Rectangle) { 
       var bounds = layer.getBounds(); 
       layer.bindPopup(bounds.getNorthWest().toString() + " NW<br>" + bounds.getSouthEast().toString() + " SE"); 
      } 
     }); 
    }); 

感謝this question about retrieving layer type on edit指着我在正確的方向。