微信小程序用户通过地址选择当前位置信息

1、小程序后台(开发管理->接口设置)开通:wx.chooseLocation、wx.getLocation

2、代码实现:

app.json添加以下代码

"requiredPrivateInfos": [
        "chooseLocation",
        "getLocation"
      ]

 

.wxml添加一个按钮

 <view bind:tap="chooseLocation">选择<van-icon name="search" /></view>

.js文件添加事件

 //#region 获取位置信息
    chooseLocation() {
        wx.chooseLocation({
          success: (res) => {
            // 成功选择位置后,res对象包含位置信息
            console.log('位置名称:', res.name);
            console.log('详细地址:', res.address);
            console.log('纬度:', res.latitude);
            console.log('经度:', res.longitude);
            
            // 这里可以将获取到的信息设置到页面数据中,更新UI
            this.setData({
              IsLocation: true,
              Location: JSON.stringify(res),
              LocationStr: res.address
            });
          },
          fail: (err) => {
            console.error('选点失败:', err);
            // 处理失败情况,例如用户拒绝授权或取消操作
            if (err.errMsg.indexOf('auth deny') !== -1) {
              wx.showToast({ 
                title: '需要您授权位置信息才能选点', 
                icon: 'none' 
              });
            } else if (err.errMsg.indexOf('cancel') !== -1) {
              // 用户取消是正常行为,可不必提示
            } else {
              wx.showToast({ 
                title: '选点失败,请重试', 
                icon: 'none' 
              });
            }
          }
        })
      },
    //#endregion

 

posted @ 2025-11-27 16:29  ziff123  阅读(8)  评论(0)    收藏  举报