index.wxml:
在微信小程序中使用map组件开发时遇到了一个问题,应该是官网的bug,就是当添加marker标签后同时给地图绑定bindtap事件和标签事件bindmarkertap事件,当点击marker后也会触发bindtap事件,导致不能单独对marker标签进行事件操作;
以下是解决方案:(思路阐述)
这里利用marker标签点击后会先执行bindtap事件再去执行bindmarkertap事件的特性,在点击marker标签后利用节流的方案来只执行规定事件内最后一次点击事件(即bindmarkertap事件),这样就合理地解决了这个bug
index.wxml:
// wxml
<map
id="myMap"
style="width: 100%; height: 100vh;"
latitude="{{latitude}}"
longitude="{{longitude}}"
markers="{{markerList}}"
scale="{{scale}}"
show-location
bindmarkertap="toMarkerForm" // marker点击事件
bindtap="toMarkerForm" // 地图点击事件
enable-satellite="{{true}}"
></map>
index.js:
// js
Page({
data: {
event: null
},
// bindtap和bindmarkertap事件同时同意入口进行节流操作
toMarkerForm: function (e) {
// 保存event
this.setData({
event: e,
})
// 节流控制只执行最后一次点击事件
throttle(this.goForm, 100)
},
goForm: function (e) {
const { event } = this.data
if (event) {
if (event.type === 'markertap') {
console.log('点击了marker')
} else {
console.log('点击了地图')
}
}
})
节流函数(util.js):
let timer = null;
const throttle = (fn, wait) => {
let context = this;
let args = arguments;
if (!timer) {
timer = setTimeout(() => {
fn.apply(context, args);
timer = null;
}, wait)
}
}
小伙伴如果有疑问可以第一时间评论或留言,看到后也会及时回复的,有帮助的麻烦动动手指点个赞哟