微信小程序定位、逆地理编码

毕竟都是腾讯的,所以用了腾讯家的腾讯位置服务。


address_reference

"address_component":{
            "nation":"中国",
            "province":"广东省",
            "city":"深圳市",
            "district":"南山区",
            "street":"桃园路",
            "street_number":"桃园路2号"
        },
"address_reference":{
  "town": {"id": "xxxx", "title":"xxxx",,,}
}

打开 产品->位置服务


位置服务
根据官方文档配置key;

注意小程序需要勾选WebServiceAPI;如果选的校验方式为域名白名单,需要填写白名单:servicewechat.com

腾讯位置服务key设置
此外,还需在小程序中配置权限

在app.json配置文件中,添加如下配置

"permission": {
    "scope.userLocation": {
      "desc": "获取您的位置信息方便您使用编辑地址功能"
    }
  }
核心代码:
var QQMapWX = require('../../libs/qqmap-wx-jssdk.js');
var qqmapsdk;
Page({
 onLoad: function () {
        // 实例化API核心类
        qqmapsdk = new QQMapWX({
            key: '申请的key'
        });
    },
})
// 微信获得经纬度
  getLocation: function () {
    let that = this;
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        console.log(JSON.stringify(res))
        var latitude = res.latitude
        var longitude = res.longitude
        that.qqmapRegeoCityInfo(longitude, latitude)
      },
      fail: function (res) {
        console.log('fail' + JSON.stringify(res))
      }
    })
  },

type必须用 gcj02。绝对不要用 wgs84(GPS),否则不止导致坐标系偏差,而且会出现无法解释的错误:定位点不在地图中心!


  qqmapRegeoCityInfo: function(longitude, latitude) {
    let location = latitude + ',' + longitude
    let that = this
    qqmapsdk.reverseGeocoder({
      //获取表单传入地址
      location: location, //地址参数,例:固定地址,address: '北京市海淀区彩和坊路海淀西大街74号'
      success: function (res) {//成功后的回调
        console.log(res)
        if (res.status == 0 && res.result) {
          that.qqmapParseCityInfo(res.result)
        }
      },
      fail: function (error) {
        console.error(error);
      },
      complete: function (res) {
        console.log(res);
      }
    })
  },

  // 腾讯地图sdk
  qqmapParseCityInfo: function(result) {
    if (result.address_component) {
      this.globalData.address_component = result.address_component
      if (result.address_reference) {
        // 街道办
        this.globalData.township = result.address_reference.town.title
      }
      if (this.didGetAddressComponent) {
        this.didGetAddressComponent("qqmap", result.address_component, this.globalData.township)
      }
    }
  },

你可能感兴趣的:(微信小程序定位、逆地理编码)