前端vue地图定位并测算当前定位离目标位置距离, 下载完整代码请访问uni-app插件市场地址: https://ext.dcloud.net.cn/plugin?id=12974
效果图如下:
#
#### 使用方法
```使用方法
```
#### HTML代码部分
```html
{{"去清远古龙峡漂流"}}
{{'距离活动地10km内可签到成功'}}
```
#### JS代码 (引入组件 填充数据)
```javascript
import Vue from 'vue'
export default {
data() {
return {
// 覆盖物
covers: [],
// 目标经纬度信息
infoDict: {
'lon': '113.17',
'lat': '23.8'
},
// 我的定位经纬度信息
myPinInfo: {},
// 默认距离为负数
distance: -9999,
distanceStr: ''
}
},
onShow() {
// 获取当前位置
this.getlocation();
},
methods: {
getlocation() {
let myThis = this;
console.log('获取位置开始');
uni.getLocation({
type: 'gcj02',
success: function(res) {
myThis.myPinInfo = res;
console.log('当前位置的经度:' + res.longitude);
console.log('当前位置的纬度:' + res.latitude);
myThis.covers = [{
latitude: myThis.infoDict.lat,
longitude: myThis.infoDict.lon,
width: 30,
height: 30,
id: 20000,
iconPath: '../../static/activity_pin.png'
},
{
latitude: myThis.myPinInfo.latitude,
longitude: myThis.myPinInfo.longitude,
width: 30,
height: 30,
id: 20001,
iconPath: '../../static/people_pin.png'
}
];
myThis.distance = myThis.getDistance(myThis.infoDict.lat, myThis.infoDict.lon, myThis
.myPinInfo.latitude, myThis.myPinInfo.longitude)
myThis.distanceStr = '(当前距离' + myThis.distance + '米)';
}
});
},
// 计算两点距离
getDistance(lat1, lng1, lat2, lng2) {
let EARTH_RADIUS = 6378.137;
let radLat1 = this.rad(lat1);
let radLat2 = this.rad(lat2);
let a = radLat1 - radLat2;
let b = this.rad(lng1) - this.rad(lng2);
let 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 * EARTH_RADIUS;
//s = Math.round(s * 10000d) / 10000d;
s = Math.round(s * 10000) / 10000;
s = s * 1000; //乘以1000是换算成米
return s;
},
// 弧度计算
rad(d) {
return d * Math.PI / 180.0;
},
// 立即签到
goSignIn(e) {
if (this.distance > 10000) {
uni.showModal({
title: '温馨提示',
content: '您的当前位置距离活动目的地太远, 无法签到',
showCancel: false
})
return;
} else if (this.distance < 0) {
uni.showModal({
title: '温馨提示',
content: '您的定位权限未打开, 请点击小程序右上角···菜单按钮, 然后点击设置,打开定位权限',
showCancel: false
})
return
}
},
}
}
```
#### CSS
```CSS
.content {
display: flex;
flex-direction: column;
height: 100%;
}
.scrollV {
width: 100vw;
}
.mapV {
width: calc(100vw);
height: 320px;
margin-top: 14px;
}
.leftTitle {
width: 284px;
height: 44px;
line-height: 44px;
font-size: 14px;
color: #333333;
}
.inputView {
flex-direction: row;
display: flex;
height: auto;
align-items: center;
margin-left: 13px;
width: calc(100vw - 30px);
padding: 2px 0px;
font-size: 13px;
color: #666666;
}
.btnview {
display: flex;
background-color: #FF731E;
justify-content: center;
align-items: center;
color: #ffffff;
width: 100%;
height: 50px;
margin-top: 20px;
}
```