javascript - 点击后如何清除传单层
问题描述
我尝试使用鼠标单击来选择/取消选择图层。首先我的地图是这样的
单击图层后,我想选择它并突出显示
现在,如果我再次单击先前选择的图层,我想取消选择它并重置高亮。这是我用来执行此操作的代码:
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: '© <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>
希望这会帮助你。
推荐阅读
- npm-install - npm 错误!对 https://registry.npmjs.org/ngx-pagination 的请求失败,原因:getaddrinfo EAI_AGAIN registry.npmjs.org registry.npmjs.org:443
- c# - 更改其他文本框时 WPF 绑定文本框值未更新
- ruby-on-rails - 在Rails中erb的文本字段中显示模型的所有ID
- python-3.x - 即使输入相同,相同的代码在主函数和用户定义的函数中使用时也会给出不同的输出
- javascript - D3:条形图的文本不出现
- javascript - 使用伊斯坦布尔插件构建代码时出错
- python - 如何在云端部署 selenium bot
- networking - ADFS / SSO - 高可用性实施
- angular - 如何在 Angular 中创建嵌套路由设置
- python - Python中“AttributeError:'list'对象没有属性'split'”的问题