# 选择位置

调用官方位置选择界面并获取选定位置信息

效果如下:

image-20250326092819647

image-20250326092906856

# 1. 页面 WXML (index.wxml)

<view class="container">
  <button bindtap="chooseLocation" type="primary">选择位置</button>
  
  <view wx:if="{{location}}" class="location-info">
    <view>位置名称:{{location.name}}</view>
    <view>详细地址:{{location.address}}</view>
    <view>纬度:{{location.latitude}}</view>
    <view>经度:{{location.longitude}}</view>
  </view>
  
  <map 
    wx:if="{{location}}"
    longitude="{{location.longitude}}" 
    latitude="{{location.latitude}}" 
    scale="16"
    markers="{{markers}}"
    style="width: 100%; height: 300px; margin-top: 20px;">
  </map>
</view>

# 2. 页面 JS (index.js)

Page({
  data: {
    location: null,
    markers: []
  },

  // 选择位置
  chooseLocation() {
    const that = this;
    wx.chooseLocation({
      success(res) {
        console.log('选择的位置:', res);
        that.setData({
          location: res,
          markers: [{
            id: 0,
            latitude: res.latitude,
            longitude: res.longitude,
            title: res.name,
            iconPath: '/images/marker.png',
            width: 30,
            height: 30
          }]
        });
      },
      fail(err) {
        console.error('选择位置失败:', err);
        wx.showToast({
          title: '选择位置失败',
          icon: 'none'
        });
      }
    });
  }
});

# 3. 页面 WXSS (index.wxss)

.container {
  padding: 20px;
}

.location-info {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 5px;
}

.location-info view {
  margin-bottom: 8px;
  font-size: 14px;
}

# 4. 需要配置的权限

app.json 中确保已添加位置相关权限:

{
  "permission": {
    "scope.userLocation": {
      "desc": "你的位置信息将用于选择位置功能"
    }
  }
}

# 功能说明

  1. 点击按钮调用 wx.chooseLocation() 打开官方位置选择界面
  2. 选择位置后返回包含以下信息的对象:
    • name: 位置名称
    • address: 详细地址
    • latitude: 纬度
    • longitude: 经度
  3. 页面会显示选择的位置信息和地图标记

# 注意事项

  1. 需要用户授权位置权限
  2. 真机调试时才能获取真实位置信息
  3. 如果需要使用地图组件,需要在 app.json 中配置 requiredPrivateInfos
{
  "requiredPrivateInfos": ["chooseLocation", "getLocation"]
}

如果需要更复杂的地图功能,可以考虑使用微信小程序的 <map> 组件或腾讯位置服务 SDK。