这是我的场景:我有一个具有点特征的 geojson,其中一些具有“救护车”属性,其他具有“干预”属性。我将使用 pointToLayer 将它们添加到 map 上
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");
}};
我得到的是:
- 具有“ambulance”属性的图层将获得“ambulance-class”类别,但是...
- 具有“intervention”属性的图层将获得“intervention-class”,并且还将获得“ambulance-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")< 获取对象
。
有任何想法吗?
最佳答案
如果您调用单独的函数在 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);
关于javascript - 动态Leaflet图层类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36918429/