微信小程序获取地理位置 - 新闻资讯 - 云南小程序开发|云南软件开发|云南网站建设-昆明葵宇信息科技有限公司

159-8711-8523

云南网建设/小程序开发/软件开发

知识

不管是网站,软件还是小程序,都要直接或间接能为您产生价值,我们在追求其视觉表现的同时,更侧重于功能的便捷,营销的便利,运营的高效,让网站成为营销工具,让软件能切实提升企业内部管理水平和效率。优秀的程序为后期升级提供便捷的支持!

您当前位置>首页 » 新闻资讯 » 小程序相关 >

微信小程序获取地理位置

发表时间:2020-10-19

发布人:葵宇科技

浏览次数:69

1.页面配置

在app.json中配置
  "permission": {
    "scope.userLocation": {
      "desc": "你的位置信息将用于小程序位置接口的效果展示"
    }
  }

2.使用wx.getLocation()

  wx.getLocation({
      success(res) {
        console.log('开启后台定位', res)
      },
      fail(res) {
        console.log('开启后台定位失败', res)
      }
    })

3.考虑用户不授权,下次还能呼唤起授权页面

使用wx.getSetting()获取用户的当前设置。返回值中只会出现小程序已经向用户请求过的权限。
使用wx.openSetting()调起客户端小程序设置界面,返回用户设置的操作结果。设置界面只会出现小程序已经向用户请求过的权限。

  wx.getLocation({
      success(res) {
        console.log('开启后台定位', res)
      },
      fail(res) {
        console.log('开启后台定位失败', res)
        authorize ()
      }
    })
    const authorize = () => wx.getSetting({
      success(res) {
        // console.log(res, 'res');
        let statu = res.authSetting
        console.log(statu['scope.userLocation'], 'statu')
        if (!statu['scope.userLocation']) {
          wx.showModal({
            title: '是否授权当前位置',
            content: '需要获取您的地理位置,请确认授权,否则地图功能将无法使用',
            success(tip) {
              if (tip.confirm) {
                wx.openSetting({
                  success(data) {
                    if (data.authSetting['scope.userLocation'] === true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  },
                  fail() {
                    wx.showToast({
                      title: '授权失败',
                      icon: 'none',
                      duration: 1000
                    })
                  }
                })
              }
            }
          })
        }
      },
      fail(err) {
        wx.showToast({
          title: '调用授权窗口失败',
          icon: 'none',
          duration: 1000
        })
      }
    })

相关案例查看更多