点击功能的传单

Leaflet clicking on features

本文关键字:功能      更新时间:2023-09-26

因此,我正试图使用传单w/geojson作为坐标来绘制公交路线。我在一个方面遇到了困难,点击一次,总线就会加粗,理想情况下,最后一次点击的功能会返回到默认样式。

到目前为止我有什么

function $onEachFeature(feature, layer) {
   layer.on({
    click: function(e) {
        //calls up the feature clicked on
        var $layer = e.target;
        var highlightStyle = {
            opacity: 1,
            weight: 5
        };
        $layer.bringToFront();
        $layer.setStyle(highlightStyle);
    }
 }); 
}
//imagine all the leaflet map tile code here
//this is where the features get added in and the $oneachfeature function
var busFeature = L.geoJson(busRoutes, {
     style: defaultBusRouteColor,
     onEachFeature : $onEachFeature
});
busFeature.addTo(map);

上面,我现在已经成功地将特性的样式更改为highlightStyle中的样式。但是,当单击另一个功能时,样式将保持不变。如何删除以前单击的功能的样式,以便一次只有一个功能具有样式highlightStyle

我已经尝试过的事情:使用addClass/removeClass到jQuery方法,使用带有传单的layer.resetStyle(),以及其他一些仍然不起作用的事情。注意:这将理想地用于移动版本,因为桌面版本使用悬停功能来强调功能,没有问题。这个:

function $oneachfeature(feature, layer){
   layer.on({
      mouseover: function (e){makes feature bold}
 });
   layer.on({
      mouseout: function (e){makes feature normal again}
 });
}

有什么建议吗?

存储对高亮显示层的引用,以便以后可以在其上调用resetStyle

// Variable to store selected
var selected
// Create new geojson layer
new L.GeoJSON(collection, {
  // Set default style
  'style': function () {
    return {
      'color': 'yellow',
    }
  }
}).on('click', function (e) {
  // Check for selected
  if (selected) {
    // Reset selected to default style
    e.target.resetStyle(selected)
  }
  // Assign new selected
  selected = e.layer
  // Bring selected to front
  selected.bringToFront()
  // Style selected
  selected.setStyle({
    'color': 'red'
  })
}).addTo(map)
  • 示例:http://embed.plnkr.co/RnQO1s/preview
  • 参考:http://leafletjs.com/reference.html#geojson-resetstyle

使用resetStyle()似乎是一个更容易的解决方案。。。在将新样式应用于特征之前,只需重置图层的样式即可。这只需要在原始函数中添加一行代码:

function $onEachFeature(feature, layer) {
    layer.on({
    click: function(e) {
        //calls up the feature clicked on
        var $layer = e.target;
        var highlightStyle = {
            opacity: 1,
            weight: 5
        };
        busFeature.resetStyle();
        $layer.bringToFront();
        $layer.setStyle(highlightStyle);
    }
}); 
}

在添加下一个突出显示之前先删除前一个:

.removeLayer()使用.addTo()删除之前设置的geoJSON选择

theMap = yourMap.Map
geoJson = yourMap.geoJSON();
onclick() {
    const highlightedFeature = {
      'color': '#12FF38',
      'fillColor': '#30D8E0',
      'fillOpacity': 0.3
    };
    this.theMap.removeLayer(this.geoJson);
    this.geoJson = yourMap.geoJSON( Feature, {
       style: highlightedFeature
    });
        
    this.geoJson.addTo(this.theMap);
}