功能介绍
![](https://img-blog.csdnimg.cn/direct/9e6ea9a2fa5b4ebaadea6876509be234.png)
这个功能是小程序会打开地图显示附近的地点,用户可以在地图或者列表选择位置添加地点。用于添加收货地址、添加商铺等功能场景。怎么做这个功能呢?
怎么做
第一步
在wxml文件加上调起这个"onSearchAddress"
<!-- xx.wxml -->
<button bindtap="onSearchAddress" class="input-button">选择地址</button>
第二步
在js文件加入以下代码内容
// JS文件代码:
//授权相关权限
builtInSearch({ code, name }) {
return new Promise((resolve, reject) => {
wx.getSetting({
success: (res) => {
if (res.authSetting[code] === false) {
wx.showModal({
title: `获取${name}失败`,
content: `获取${name}失败,请在【右上角】-小程序【设置】项中,将【${name}】开启。`,
confirmText: '去设置',
confirmColor: '#FA550F',
cancelColor: '取消',
success(res) {
if (res.confirm) {
wx.openSetting({
success(settinRes) {
if (settinRes.authSetting[code] === true) {
resolve();
} else {
console.warn('用户未打开权限', name, code);
reject();
}
},
});
} else {
reject();
}
},
fail() {
reject();
},
});
} else {
resolve();
}
},
fail() {
reject();
},
});
});
},
onSearchAddress() {
console.log('onSearchAddress method is triggered');
this.builtInSearch({ code: 'scope.userLocation', name: '地址位置' }).then(() => {
wx.chooseLocation({
success: (res) => {
console.log('wx.chooseLocation success:', res);
if (res.name) {
this.setData({
'locationState.address': res.address,
'locationState.name': res.name,
'locationState.latitude': res.latitude,
'locationState.longitude': res.longitude,
});
} else {
Toast({
context: this,
selector: '#t-toast',
message: '地点为空,请重新选择',
icon: '',
duration: 1000,
});
}
},
fail: function (res) {
console.warn(`wx.chooseLocation fail: ${JSON.stringify(res)}`);
if (res.errMsg !== 'chooseLocation:fail cancel') {
Toast({
context: this,
selector: '#t-toast',
message: '地点错误,请重新选择',
icon: '',
duration: 1000,
});
}
},
});
});
},
主要是通过小程序官方wx.chooseLocation接口调起小程序内置的地图选择界面
(官方文档:wx.chooseLocation(Object object) | 微信开放文档)
除此以上代码之外,还需要把https://apis.map.qq.com地址添加到request合法域名中才能运行,如未添加具体可以参考重新编译后的报错信息来解决