2015-09-08 57 views
1

我使用L.divIcon在Leaflet/Mapbox.js地圖上設置樣式標記。我設法將一個className設置爲地圖上的所有要素,但我想根據與每個要素關聯的屬性設置不同的類。似乎我嘗試過的每個配置都會返回一個「功能未定義」錯誤,或者只會返回默認的l.divIcon方塊。根據geoJSON屬性設置不同的L.divIcon樣式

"features": [ 
{ "type": "Feature", "properties": { "Dam_name": "A Luoi", "Main": "false"}, "geometry": { "type": "Point", "coordinates": [ 107.18, 16.21 ] } }, 
{ "type": "Feature", "properties": { "Dam_name": "Banda", "Main": "true"}, "geometry": { "type": "Point", "coordinates": [ 97.93, 30.2 ] } }, 

我創建了一個開關功能,以尋找「真」與「假」,並返回一個CSS類,我已經:

http://pennybeames.net/maps/MekongHydroTimeline2.html

從GeoJSON的摘錄進展中的工作在我的樣式表中定義:

function getClassName(x) { 
      switch(x) { 
       case "true": 
        return 'circle' ; 
        //'circle set in stylesheet' 
        break; 
       case "false": 
        //'leaflet-div-icon' set by leaflet stylesheet 
        return 'leaflet-div-icon'; 
        break; 
       default: 
        //set default to 'triangle' from my own stylesheet to test if the code 
        //was recognizing this function and would set everything to 'triangle', 
        //but it doesn't 
        return 'triangle'; 
        break; 
     }}; 

,然後創建一個函數的className取決於以GeoJSON在feature.properties.Main發現結果返回:

var setDivIcon = function(feature) { 
      return { 
       className: getClassName(feature.properties.Main) 
      }; 
     } 

,然後創建我的L.divIcon:

var damIcon = L.divIcon(setDivIcon); 

後來我用pointToLayer後來到以GeoJSON添加到地圖:

pointToLayer: function (feature, latlng) { 
     return L.marker(latlng, {icon: damIcon}); 
    } 

但無論怎樣,我都get是默認的leaflet-div-icon,並在控制檯中獲得零錯誤。我錯過了什麼?

回答

1

L.divIcontakes an object as input

var damIcon = L.divIcon(setDivIcon); 

setDivIcon是函數返回對象,而不是一個對象。

正確的通話將

var damIcon = L.divIcon(setDivIcon(feature)); 

而且所有一起:

pointToLayer: function (feature, latlng) { 
    return L.marker(latlng, { icon: L.divIcon(setDivIcon(feature)) }); 
} 
+0

真棒,謝謝。 我第一次嘗試這個時,我同時插入了兩個建議。下面給了我一個「功能未定義」的錯誤: var damIcon = L.divIcon(setDivIcon); 但是{icon:L.divIcon(setDivIcon(feature))}像一個魅力一樣工作。 – user3825080

相關問題