前文
在小程序中的请求都是异步的请求,但是我们需要经常需要发送一个请求拿到一个结果才能去发下一个请求。就以我项目中遇到的问题进行记录,我需要先获取用户自己定位然后拿到用户自身定位的经纬度去发送请求计算距离商家的距离。uniapp使用vue2代码如下
export default{
data(){
page:1,//请求分页
pages:10,//请求分页
latitude:'',//纬度坐标
longitude:'',//经度坐标
provinceName: '', //存放转换来的省份
cityName: '', //存放转换来的城市
districtName: '', //存放转换来的区域
townshipName: '', //存放转换来的街道
useradress: '', //地址
},
async onLoad(){
//这个地方用的市Proimse 也可以用await
/* let res,
res=await this.usergetLocation()
this.longitude=res.longitude;
this.latitude=res.latitude;
this.getStores(res.latitude,res.longitude)
this.loadCity(res.longitude, res.latitude)
*/
this.usergetLocation().then(res=>{
this.longitude=res.longitude;
this.latitude=res.latitude;
this.getStores(res.latitude,res.longitude)
this.loadCity(res.longitude, res.latitude)
});
this.getArea();
},
methods:{
// 获取用户的定位
usergetLocation() {
return new Promise((resolve,reject)=>{
const _this = this
uni.getLocation({
type: 'wgs84',
geocode: true, //该参数是为了获取经纬度城市信息
success: function(res) {
// console.log('11111',res);
this.longitude = res.longitude;
this.latitude = res.latitude;
// console.log('当前位置的经度:' + this.longitude);
// console.log('当前位置的纬度:' + this.latitude);
resolve(res)
},
fail: function() {
uni.showToast({
title: '获取地址失败,请手动选择地址',
icon: 'none'
})
}
});
})
},
//经纬度转化为城市
loadCity(longitude, latitude) {
const _this = this;
// console.log(longitude, latitude);
uni.request({
header: {
'Content-Type': 'application/text',
},
//这里的key值需要高德地图web服务生成的key
url: 'https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=' +
longitude +
',' +
latitude +
'&key=' +
MAP_KEY +
'&radius=1000&extensions=all',
success(res) {
if (res.statusCode === 200) {
_this.provinceName = res.data.regeocode.addressComponent.province;
_this.cityName = res.data.regeocode.addressComponent.city;
_this.districtName = res.data.regeocode.addressComponent.district;
_this.townshipName = res.data.regeocode.addressComponent.township;
_this.useradress = `${_this.provinceName}-${_this.cityName}-${_this.districtName}`;
_this.areaVal = _this.useradress;
} else {
console.log('获取信息失败,请重试!')
}
}
})
},
// 获取门店列表
getStores(latitude, longitude) {
let that = this;
let params = {
id: this.$Route.query.id,
latitude: latitude,
longitude:longitude,
page:this.page
}
console.log('111', latitude,longitude);
this.shopID = this.$Route.query.id;
// console.log(params)
this.$http('store.keeplist', params).then(res => {
for(let i=0;i<res.data.data.length;i++){
this.StoresList.push(res.data.data[i]);
}
for (let i = 0; i < this.StoresList.length; i++) {
let obj = {
longitude: this.StoresList[i].longitude,
latitude: this.StoresList[i].latitude
};
this.Storecoordinate.push(obj);
}
}).catch(err => {
console.log(err) //代码错误、请求失败捕获
})
},
}