1. 先在 manifest.json 配置 premission 属性

      1. "mp-weixin" : {
      2. "appid" : "wxxxxxxxxxxxxxxxxe",
      3. "setting" : {
      4. "urlCheck" : false,
      5. "es6" : true,
      6. "postcss" : true,
      7. "minified" : true
      8. },
      9. "usingComponents" : true,
      10. "permission" : {
      11. "scope.userLocation" : {
      12. "desc" : "小程序将使用定位功能"
      13. }
      14. }
      15. },
    2. 在页面中调用

      1. <template>
      2. <view @click="getSetting">获取当前位置</view>
      3. <map
      4. v-if="latitude && longitude"
      5. style="width: 100%; height: 330rpx;"
      6. class="mb-40"
      7. :latitude="latitude"
      8. :longitude="longitude"
      9. :markers="maskers"
      10. ></map>
      11. </template>
      1. <script>
      2. method: {
      3. getSetting() { // 获取定位权限
      4. uni.getSetting({ // 获取用户当前设置
      5. success: res => {
      6. // res.authSetting 用户授权结果,其中key为scope值,value为Boolean值,表示用户是否允许授权
      7. if (res.authSetting["scope.userLocation"]) {
      8. this.chooseLocation();
      9. } else {
      10. /*
      11. uni.authorize 提前向用户发起授权请求
      12. 调用后会立刻弹窗询问用户是否同意授权,但不会实际调用对应接口
      13. 若用户之前已同意授权,则不会出现弹窗,直接返回成功
      14. 若用户之前拒绝授权,此接口会直接进入失败回调
      15. 一般搭配uni.getSetting和uni.openSetting使用
      16. */
      17. uni.authorize({
      18. scope: "scope.userLocation", // 需要获取权限的 scope
      19. success: res => {
      20. this.chooseLocation();
      21. },
      22. fail: error => {
      23. uni.showModal({
      24. title: "提示",
      25. content: "检测到您没打开获取位置功能权限,是否去设置打开?",
      26. confirm: () => {
      27. this.openSettiog();
      28. }
      29. });
      30. }
      31. });
      32. }
      33. }
      34. });
      35. },
      36. // 打开位置设置权限
      37. openSettiog() {
      38. uni.openSetting({ // 调起客户端小程序设置界面,返回用户设置的操作结果
      39. success: res => {
      40. if (res.authSetting["scope.userLocation"]) {
      41. this.chooseLocation();
      42. } else {
      43. uni.showToast({
      44. title: "您拒绝了授权, 无法操作内容",
      45. icon: "none",
      46. duration: 2500
      47. });
      48. }
      49. }
      50. });
      51. },
      52. // 选择位置
      53. chooseLocation() {
      54. uni.chooseLocation({ // 打开地图选择位置
      55. success: res => {
      56. if (!res.address) return false;
      57. this.formData.address = res.address; // 详细地址
      58. this.latitude = res.latitude; // 纬度
      59. this.longitude = res.longitude; // 经度
      60. const masker = [
      61. {
      62. id: 1,
      63. latitude: res.latitude,
      64. longitude: res.longitude,
      65. iconPath: "/static/images/train/address.png",
      66. width: 20,
      67. height: 27
      68. }
      69. ];
      70. this.maskers = masker; // 将位置信息显示到页面地图中
      71. },
      72. fail: error => {
      73. uni.showToast({
      74. title: error,
      75. icon: "none",
      76. duration: 2500
      77. });
      78. }
      79. });
      80. },
      81. }
      82. </script>

    scope 列表