<template>
<view class="content">
<view>经度:{{this.longitude}}</view>
<view>纬度:{{latitude}}</view>
<view>名称:{{pocationName}}</view>
<view>距离:{{s}}</view>
</view>
</template>
<script>
export default {
data() {
return {
longitude:'',
latitude:'',
pocationName:'',
s:'',
}
},
onLoad() {
this.getLocation()
this.distance(39.901403,116.406243,30.53599,104.096219)
},
methods: {
getLocation(){
let this_=this
uni.getLocation({
type: 'gcj02', //返回可以用于uni.openLocation的经纬度
success:(res)=>{
this_.latitude = res.latitude;
this_.longitude = res.longitude;
console.log(res)
uni.request({
header:{
"Content-Type": "application/text"
},
//注意:这里的key值需要高德地图的 web服务生成的key 只有web服务才有逆地理编码
url:'https://restapi.amap.com/v3/geocode/regeo?output=JSON&location='+res.longitude+','+res.latitude+'&key=地图密钥',
success(re) {
console.log(re,11111)
if(re.statusCode===200){
this_.pocationName=re.data.regeocode.formatted_address
}else{
console.log("获取信息失败,请重试!")
}
}
});
}
});
},
//1当前位置 2目标位置
distance(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;
if (s < 1) {
this.s = s * 1000 + 'm'
} else {
this.s = s + 'm'
}
},
}
}
</script>
uni获取当前定位和计算距离
于 2021-07-30 15:50:18 首次发布
该博客展示了一个uni-app小程序中获取用户经度和纬度的示例,并利用高德地图API进行逆地理编码获取位置名称。同时,实现了计算当前位置与指定坐标之间的距离功能,结果以米为单位。在onLoad函数中调用了getLocation和distance方法,确保页面加载时获取并显示相关信息。
1万+

被折叠的 条评论
为什么被折叠?



