微信小程序獲取當前位置
檢查用戶是否有
已授權
。當用戶已操作授權
的,直接調用獲取當前位置
方法。項目中需求:
獲取當前位置
後, 把經緯度
發送給後端,由於展示位置相關信息
的頁面是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"