微信小程序 - 获取用户地理位置、地址解析及逆地址解析

6,239 阅读2分钟

需求背景

小程序需要用户授权获取用户位置,获取到经纬度请求数据列表并解析为城市地址,用户选择城市时把城市解析为经纬度。

代码实现(项目基于 Taro+react )

1.获取用户授权 (微信小程序文档-指南-开放能力-用户信息-授权)

小程序授权类接口调用时:

  1. 如果用户未接受或拒绝过此权限,会弹窗询问。
  2. 如果用户已授权,可直接调用接口。
  3. 如果用户已拒绝授权,则不会出现弹窗,而是直接进入接口fail回调。
export default {
pages: [
  'pages/index/index',
],
permission: {
  "scope.userLocation": {
    "desc": "是否允许获取你当前的地理位置信息?"
  }
},
}

效果:

2.获取用户位置经纬度

api介绍:

  • wx.getSetting(): 获取用户当前的授权状态
  • wx.getLocation(): 获取当前的地理位置、速度。当用户离开小程序后,此接口无法调用。
// 判断用户当前授权状态
getCurrentLocation = () => {
   const vm = this;
   // 判断用户是否授权获取地理位置
   wx.getSetting({
     success: (res) => {
       // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
       // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
       // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
       if (
         res.authSetting["scope.userLocation"] != undefined &&
         res.authSetting["scope.userLocation"] == false
       ) {
         // 非第一次进入页面且未授权,可根据需求在此处做操作
         
       } else {
        // 获取用户位置经纬度
         vm.getLocation();
       }
     },
   })
 }
 // 获取用户位置
 getLocation() {
   const that = this;
   wx.getLocation({
     type: "gcj02",
     success(res) {
     // res包含用户位置经纬度、speed等
       const latitude = res.latitude;
       const longitude = res.longitude;
       that.setState({
         latitude,
         longitude,
       });
     },
     fail(res) {
       // 用户未给定位权限,打开城市选择器
       // 实践中发现安卓和苹果此处错误信息不同
       if (
         res.errMsg == "getLocation:fail auth deny" ||
         res.errMsg == "getLocation:fail:auth denied"
       ) {
          that.setState({
           areaOpened: true,
         });
       }
     },
   });
 }

3.将获取经纬度信息解析为具体城市地址

借助腾讯地图逆地址解析接口,申请一个腾讯地图的key,传入经纬度即可。

var accessKey = 'xxxxx自己申请一个腾讯地图的key'
var qqMapApi =
         "https://apis.map.qq.com/ws/geocoder/v1/" +
         "?location=" +
         latitude +
         "," +
         longitude +
         "&key=" +
         accessKey +
         "&get_poi=1";
wx.request({
     url: qqMapApi,
     header: {
       "Content-Type": "application/json",
     },
     data: {},
     method: "GET",
     success: (res) => {
       if (res.statusCode == 200 && res.data.status == 0) {
         // 从返回值中提取需要的业务地理信息数据 国家、省、市、县区、街
         that.setAddress(res.data.result.address_component);
       }
     },
     fail: () => {
       wx.showToast({
         title: "地址解析失败",
         icon: "none",
       })
     },
   })

4.用户选择城市时需要将城市解析为经纬度

借助腾讯地图地址解析接口

var accessKey = 'xxxxx自己申请一个腾讯地图的key'
var qqMapApi =
      "https://apis.map.qq.com/ws/geocoder/v1/?address=" +
      provinceName +
      cityName +
      countyName +
      "&key=" +
      accessKey;
wx.request({
    url: qqMapApi,
    header: {
      "Content-Type": "application/json",
    },
    data: {},
    method: "GET",
    success: (res) => {
      if (res.statusCode == 200 && res.data.status == 0) {
        that.setState({
          longitude: res.data.result.location.lng,
          latitude: res.data.result.location.lat,
        });
      }
    },
    fail: (res) => {
      wx.hideToast();
      wx.showToast({
        title: "地址解析失败",
        icon: "none",
      });
    },
  });

5.用户拒绝授权后,手动打开设置授权界面

用户可以在小程序设置界面(「右上角」 - 「关于」 - 「右上角」 - 「设置」)中控制对该小程序的授权状态。

开发者可以调用 wx.openSetting 打开设置界面,引导用户开启授权。

wx.openSetting({
    success(res) {
      if (res.authSetting["scope.userLocation"]) {
        // 已授权
      } else {
        // 未授权
      }
    },
  });

调用后可打开: