vue实现定位打卡
Vue实现定位打卡功能
依赖准备
安装vue-baidu-map或vue2-google-maps等地图库,根据项目需求选择
npm install vue-baidu-map --save
# 或
npm install vue2-google-maps
百度地图实现方案 在main.js中初始化地图组件
import BaiduMap from 'vue-baidu-map'
Vue.use(BaiduMap, {
ak: 'YOUR_BAIDU_MAP_API_KEY'
})
组件实现 创建打卡组件Geolocation.vue
<template>
<baidu-map class="map" :center="center" :zoom="zoom" @ready="handler">
<bm-geolocation
:auto-location="true"
@locationSuccess="getLocation"
@locationError="locationError"
></bm-geolocation>
<bm-marker :position="markerPoint"></bm-marker>
</baidu-map>
</template>
<script>
export default {
data() {
return {
center: {lng: 116.404, lat: 39.915},
zoom: 15,
markerPoint: {lng: 0, lat: 0}
}
},
methods: {
handler({BMap, map}) {
this.BMap = BMap
this.map = map
},
getLocation(point) {
this.markerPoint = point.point
this.center = point.point
// 可以在此处提交位置信息到后端
console.log('当前位置:', point.point)
},
locationError(error) {
console.error('定位失败:', error)
}
}
}
</script>
谷歌地图实现方案 配置谷歌地图API
import * as VueGoogleMaps from 'vue2-google-maps'
Vue.use(VueGoogleMaps, {
load: {
key: 'YOUR_GOOGLE_MAP_API_KEY',
libraries: 'places'
}
})
打卡功能组件
<template>
<GmapMap
:center="center"
:zoom="15"
style="width:100%; height:400px"
@click="updateLocation"
>
<GmapMarker
:position="marker.position"
:clickable="true"
:draggable="true"
/>
</GmapMap>
</template>
<script>
export default {
data() {
return {
center: {lat: 39.9042, lng: 116.4074},
marker: {
position: {lat: 0, lng: 0}
}
}
},
mounted() {
this.getCurrentLocation()
},
methods: {
getCurrentLocation() {
navigator.geolocation.getCurrentPosition(
position => {
this.center = {
lat: position.coords.latitude,
lng: position.coords.longitude
}
this.marker.position = this.center
},
error => {
console.error('Error getting location', error)
}
)
},
updateLocation(event) {
this.marker.position = {
lat: event.latLng.lat(),
lng: event.latLng.lng()
}
}
}
}
</script>
打卡数据提交 实现打卡数据提交方法
methods: {
submitCheckIn() {
const checkInData = {
timestamp: new Date(),
coordinates: this.marker.position,
userId: 'current_user_id'
}
// 调用API提交数据
axios.post('/api/checkin', checkInData)
.then(response => {
console.log('打卡成功', response.data)
})
.catch(error => {
console.error('打卡失败', error)
})
}
}
注意事项
- 需要申请对应地图平台的API密钥
- 生产环境需要HTTPS协议才能使用地理位置API
- 考虑添加定位失败的回退方案
- 注意用户隐私政策合规性







