javascript - 动态Leaflet图层类

标签 javascript svg leaflet geojson

这是我的场景:我有一个具有点特征的 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/

相关文章:

css - svg 图形不适合

javascript - 在同一页面上显示 3 个传单 map

javascript - promise 重试模式内存占用

javascript - Vue 子组件不会因 Prop 更改而更新

html - HTML 中内联的 SVG <image> 标记未在浏览器中加载图像

javascript - d3js svg 水滴或泪滴

javascript - 传单弹出窗口在第一次关闭时清除内容

jquery - 带有 Leaflet-Awesome-Markers 的 Font-Awesome-Icons 不显示

javascript - 在Moment.js中,如何获取当前的财务季度?

javascript - 打印出数组中随机生成的数字后,在 2 个偶数之间添加破折号