vue实现电子围栏
Vue实现电子围栏的方法
地图组件集成
使用高德地图或百度地图的JavaScript API,在Vue项目中通过npm安装官方提供的SDK包。在Vue组件中初始化地图实例,设置中心点坐标和缩放级别。地图容器需指定明确的宽度和高度样式。
import AMap from 'AMap'
export default {
mounted() {
this.initMap()
},
methods: {
initMap() {
const map = new AMap.Map('map-container', {
zoom: 13,
center: [116.397428, 39.90923]
})
}
}
}
围栏绘制功能
通过地图API的覆盖物接口添加多边形绘制工具。监听用户绘制完成事件,获取顶点坐标集合。使用地图的MouseTool插件实现交互式绘制,支持多边形和圆形两种围栏类型。
addFenceTool() {
const mouseTool = new AMap.MouseTool(this.map)
mouseTool.polygon({
strokeColor: '#FF33FF',
fillOpacity: 0.2
})
mouseTool.on('draw', (e) => {
this.fenceCoordinates = e.obj.getPath()
})
}
坐标点判断算法
实现射线法判断点是否在多边形内,该算法通过计算目标点向右发射的射线与多边形边的交点数量确定位置。对于圆形围栏,计算两点间距离是否小于半径。
function isPointInPolygon(point, polygon) {
const x = point[0], y = point[1]
let inside = false
for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
const xi = polygon[i][0], yi = polygon[i][1]
const xj = polygon[j][0], yj = polygon[j][1]
const intersect = ((yi > y) !== (yj > y))
&& (x < (xj - xi) * (y - yi) / (yj - yi) + xi)
if (intersect) inside = !inside
}
return inside
}
围栏状态管理
使用Vuex存储所有电子围栏数据,包括坐标集合、围栏类型和告警规则。定义mutations处理围栏的增删改查操作,通过getters提供围栏的空间查询接口。
const store = new Vuex.Store({
state: {
fences: []
},
mutations: {
ADD_FENCE(state, fence) {
state.fences.push(fence)
}
}
})
实时位置监控
集成浏览器Geolocation API或第三方定位SDK,定时获取设备当前位置。使用watch监听位置变化,调用判断算法检测是否触发围栏事件,触发后调用告警处理逻辑。
navigator.geolocation.watchPosition((position) => {
const currentPos = [position.coords.longitude, position.coords.latitude]
this.checkFenceTrigger(currentPos)
})
checkFenceTrigger(point) {
this.fences.forEach(fence => {
const isInside = fence.type === 'polygon'
? isPointInPolygon(point, fence.path)
: getDistance(point, fence.center) <= fence.radius
if (isInside !== fence.lastStatus) {
this.triggerAlarm(fence, isInside)
}
})
}
可视化反馈
在地图上渲染不同状态的围栏区域,进入区域时显示高亮填充色。使用信息窗口展示围栏详情,通过自定义覆盖物添加动态标记效果。结合Vue的过渡系统实现平滑的状态变化动画。
renderFences() {
this.fences.forEach(fence => {
const path = fence.type === 'polygon' ? fence.path : this.getCirclePath(fence)
new AMap.Polygon({
path: path,
fillColor: fence.active ? '#FF0000' : '#00FF00',
strokeWeight: 2
}).setMap(this.map)
})
}
性能优化策略
对围栏数据进行空间索引建立R-tree结构,快速筛选可能触发的围栏。采用防抖机制控制高频位置更新的处理频率,使用Web Worker处理复杂的空间计算任务避免UI线程阻塞。
const worker = new Worker('./fenceWorker.js')
worker.postMessage({
point: currentPos,
fences: this.activeFences
})
worker.onmessage = (e) => {
this.handleAlerts(e.data.triggeredFences)
}


