首页 > 解决方案 > 点击后如何清除传单层

问题描述

我尝试使用鼠标单击来选择/取消选择图层。首先我的地图是这样的

单击图层后,我想选择它并突出显示

现在,如果我再次单击先前选择的图层,我想取消选择它并重置高亮。这是我用来执行此操作的代码:

  onEachFeature: function(feature,layer) {

      layer.setStyle({fillOpacity: 0.0 , color: '#424a44', weight: 2});
      layer.on('click', function(e) {

      let isLayerAlreadySelected =  // Some logic to undestand if layer alreeady selected

      if(isLayerAlreadySelected) 
         layer.setStyle({fillOpacity: 0.0 , color: '#424a44', weight: 2});
      else
          layer.setStyle({fillOpacity: 0.4 , color: '#004691', weight: 3});
      }

  }

但有时当我尝试取消选择先前选择的图层时,图层样式不会重置不透明度。对此有何建议?

标签: javascriptangularleaflet

解决方案


只需使用resetStyle()方法将给定矢量图层的样式重置为原始 GeoJSON 样式。

var map = L.map('map').setView([37.8, -96], 4);

	L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
		maxZoom: 18,
		attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
	}).addTo(map);




	// get color depending on population density value
	function getColor(d) {
		return d > 1000 ? '#800026' :
				d > 500  ? '#BD0026' :
				d > 200  ? '#E31A1C' :
				d > 100  ? '#FC4E2A' :
				d > 50   ? '#FD8D3C' :
				d > 20   ? '#FEB24C' :
				d > 10   ? '#FED976' :
							'#FFEDA0';
	}

	function style(feature) {
		return {
			weight: 2,
			opacity: 1,
			color: 'white',
			dashArray: '3',
			fillOpacity: 0.7,
			fillColor: getColor(feature.properties.density)
		};
	}

	function highlightFeature(e) {
    geojson.resetStyle();
		var layer = e.target;

		layer.setStyle({
			weight: 5,
			color: '#666',
			dashArray: '',
			fillOpacity: 0.7
		});

		if (!L.Browser.ie && !L.Browser.opera && !L.Browser.edge) {
			layer.bringToFront();
		}

	}

	var geojson;

	function resetHighlight(e) {
		geojson.resetStyle(e.target);
	}

	function zoomToFeature(e) {
		map.fitBounds(e.target.getBounds());
	}
    // Set style function that sets fill color property
function style(feature) {
    return {
        fillColor: '#004691', 
        fillOpacity: 0.5,  
        weight: 1,
        opacity: 1,
        color: '#424a44',
        dashArray: '1'
    };
}
	var highlight = {
		'fillColor': 'yellow',
		'weight': 1,
		'opacity': 1
	};

	function onEachFeature(feature, layer) {
		layer.on({
			
			click: highlightFeature
		});
        
	}

	geojson = L.geoJson(statesData, {
		style: style,
		onEachFeature: onEachFeature
	}).addTo(map);
#map {
         width: 600px;
         height: 400px;
         }
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" crossorigin=""/>
    <script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js"crossorigin=""></script>
      
       <div id='map'></div>
      <script type="text/javascript" src="https://leafletjs.com/examples/choropleth/us-states.js"></script>

您可以参考以获取更多信息。

希望这会帮助你。


推荐阅读