uni.getLocation(OBJECT)
获取当前的地理位置、速度。
1.首先在uniapp中的manifest.json配置文件开启获取位置权限来获取当前位置
2.代码块部分
<template>
<view v-for="(item,index) in dataList" :key='index'>{{item.jl}}</view>
</template>
<script>
import {index} from '@/api/index.js' //(要根据根本后端来反馈--虚拟的接口)
export default {
data() {
return {
dataList:[],
location: {
lat: 0,
lng: 0,
},
}
},
mounted() {
//#ifdef MP-WEIXIN
this.initPage()
// #endif
//#ifndef MP-WEIXIN
this.getList()
// #endif
},
methods:{
//发送请求获取你要得到那个地方的经度纬度(要根据根本后端来反馈--虚拟的接口)
getList(){
index().then(res=>{
this.dataList = res.rows
this.dataList.forEach(item => {
var s = this.distance(item.location.split(',')[1], item.location.split(',')[0]) //调用计算方法(经度,纬度)传值
this.$set(item, 'jl', s) //把距离存储到dataList中
})
})
},
//获取当前位置
getLocation() {
let location = {
lat: 0,
lng: 0,
}
return new Promise((reserve, reject) => { //因为获取位置是异步接口所以需要使用promise
uni.getLocation({
success(res) {
location.lat = res.latitude
location.lng = res.longitude,
reserve(location);
console.log(res.latitude,res.longitude)
},
fail(err) {
reject(location); //获取失败则返回经纬坐标为0
}
})
})
},
//根据金纬度计算距离
distance(lat1, lng1) {
var that = this;
let lat2 = that.location.lat;
let lng2 = that.location.lng;
let rad1 = lat1 * Math.PI / 180.0;
let rad2 = lat2 * Math.PI / 180.0;
let a = rad1 - rad2;
let b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) *
Math.cos(
rad2) * Math.pow(
Math.sin(b / 2), 2)));
s = s * 6378.137;
s = Math.round(s * 10000) / 10000;
s = s.toString();
s = s.substring(0, s.indexOf('.') + 2);
return s
},
initPage: async function() {
this.location = await this.getLocation()
this.getList()
}
},
}
</script>