微信小程序开发代码集

微信小程序获取定位

在微信小程序中获取用户的定位,可以使用小程序提供的wx.getLocation() API。该API将请求用户授权并返回用户的地理位置信息。

以下是获取定位的基本代码示例:

// 请求用户授权获取地理位置
wx.authorize({
  scope: 'scope.userLocation',
  success() {
    // 成功授权后获取地理位置信息
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        const latitude = res.latitude // 纬度
        const longitude = res.longitude // 经度
        console.log(latitude, longitude)
      }
    })
  },
  fail() {
    // 用户拒绝授权时提示
    wx.showToast({
      title: '请允许获取您的地理位置',
      icon: 'none'
    })
  }
})

需要注意的是,在小程序中获取用户地理位置需要用户授权。如果用户拒绝授权或未开启定位服务,则无法获取到地理位置信息。