微信小程序獲取及選擇位置
- 獲取當前的地理位置、速度
wx.getLocation({
type: "wgs84", //wgs84 返回 gps 坐標,gcj02 返回可用於 wx.openLocation 的坐標 gcj02在android機上有bug,無法選擇位置
success(res) {
}
});
- 打開地圖選擇位置
wx.chooseLocation({
success(res) {
let name = res.name; //名稱
let address = res.address; //詳細地址
let longitude = res.longitude;//經度
let latitude = res.latitude;//緯度
fail: function(info){
//失敗回調
console.log(info)
}
})
}
});
- 使用微信內置地圖查看位置
openLocation(item){
let longitude = item.longitude;
let latitude = item.latitude;
wx.openLocation({
latitude,
longitude,
scale: 18
});
},
逆地址解析(根據經緯度坐標獲取城市省份信息)
微信小程序位置api並沒有提供獲取省份城市的信息,這里使用高德第三方地圖來獲取省份城市
-
申請高德key
-
將https://restapi.amap.com添加到微信小程序合法域名里面
-
下載高德微信小程序sdk
https://lbs.amap.com/api/wx/download
高德微信小程序sdk文檔說明
https://lbs.amap.com/api/wx/reference/core
- 在vue文件中引入
import amapFile from "../../../../../static/sdk/amap-wx";
- 初始化地圖及獲取省份城市信息
mounted() {
this.initMap();
},
initMap(){
this.myAmapFun = new amapFile.AMapWX({key:'app key'});
},
that.myAmapFun.getRegeo({
location:`${longitude},${latitude}`,
success: function(data){
let province = data[0].regeocodeData.addressComponent.province;
let city = data[0].regeocodeData.addressComponent.city;
// city:[]
if(Object.prototype.toString.call(city)=="[object Array]"){
city = city.join('');
}
that.province = province;
that.city = city;
},
fail: function(info){
//失敗回調
console.log(info)
}
})
返回參數說明
https://lbs.amap.com/api/webservice/guide/api/georegeo/#regeo
進入小程序讓只初始化一次
- 在main.js中引入並初始化
import amapFile from'../static/sdk/amap-wx';
//將其綁定到vue原型上 //使用 this.$myAmapFun訪問
let myAmapFun = new amapFile.AMapWX({ key: 'app key' });
Vue.prototype.$myAmapFun = myAmapFun
- vue組件中使用高德地圖
that.$myAmapFun.getRegeo({
location:`${longitude},${latitude}`,
success: function(data){
let province = data[0].regeocodeData.addressComponent.province;
let city = data[0].regeocodeData.addressComponent.city;
// city:[]
if(Object.prototype.toString.call(city)=="[object Array]"){
city = city.join('');
}
that.province = province;
that.city = city;
},
fail: function(info){
//失敗回調
console.log(info)
}
})