2015-08-25 27 views
0

我對geoJson文件中提供的一個準則基於geoJson文件中不同的geoJson功能感興趣。我知道我可以通過onEachFeature鉤子來實現,但我也希望用戶在解析的圖層上具有圖層控制(圖層顯示開啓/關閉)。爲此,我創建一個layerGroup。我是JS和Leaflet新手,並且無法弄清楚如何從geoJson文件中添加到layerGroup中的單個特性。如何將geoJson文件解析爲單張圖層

某些代碼:

var active = new L.layerGroup(); 
var inactive = new L.layerGroup(); 

// kcdfp_parcel is the geoJson file variable 
for (var i=0; i < kcdfp_parcel.features.length; ++i) 
    if (kcdfp_parcel.features[i].properties.InActive == 0){ // Inactive=no 
// How to add to the active layerGroup???? 
var overlays = { 
    "Active": active, 
    "Inactive": inactive}; 
L.control.layers(overlays).addTo(map); 
+0

代碼示例不使用onEachFeature,而是使用i ++循環。是否有理由選擇其中之一? – TomC

+0

找到了將geoJson轉換爲Leaflet圖層的通用方法。編碼遠遠超出了我的理解程度。 [鏈接] http://jsfiddle.net/mvLe5n39/ – TomC

+0

如果你知道JavaScript只是檢查https://github.com/gagan-bansal/geojson2svg,這裏有一些例子http://maps-on-blackboard.com/ tag/geojson2svg/ – Gagan

回答

0

onEachFeature的優點是,它爲您提供了該功能創建的層的直接訪問。

此外,如果使用new關鍵字you have to capitalize the name of the "class"。更容易不使用new

var active = L.layerGroup(); 
var inactive = L.layerGroup(); 

L.geoJson(kcdfp_parcel, { 
    onEachFeature: function(feature, layer) { 
     if (feature.properties.InActive == 0) { 
      layer.addTo(active); 
     } else { 
      layer.addTo(inactive); 
     } 
    } 
}) 

// the rest as you had it 
var overlays = { 
    "Active": active, 
    "Inactive": inactive 
}; 
L.control.layers(overlays).addTo(map); 
+0

謝謝。我不熟悉「圖層」參考。它是否是JS層次結構的一部分?或者傳遞給每個功能的參數? – TomC

+0

它是一個參數。當小冊子解析每個geoJSON特徵時,它會將其轉換爲小冊子「圖層」 - 基本上可以在地圖上顯示的抽象對象 – toms

+0

謝謝。如果你不介意,我也有一些問題得到層的樣式。我發現.setStyle並嘗試過,但它不起作用。每一層都是多邊形。這是我添加的代碼: '代碼' L.geoJson(kcdfp_parcel,{ onEachFeature:功能(功能,層){ 如果(feature.properties.InActive == 0){ \t \t \t layer.setStyle({填充顏色: '紅'}); \t \t \t layer.addTo(活性); }否則{ layer.setStyle({填充顏色: '藍'}); \t \t \t layer.addTo(不活動); } } }) – TomC