先在 manifest.json 配置 premission 属性
"mp-weixin" : {
"appid" : "wxxxxxxxxxxxxxxxxe",
"setting" : {
"urlCheck" : false,
"es6" : true,
"postcss" : true,
"minified" : true
},
"usingComponents" : true,
"permission" : {
"scope.userLocation" : {
"desc" : "小程序将使用定位功能"
}
}
},
在页面中调用
<template>
<view @click="getSetting">获取当前位置</view>
<map
v-if="latitude && longitude"
style="width: 100%; height: 330rpx;"
class="mb-40"
:latitude="latitude"
:longitude="longitude"
:markers="maskers"
></map>
</template>
<script>
method: {
getSetting() { // 获取定位权限
uni.getSetting({ // 获取用户当前设置
success: res => {
// res.authSetting 用户授权结果,其中key为scope值,value为Boolean值,表示用户是否允许授权
if (res.authSetting["scope.userLocation"]) {
this.chooseLocation();
} else {
/*
uni.authorize 提前向用户发起授权请求
调用后会立刻弹窗询问用户是否同意授权,但不会实际调用对应接口
若用户之前已同意授权,则不会出现弹窗,直接返回成功
若用户之前拒绝授权,此接口会直接进入失败回调
一般搭配uni.getSetting和uni.openSetting使用
*/
uni.authorize({
scope: "scope.userLocation", // 需要获取权限的 scope
success: res => {
this.chooseLocation();
},
fail: error => {
uni.showModal({
title: "提示",
content: "检测到您没打开获取位置功能权限,是否去设置打开?",
confirm: () => {
this.openSettiog();
}
});
}
});
}
}
});
},
// 打开位置设置权限
openSettiog() {
uni.openSetting({ // 调起客户端小程序设置界面,返回用户设置的操作结果
success: res => {
if (res.authSetting["scope.userLocation"]) {
this.chooseLocation();
} else {
uni.showToast({
title: "您拒绝了授权, 无法操作内容",
icon: "none",
duration: 2500
});
}
}
});
},
// 选择位置
chooseLocation() {
uni.chooseLocation({ // 打开地图选择位置
success: res => {
if (!res.address) return false;
this.formData.address = res.address; // 详细地址
this.latitude = res.latitude; // 纬度
this.longitude = res.longitude; // 经度
const masker = [
{
id: 1,
latitude: res.latitude,
longitude: res.longitude,
iconPath: "/static/images/train/address.png",
width: 20,
height: 27
}
];
this.maskers = masker; // 将位置信息显示到页面地图中
},
fail: error => {
uni.showToast({
title: error,
icon: "none",
duration: 2500
});
}
});
},
}
</script>