最近在写支付宝小程序的时候,想要在地图上面添加几个按钮,但是发现支付宝小程序不能像微信小程序那样有专用的控件标签,只能通过在 <map> 标签内添加 controls="{{controls}}"属性来实现这个功能。具体实现方法如下:
添加控件
官方文档
注意:这个controls 是一个数组,里面可以写多个控件。
具体写法如下:
index.axml文件:
<map
id="myMap"
onMarkerTap="markertap"
show-location
controls="{{controls}}"
onControlTap="controltap"></map>index.js文件:
Page({ data: {
motto: 'Hello World',
controls: [{
id: 1,
iconPath: '../../img/location.png',
position: {
left: 280,
top: 250,
width: 30,
height: 30
}, clickable: true
},{ id: 2,
iconPath: '../../img/location.png',
position: {
left: 280,
top: 300,
width: 30,
height: 30
}, clickable: true
},{ id:3,
iconPath:'../../img/scancode.png',
position:{
left:10,
top:400,
width:300,
height:40
}, clickable: true
}]
},
})最后效果是这样:
注意:在controls内部写入了 id ,这个是用来区分我点击哪个控件触发对应事件的。因为在 <map> 标签内,所有的控件只能通过一个 onControlTap="controltap"来触发,所以需要一个 id 来作为索引。
为控件添加事件
在上面地图中,我们有三个控件,所以就需要先分别写三个与之对应的事件,然后根据官方提供的id属性这个思路来做,通过点击控件来判断该控件返回的 id 值,来判断到底点到了哪个控件上面,再来匹配且触发与之对应的事件:
index.js文件:
//三个事件
scanCode() {
my.scan({ type: 'qr', success: (res) => {
my.alert({ title: res.code });
},
});
},
call() {
my.makePhoneCall({ number: '400-6701818' });
},
moveToLocation() { this.mapCtx.moveToLocation()
},//事件的处理方法
controltap(e){ switch(e.controlId){ case 1: this.moveToLocation(); break; case 2: this.call(); break; case 3: this.scanCode(); break; default:break;
}
}
作者:刘员外__
链接:https://www.jianshu.com/p/328bc24d3f65