微信小程序实时获取用户经纬度( 附源码 )

怎甘沉沦 提交于 2019-11-29 05:51:10

注意,使用这个功能之前手机得先打开位置信息。

现在app.json配置

{
  "pages": [
    "pages/map/map",
    "pages/index/index",
    "pages/register/register",
    "pages/logs/logs"
  ],
  "window": {
    "backgroundTextStyle": "light",
    "navigationBarBackgroundColor": "#fff",
    "navigationBarTitleText": "WeChat",
    "navigationBarTextStyle": "black"
  },
  "permission": {
    "scope.userLocationBackground": {
      "desc": "位置信息将用于展示所在地区"
    }
  },
  "requiredBackgroundModes": ["location"],
  "sitemapLocation": "sitemap.json"
}

页面js代码

  getUserLocation() {
    wx.getSetting({
      success(res) {
        console.log(res)
        if (res.authSetting['scope.userLocationBackground']) {
          wx.startLocationUpdateBackground({
            success: (res) => {
              console.log('startLocationUpdate-res', res)
            },
            fail: (err) => {
              console.log('startLocationUpdate-err', err)
            }
          })
        } else {
          if (res.authSetting['scope.userLocation']==false) {
            console.log('打开设置页面去授权')
          } else {
            wx.startLocationUpdateBackground({
              success: (res) => {
                console.log('startLocationUpdate-res', res)
              },
              fail: (err) => {
                console.log('startLocationUpdate-err', err)
              }
            })
          }
        }
      }
    })
  },

然后在onShow 监听用户实时位置信息

 onShow() {
    this.getUserLocation();
    const _locationChangeFn = res=> {
      console.log('location change', res.latitude, res.longitude)
    }
    wx.onLocationChange(_locationChangeFn);
  },

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!