gpt4 book ai didi

javascript - 点击后如何清除传单层

转载 作者:行者123 更新时间:2023-12-03 09:43:18 26 4
gpt4 key购买 nike

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



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



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

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

}

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

最佳答案

您只需使用 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>


您可以引用 thisthis了解更多信息。

希望这会对你有所帮助。

关于javascript - 点击后如何清除传单层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59662856/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com