两种思路:
1、通过OpenLayers自身交互事件
2、通过地图鼠标移动事件触发选择要素
第一种:
const select = new ol.interaction.Select({
condition: ol.events.condition.pointerMove, //以某种状态选择要素,关键代码,默认点击选择要素
hitTolerance: 5 //设置容差
});
map.addInteraction(select);
也可以利用选择事件做一些操作
select.on('select', function (e) {
if (e.selected.length > 0) { console.log('选中:', e.selected) }
else { console.log('取消选中!') }
})
第二种:
// 识别
const hoverStyle = new ol.style.Style({
fill: new ol.style.Fill({
color: 'green'
}),
stroke: new ol.style.Stroke({
color: 'black',
width: 5
}),
image: new ol.style.Circle({
radius: 10,
stroke: new ol.style.Stroke({
color: 'rgba(0,0,0,0.7)',
}),
fill: new ol.style.Fill({
color: 'green'
})
}),
})
let hoverFeature;
function featureHover(e) {
let features = map.getFeaturesAtPixel(e.pixel, { hitTolerance: 3 }) //getFeaturesAtPixel()获取与视口像素相交的所有元素,返回类型为数组类型
if (features) {
if (hoverFeature) {
hoverFeature.setStyle(undefined);
hoverFeature = null
}
hoverFeature = features[0];
console.log(hoverFeature);
hoverFeature.setStyle(hoverStyle2);
}
else {
if (hoverFeature) {
hoverFeature.setStyle(undefined);
}
}
}
map.on('pointermove', featureHover);
如有错误欢迎指正!!!