關於獲取用戶當前位置,微信官方文檔使用wx.getLocation()來讓用戶授權位置信息
wx.getLocation({
type: 'wgs84',//默認爲 wgs84 返回 gps 座標,gcj02 返回可用於wx.openLocation的座標
success: function(res) {
var latitude = res.latitude
var longitude = res.longitude
console.log(res)
}
})
得到輸出的結果
這時候需要將地理座標信息轉化爲具體中文位置
騰訊官方給出了針對小程序地圖位置信息的JavaScript SDK
http://lbs.qq.com/qqmap_wx_jssdk/index.html
第一步,申請密鑰
第二步,通過 逆地址解析 ,就可以實現地理位置的中文轉換。
最終輸出結果
js代碼
// 引入SDK核心類
var QQMapWX = require('../../tools/qqmap-wx-jssdk.min.js');
// 實例化API核心類
var demo = new QQMapWX({
key: '開發者密鑰' // 必填
});
Page({
data: {
localCity: ""//本地城市
}
/**
* 生命週期函數--監聽頁面加載
*/
onLoad: function (options) {
let that = this;
// 調用接口
wx.getLocation({
type: 'wgs84',
success: function (res) {
var latitude = res.latitude//緯度
var longitude = res.longitude//經度
demo.reverseGeocoder({
location: {
latitude: latitude,
longitude: longitude
},
success: function (res) {
console.log(res);
let province = res.result.address_component.province;//省份
let city = res.result.address_component.city;//城市
that.setData({
localCity: city
})
},
fail: function (res) {
console.log(res);
}
});
}
})
}
})