Leaflet JS多边形鼠标悬停高亮功能实现求助
Leaflet多边形鼠标悬停高亮实现方案
你的代码里缺少鼠标事件绑定和样式切换的核心逻辑,按照以下步骤修改即可实现高亮功能:
1. 定义高亮样式
新增一个与默认样式区分的高亮样式对象,可根据视觉需求调整参数:
var highlightStyle = { fillColor: "#ffcc00", color: "#ff0000", weight: 3, opacity: 1, fillOpacity: 0.7 };
2. 给图层绑定鼠标事件
修改districtdata函数,在保留弹窗绑定逻辑的基础上,添加鼠标悬停和移出的事件监听,实现样式切换:
function districtdata(feature, layer){ // 原弹窗绑定逻辑保留 layer.bindPopup("<span class='headings'>District: </span>" + feature.properties.ALD_DIST + "<br>" + "<span class='headings'>Representative: </span>" + feature.properties.Representa + "<br>" + "<span class='headings'>Contact Representative: </span>" + feature.properties.ContactRep + "<br>" + "<span class='headings'>District Population: </span>" + feature.properties.DistrictPo + "<span class='headings'></span>" + feature.properties.Image); // 鼠标悬停时应用高亮样式 layer.on('mouseover', function() { this.setStyle(highlightStyle); // 可选:让悬停图层置顶,避免被其他多边形遮挡 if (!this._map._panes.overlayPane.contains(this._path)) { this._map._panes.overlayPane.appendChild(this._path); } }); // 鼠标移出时恢复默认样式 layer.on('mouseout', function() { geojason.resetStyle(this); }); }
3. 完整修改后的代码
整合所有逻辑后的完整代码如下:
var map = L.map('map').setView([43.0982, -89.3811], 12); var googleSat = L.tileLayer('http://{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}',{ minZoom: 1, maxZoom: 20, subdomains:['mt0','mt1','mt2','mt3'], attribution: '<a href="https://www.google.com/maps" target=_blank> Google Sattellite Map</a>' }).addTo(map); // 默认多边形样式 var myStyle = { fillColor: "#2c7fb8", color: "#f20b0b", weight: 1, opacity: 1, fillOpacity: 0.55 }; // 高亮样式 var highlightStyle = { fillColor: "#ffcc00", color: "#ff0000", weight: 3, opacity: 1, fillOpacity: 0.7 }; // 加载GeoJSON数据 var geojason = L.geoJSON(alderdstricts, { style:myStyle, onEachFeature:districtdata, }).addTo(map); // 绑定弹窗与高亮事件 function districtdata(feature, layer){ layer.bindPopup("<span class='headings'>District: </span>" + feature.properties.ALD_DIST + "<br>" + "<span class='headings'>Representative: </span>" + feature.properties.Representa + "<br>" + "<span class='headings'>Contact Representative: </span>" + feature.properties.ContactRep + "<br>" + "<span class='headings'>District Population: </span>" + feature.properties.DistrictPo + "<span class='headings'></span>" + feature.properties.Image); // 鼠标悬停触发高亮 layer.on('mouseover', function() { this.setStyle(highlightStyle); // 图层置顶处理(可选) if (!this._map._panes.overlayPane.contains(this._path)) { this._map._panes.overlayPane.appendChild(this._path); } }); // 鼠标移出恢复默认样式 layer.on('mouseout', function() { geojason.resetStyle(this); }); };
关键说明
- 使用
geojason.resetStyle(this)可以快速恢复图层初始样式,无需手动重新设置所有样式属性; - 图层置顶代码为可选逻辑,解决多多边形重叠时悬停图层被遮挡的问题;
- 可根据需求自由调整
highlightStyle中的颜色、边框粗细等参数,适配你的地图视觉风格。
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

