微信小程序-打开地图选择位置

  • Post author:
  • Post category:小程序


微信小程序地图自动定位位置:

方法步骤如下:

1.申请获取用户地址的权限;

2.打开地图选择;

3.由于获取到的地址是一串字符串,所以必须通过经纬度反查地址分隔省市县;(如不需要分隔可省略)获取之后自动填充到表单中。

在wxml中点击触发以下方法即可

getCenterLocation() {
    var that = this;
    wx.authorize({
      scope: 'scope.userLocation',
      complete: function (res) {
        console.log(res)
        wx.chooseLocation({
          success(str) {
            console.log(str)
            var key = 'V7DBZ-XXXX-XXXXX-XXXXX-XXXXX-AEFCM';
            //发送请求通过经纬度反查地址信息
            var getAddressUrl = "https://apis.map.qq.com/ws/geocoder/v1/?location=" + str.latitude + "," + str.longitude + "&key=" + key + "&get_poi=1";
            wx.request({
              url: getAddressUrl,
              success: function (result) {
                var province = result.data.result.address_component.province;
                var city = result.data.result.address_component.city;
                var district = result.data.result.address_component.district;
                var address = result.data.result.formatted_addresses.recommend;
                console.log('省市县:' + province + city + district)
                console.log('地址:' + address)
                that.setData({
                  "input[2].val": [province, city, district],
                  "input[3].val": address
                })
              }
            })
          }
        })
      }
    })

  },



版权声明:本文为ange2017原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。