当前位置:首页 > VUE

vue实现电子围栏

2026-01-15 01:16:54VUE

Vue 实现电子围栏功能

电子围栏通常指在地图上划定一个虚拟边界,当目标进入或离开该区域时触发相应操作。以下基于 Vue 和常见地图库(如高德、百度或 Leaflet)的实现方案:

地图库引入

根据项目需求选择地图库,例如高德地图:

// 安装依赖
npm install @amap/amap-jsapi-loader

// Vue组件中引入
import AMapLoader from '@amap/amap-jsapi-loader';

地图初始化

在 Vue 组件的 mounted 生命周期中初始化地图:

vue实现电子围栏

mounted() {
  AMapLoader.load({
    key: '你的高德地图Key',
    version: '2.0',
    plugins: ['AMap.PolyEditor', 'AMap.Marker']
  }).then((AMap) => {
    this.map = new AMap.Map('map-container', {
      zoom: 15,
      center: [116.397428, 39.90923]
    });
    this.initFence();
  });
}

绘制电子围栏

使用多边形绘制围栏并绑定事件:

methods: {
  initFence() {
    const path = [
      [116.403322, 39.920255],
      [116.410703, 39.897555],
      [116.402292, 39.892353]
    ];

    this.fence = new AMap.Polygon({
      path: path,
      strokeColor: '#FF33FF',
      strokeWeight: 2,
      fillColor: '#1791fc',
      fillOpacity: 0.4
    });
    this.map.add(this.fence);

    // 启用编辑功能
    this.polyEditor = new AMap.PolyEditor(this.map, this.fence);
  }
}

围栏状态检测

通过地图 API 判断目标点是否在围栏内:

vue实现电子围栏

checkPositionInFence(lng, lat) {
  const point = new AMap.LngLat(lng, lat);
  return AMap.GeometryUtil.isPointInRing(point, this.fence.getPath());
}

实时监控实现

结合 WebSocket 或定时器实现动态检测:

// 模拟实时坐标
startMonitoring() {
  this.timer = setInterval(() => {
    const mockLng = 116.403322 + Math.random() * 0.01;
    const mockLat = 39.920255 + Math.random() * 0.01;

    if (this.checkPositionInFence(mockLng, mockLat)) {
      console.log('目标进入电子围栏');
    }
  }, 3000);
}

组件销毁处理

清除地图实例和监听器:

beforeDestroy() {
  if (this.map) this.map.destroy();
  if (this.timer) clearInterval(this.timer);
}

注意事项

  1. 地图 Key 需从对应平台申请
  2. 生产环境建议使用 WebSocket 实现真实坐标传输
  3. 复杂多边形需使用 AMap.GeometryUtilisPointInPolygon 方法
  4. 移动端需处理地图手势冲突问题

可根据具体需求扩展围栏编辑、历史轨迹记录等功能。

标签: 围栏电子
分享给朋友:

相关文章

vue实现电子围栏

vue实现电子围栏

Vue 实现电子围栏功能 电子围栏通常指通过地理围栏技术(Geo-fencing)在特定区域内触发业务逻辑。以下是基于 Vue 的实现方案: 基础实现思路 使用浏览器原生 Geolocation…