动态 Leaflet 图层 class

Dynamic Leaflet layer class

这是我的场景:我有一个带有点特征的 geojson,一些带有属性 "ambulance",其他带有 "intervention"。我将使用 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 添加特定的 classes(基于特征属性),这样我就可以使用新的 Web Animation Api 为它们制作动画。我尝试了以下方法:

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

... addClass 函数应该查询特征的地方,检查特征的属性是 "ambulance" 还是 "intervention" 并相应地添加一个 class:

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"); 
  }});

..但这根本不会添加 classes。我在使用 layer.defaultOptions.icon.options 添加 class 时可能是错误的,但使用它我能够获得带有 document.getElementsByClassName("ambulance-class") 的对象。 有任何想法吗?

如果您调用单独的函数在 pointToLayer 中创建图标,您可以检查功能属性并将适当的 class 附加到 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);