代码
var map = new BMap.Map('map');
var center = new BMap.Point(116.668, 39.689);
map.centerAndZoom(center, 10);
map.enableScrollWheelZoom(true);
// 当前高亮的要素下标,-1 表示无高亮
var activeIndex = -1;
// 颜色、线宽用回调按要素求值:命中的那条用红色加粗,其余保持默认
function buildStyle() {
return {
strokeColor: function (properties, feature, index) {
return index === activeIndex ? '#ff0000' : '#2a6cf6';
},
strokeWeight: function (properties, feature, index) {
return index === activeIndex ? 6 : 5;
},
};
}
var options = buildStyle();
options.referCenter = center;
options.enablePicked = true; // 必须开启拾取,click 才会命中要素
var polylineLayer = new BMap.PolylineLayer(options);
map.addLayer(polylineLayer);
fetch('https://mapopen-pub-jsapigl.bj.bcebos.com/svgmodel/lineLayerData.json')
.then(function (res) {
return res.json();
})
.then(function (geojson) {
polylineLayer.setData(geojson);
})
.catch(function (err) {
console.error('线数据加载失败:', err);
});
// 命中要素 → 只高亮该条;点空白 → 清除高亮
polylineLayer.addEventListener('click', function (e) {
activeIndex = e.value ? e.value.index : -1;
// 传入新的回调触发图层按最新 activeIndex 重新求值
polylineLayer.setOptions(buildStyle());
});
通过 new BMap.PolylineLayer 创建折线图层,点击线条后记录命中要素的 index,并通过样式回调高亮对应折线。
预览