uniapp利用定位获取两个位置并对结果进行升序排序
·
在前台的项目编写中少不了用到定位,当需要展示当前位置与另一个位置的距离时就需要用到定位,还需要对两个位置的经纬度进行换算。下面开始展示代码
效果图:

核心代码:
import {reactive,ref} from 'vue'
const newAddress=reactive([])//获取用户的经纬度
const latitude=ref(0)//获取当前定位信息经度
const longitude =ref(0)//获取当前定位信息纬度
onReady(()=>{
// 获取发布信息的经纬度
for(let i=0;i<store.dataStr[0].length;i++){
uni.request({
url: 'https://restapi.amap.com/v3/geocode/geo?parameters',
method:'GET',
data: {
key:'您的key',
address:‘您的地址数据’
},
success: (res) => {
let jd = res.data.geocodes[0].location.split(',')[0]
let wd = res.data.geocodes[0].location.split(',')[1]
// 调用上述函数计算距离
getDistanceByLine(latitude.value,parseFloat(jd), longitude.value, parseFloat(wd),store.dataStr[0][i].id,store.dataStr[0][i].address,store.dataStr[0][i].nickname,store.dataStr[0][i].age,store.dataStr[0][i].profileSrc)
},
})
}
})
/ 定义地球上每1度对应的公里数
const EARTH_RADIUS = 6378.14; // 单位为千米
function getDistanceByLine(latitude1, longitude1, latitude2, longitude2 ,id ,address ,nickname ,age ,profileSrc) {
const radLat1 = toRadians(latitude1);
const radLon1 = toRadians(longitude1);
const radLat2 = toRadians(latitude2);
const radLon2 = toRadians(longitude2);
const a = Math.sin((radLat2 - radLat1) / 2) * Math.sin((radLat2 - radLat1) / 2) +
Math.cos(radLat1) * Math.cos(radLat2) *
Math.sin((radLon2 - radLon1) / 2) * Math.sin((radLon2 - radLon1) / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
const distanceInKilometers = EARTH_RADIUS * c ;
//把结果push到数组中
newAddress.push({
id:id,
address:address,
AddressNum:parseInt(distanceInKilometers),
nickname:nickname,
age:age,
profileSrc:profileSrc
})
// 对输出结果进行排序,最小的排在最前面
newAddress.sort(function(a,b){
return a.AddressNum-b.AddressNum
})
}
//转换成圆弧
function toRadians(degrees) {
return (degrees * Math.PI) / 180;
}
更多推荐
所有评论(0)