微信小程序获取当前位置
检查用户是否有
已授权
。当用户已操作授权
的,直接调用获取当前位置
方法。项目中需求:
获取当前位置
后, 把经纬度
发送给后端,由于展示位置相关信息
的页面是vue的
, 这里应用到微信小程序跳转h5方法可
直接使用代码
, 有所不足.欢迎大神指教。
效果图
相关API
获取用户当前设置
如用户
没有授权
情况,用户发生点击行为后会弹窗询问
,点击允许
成功回调中获取当前位置
。当用户点击
拒绝
后, 下次用户再发生点击行为后直接调起客户端设置界面
,用户设置操作
。【也可以用弹窗方式询问用户再调起客户端界面
, 各所需】
/**
* 授权打开定位
*/
ruleLocation: function() {
var that = this;
//检查地理位置授权
wx.getSetting({
success: (res) => {
if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
console.log('location', res);
// 调起客户端设置界面
wx.openSetting({
success: function(data) {
if (data.authSetting["scope.userLocation"] == true) {
// wx.showToast({
// title: '授权成功',
// icon: 'success',
// duration: 5000
// })
that.getLocation();
} else {
// wx.showToast({
// title: '授权失败',
// icon: 'success',
// duration: 5000
// })
}
}
})
} else {
that.getLocation();
}
}
})
},
获取当前位置经纬度
/**
* 调用wx.getLocation系统API,获取并设置当前位置经纬度
*/
getLocation: function() {
var that = this;
//获取位置
wx.getLocation({
type: 'gcj02', //默认为 wgs84 返回 gps 座标,gcj02 返回可用于wx.openLocation的座标
success: function(res) {
//console.log(res.longitude+'~~~'+res.latitude);
that.setData({
lng: res.longitude,
lat: res.latitude
})
// 处理业务逻辑 (把当前经纬度发送给后端处理等)
//这里: 跳转h5页面
wx.navigateTo({
url: '/pages/out/out?lng='+that.data.lng+'&lat='+that.data.lat,
})
},
fail: function(e) {
console.log("error", e);
}
});
},
注意:
这时,如果直接运行代码会提示需声明
permission
字段。那就按照提示操作吧~~~
提示操作
声明字段
在
app.json
中声明permission
字段, 如下
"permission": {
"scope.userLocation": {
"desc": "需要获取您的地理位置,请确认授权,否则地图定位功能将无法使用"
}
},
"sitemapLocation": "sitemap.json"