思路:1. 通过获取地理位置 uni.getLocation({ success(res) {
// 把这个获取地理位置成功回调里面的 当前经纬度数据保存到this.position
that.position = res }
})
2. 把后端接口返回的经纬度数据通过实参保存到enhance方法:
that.enhance(res.data);//把数据传给enhance获取经纬度的方法
3. 定义的enhance方法调用封装经纬度的方法
that.getDistance(d.latitude, d.longitude, address.latitude, address.longitude)
把 uni.getLocation的经纬度和后端传过来的经纬度数据赋值给 d.distance字段 ,
stores.vue:
<!-- 查询出来的数据 -->
<block v-for="(item,index) in QueryList" :key="index"><navigator :url="'/filepage/storesdetails/storesdetails?cid=' + item.id + '&name=' + item.name">
<view class="query">
<view style="padding: 10px;"><uni-row class="demo-uni-row">
<uni-col :span="21">
<uni-title type="h3" class="title" :title="item.name"> </uni-title>
</uni-col>
<uni-col :span="3">
<view style="padding-top: 10px;">
<uni-icons type="forward" size="20"></uni-icons>
</view>
</uni-col>
</uni-row>
<uni-row class="demo-uni-row">
<uni-col :span="24">
<view class="yinye">{{item.businessHours}}</view>
</uni-col>
</uni-row><uni-row class="demo-uni-row">
<view class="rosered">
<uni-col :span="2">
<image src="../../static/imges/icon_dingwei.png" style="height: 40rpx;width: 20px;">
</image>
</uni-col>
<uni-col :span="5">
<text>{{item.distance == null ? "-" : item.distance}}km</text>
</uni-col>
<uni-col :span="17">
<view>{{item.address}}</view>
</uni-col>
</view>
</uni-row>
</view>
</view>
</navigator>
</block>
script:
export default {
data() {
return {
value: ' ',
name: ' ',
QueryList: [ ],
// 拒绝授权就显示
Toauthorize: false,
position: { },
}
},
methods: {
/**
* lat1 维度 lng1 经度
* lat2 维度 lng2 经度
*/封装经纬度方法来获取当前位置离要去的位置有多远:
getDistance(lat1, lng1, lat2, lng2) {
var radLat1 = (lat1 * Math.PI) / 180.0;
var radLat2 = (lat2 * Math.PI) / 180.0;
var a = radLat1 - radLat2;
var b = (lng1 * Math.PI) / 180.0 - (lng2 * Math.PI) / 180.0;
var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math
.pow(Math.sin(b / 2), 2)));
s = s * 6378.137; // EARTH_RADIUS;
s = Math.round(s * 10000) / 10000;
return (Math.round(s * 100) / 100);
},// 获取的当前经纬度数据和api接口返回的后端经纬度数据 直接赋值给到d.distance
//d.distance是一个json对象,你写了,如果json对象里面有字段,就替换,如果没有就写入
enhance(data){
const that = this;
var address = that.position;
for (var i in data) {
var d = data[i]
if (address != '') {
d.distance = that.getDistance(d.latitude, d.longitude, address.latitude, address.longitude)
}
}
return data;
},//调用后端接口 // 下拉框改变事件
async getQuery(e) {
// console.log(e)
var that = this;
this.value = e;
const res = await this.$myRuquest({
url: '/api/Home/QueryShops',data: {
cid: e,
name: this.name
},
})
// console.log( that.value)
this.QueryList = that.enhance(res.data);//把数据传给enhance获取经纬度的方法
if (res.code !== 200) {
return uni.$showMsg('请求数据失败', 2000)
}
},// 获取地理位置
getLocationInfo() {
var that = this;
uni.getLocation({
type: 'wgs84',
success(res) {
// 把这个当前经纬度地址保存到this.position
that.position = res
console.log(res)
uni.openSetting(); // 打开地图权限设置
}
});
},}