2013-02-08 119 views
3

我正在使用Leaflet框架處理等值線地圖。我想有好幾年了幾個不同的層,所以我已經寫了這個代碼(注意,只有名字‘style2002’和‘style2010’應該過去了,不帶任何參數):Leaflet:將額外的參數傳遞給L.geoJson選項

 population2002 = L.geoJson(regionData, { 
     style: style2002 
    }); 

    population2010 = L.geoJson(regionData, { 
     style: style2010 
    }); 

,有「風格」功能,這是着色我的矢量多邊形depening其屬性(其名稱爲前綴「Pop_」加年)是:

 function style2002(feature) 
    { 
     return { 
      fillColor: getColor(feature.properties.Pop_2002), 
      weight: 2, 
      opacity: 1, 
      color: 'white', 
      dashArray: '', 
      fillOpacity: 0.7 
     }; 
    } 

    function style2010(feature) 
    { 
     return { 
      fillColor: getColor(feature.properties.Pop_2010), 
      weight: 2, 
      opacity: 1, 
      color: 'white', 
      dashArray: '', 
      fillOpacity: 0.7 
     }; 
    }; 

正如您可以猜到,我想用一個「風格」功能,而不是我需要每年的獨立功能。例如:

 function styleByYear(feature, year) 
    { 
     var property = 'feature.properties.Pop_'; 
     property += year; 
     return { 
      fillColor: getColor(property), 
      weight: 2, 
      opacity: 1, 
      color: 'white', 
      dashArray: '', 
      fillOpacity: 0.7 
     }; 
    } 

但如何將第二個參數傳遞給樣式函數?在L.geoJson構造函數中,我只寫了函數的名字,沒有任何參數,正如你從第一段代碼中看到的那樣! 我該怎麼辦? 還有一個問題:如何將第一個參數('feature')傳遞給圖層構造函數..?

回答

0

您可以嘗試Leaflet tutorial on GeoJSON中的內容。在「選項」部分查找第二個代碼部分。您只需首先添加常規樣式(即兩年內相同的樣式)。從該網站加入您的特定代碼所採取的示例:

geojsonlayer = L.geoJson(regionData, { 
    style: function(feature) { 
    var finalStyleObject = normalStyling(feature); //return the normal style object 
    switch (feature.properties) { //switch through the various years 
     case 'Pop_2002': {finalStyleObject.fillColor: "#ff0000"}; 
     case 'Pop_2010': {finalStyleObject.fillColor: "#0000ff"}; 
    } 
    return finalStyleObject; 
    } 
}); 

function normalStyling(feature){ 
    return { 
     weight: 2, 
     opacity: 1, 
     color: 'white', 
     dashArray: '', 
     fillOpacity: 0.7 
    }; 
} 
1

如果你創建一個全局變量:

var property = 'Pop_' + year 

和編輯你的函數以下(您應該使用括號,而不是點表示) :

function styleByYear(feature) 
{ 

    return { 
     fillColor: getColor(feature['properties'][property]), 
     weight: 2, 
     opacity: 1, 
     color: 'white', 
     dashArray: '', 
     fillOpacity: 0.7 
    }; 
} 

我已經做了類似於你所要求的基於你的choropleth教程的東西。我有多個按鈕可以更改不同日期的地圖樣式。

相關問題