2016-04-28 55 views
1

這是我的場景:我有一個具有點特徵的geojson,一些具有「救護車」屬性,其他「干預」。我將添加它們在地圖上與pointToLayer動態單張圖層類

var geojsonLayer = L.geoJson(cars, { 
pointToLayer: function(feature, latlng) { 
    return new L.Marker(latlng, {icon: cssIcon}); 
    }, onEachFeature: onEachFeature }); 

cssIcon變量使我可以使用SVG的我的觀點。

var cssIcon = L.divIcon({ 
     className: "css-icon", 
     html: "<svg> my svg code here </svg>" 
     ,iconSize: [20,20] 
     ,iconAnchor: [20,20]}); 

現在的問題。我需要爲這個Svgs添加特定的類(基於特性屬性),這樣我就可以使用新的Web Animation Api對它們進行動畫處理。我曾嘗試以下:

function onEachFeature(feature, layer) { 
layer.on({ 
    add: addClass, 
})}; 

...在addClass函數應查詢的功能,檢查功能的屬性爲「救護車」或「干預」,並相應地添加一個類:

function addClass(e){ 
    var layer = e.target; 
    if(layer.feature.properties.car_type === "ambulance"){ 
    L.DomUtil.addClass(layer.defaultOptions.icon.options, "ambulance-class"); 

}else(layer.feature.properties.car_type === "intervention") { 
    L.DomUtil.addClass(layer.defaultOptions.icon.options, "intervention-class"); 
}}; 

我得到的是:

  • 的「救護車」屬性將得到「救護車」級級層,但是...
  • 的具有「干預」屬性的圖層將獲得「干預級」,並且還將獲得「救護車級」級。

我也試過:

geojson_layer.eachLayer(function (layer) { 
    if(layer.feature.properties.car_type === "ambulance") {  
    L.DomUtil.addClass(layer.defaultOptions.icon.options, "ambulance-class"); 
    }}); 

..但是這沒有添加類。我可能錯誤地使用layer.defaultOptions.icon.options來添加類,但是使用這個我可以得到document.getElementsByClassName("ambulance-class")的對象。 任何想法?

回答

1

如果你調用一個單獨的函數內pointToLayer創建圖標,就可以檢查功能屬性和相應的類追加到className有:

function getCssIcon(feature) { 
    if (feature.properties.car_type === "ambulance") { 
    classTxt = " ambulance-class"; 
    } else if (feature.properties.car_type === "intervention") { 
    classTxt = " intervention-class"; 
    } 
    return L.divIcon({ 
    className: "css-icon" + classTxt, 
    html: "<svg> my svg code here </svg>", 
    iconSize: [20, 20], 
    iconAnchor: [20, 20] 
    }); 
} 

var geojsonLayer = L.geoJson(cars, { 
    pointToLayer: function(feature, latlng) { 
    return new L.Marker(latlng, { 
     icon: getCssIcon(feature) 
    }); 
    }, 
    onEachFeature: onEachFeature 
}).addTo(map); 
+0

這是我落得這樣做。 –