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

时间:2024-04-13 07:35:49

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

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

 

方法步骤如下:

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-K7C22-SXXUJ-CDUE7-AM2LH-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
                })
              }
            })
          }
        })
      }
    })

  },