vue实现考勤定位功能
获取用户地理位置
使用浏览器的Geolocation API获取用户当前位置坐标。Vue中可通过navigator.geolocation实现:
methods: {
getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
position => {
this.latitude = position.coords.latitude;
this.longitude = position.coords.longitude;
},
error => {
console.error("获取位置失败:", error);
}
);
} else {
alert("浏览器不支持地理定位");
}
}
}
地理位置权限处理
在created生命周期中请求定位权限,并处理用户拒绝的情况:
created() {
this.getLocation();
},
data() {
return {
latitude: null,
longitude: null,
permissionDenied: false
}
}
显示定位结果
在模板中显示获取到的坐标信息:
<template>
<div>
<p v-if="latitude">纬度: {{ latitude }}</p>
<p v-if="longitude">经度: {{ longitude }}</p>
<p v-if="permissionDenied">位置权限被拒绝</p>
</div>
</template>
定时更新位置
对于需要持续跟踪的场景,使用watchPosition方法:
methods: {
startTracking() {
this.watchId = navigator.geolocation.watchPosition(
position => {
this.latitude = position.coords.latitude;
this.longitude = position.coords.longitude;
},
error => {
console.error("跟踪位置失败:", error);
}
);
},
stopTracking() {
navigator.geolocation.clearWatch(this.watchId);
}
}
考勤范围判定
计算当前位置与考勤点的距离,判断是否在有效范围内:
methods: {
calculateDistance(lat1, lon1, lat2, lon2) {
const R = 6371; // 地球半径(km)
const dLat = (lat2 - lat1) * Math.PI / 180;
const dLon = (lon2 - lon1) * Math.PI / 180;
const a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1 * Math.PI / 180) *
Math.cos(lat2 * Math.PI / 180) *
Math.sin(dLon/2) * Math.sin(dLon/2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
return R * c * 1000; // 转换为米
},
checkInRange() {
const distance = this.calculateDistance(
this.latitude,
this.longitude,
公司纬度,
公司经度
);
return distance <= 允许范围米数;
}
}
异常处理增强
增加定位超时和精度控制:
navigator.geolocation.getCurrentPosition(
successCallback,
errorCallback,
{
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
}
);
定位结果存储
将考勤记录提交到后端:
methods: {
submitAttendance() {
axios.post('/api/attendance', {
latitude: this.latitude,
longitude: this.longitude,
timestamp: new Date(),
inRange: this.checkInRange()
}).then(response => {
// 处理成功响应
}).catch(error => {
// 处理错误
});
}
}
地图可视化集成
使用地图库(如高德/百度地图)显示位置:
import AMap from 'AMap';
mounted() {
this.map = new AMap.Map('map-container', {
zoom: 16
});
this.marker = new AMap.Marker({
map: this.map
});
},
methods: {
updateMapPosition() {
this.marker.setPosition([this.longitude, this.latitude]);
this.map.setCenter([this.longitude, this.latitude]);
}
}
设备兼容性处理
针对不同平台做兼容处理:
methods: {
getLocation() {
// 微信环境
if (window.wx && wx.getLocation) {
wx.getLocation({
type: 'wgs84',
success: res => {
this.latitude = res.latitude;
this.longitude = res.longitude;
}
});
}
// 普通浏览器
else if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
// ...普通浏览器处理
);
}
}
}






