amap mousewheel 阻断小技巧
背景
经常我们会遇到这样的一个情况:在鼠标在非地图模块上时,滚动鼠标滑轮,希望是滚动页面,而非缩放地图。
然后高德地图的 map.on('mousewheel')
事件无法被常规打断。且报错也被劫持,无法特殊处理。
技巧
核心理念
监听mousewheel
,并且当鼠标不在地图核心模块时,通过throw err进行强行阻断。
但同时需要对err进行处理,避免被错误上报系统抓取。
代码示例
mapIns?.on('mousewheel', methods.onMousewheel);
onMousewheel(event) {
try {
const res = mapLayerRef.current.getDistrictByContainerPos(event.pixel) || {};
if (!res.adcode) {
event.preventDefault(); // 通过这个强行让后台报错,从而阻断原生滚动
} else {
let codeList = [...wheelUseAdcode.current]; // 这里的wheelUseAdcode.current就是所有的当前视角里正在展示的城市code合集
const strCode = String(res.adcode);
if (strCode === '110000' || strCode === '110100') { // 北京
codeList = [...codeList, '110000', '110100'];
} else if (strCode === '120000' || strCode === '120100') { // 天津
codeList = [...codeList, '120000', '120100'];
} else if (strCode === '310000' || strCode === '310100') { // 上海
codeList = [...codeList, '310000', '310100'];
} else if (strCode === '500000' || strCode === '500100' || strCode === '500500') { // 重庆
codeList = [...codeList, '500000', '500100', '500200'];
}
if (!codeList.includes(strCode)) {
event.preventDefault(); // 通过这个强行让后台报错,从而阻断原生滚动
}
}
} catch(err) {
throw new Error('请至地图内部进行缩放操作'); // 在src/common/ignore/sentryError.ts处被过滤,将不做错误上报
}
},