vue实现高德地图多边形绘制电子围栏

本文介绍了如何使用Vue.js配合AMap API实现地图上的多边形绘制、编辑和删除功能,通过实例展示了如何使用PolyEditor插件进行实时经纬度调整。

<template>
  <div class="index">
    <el-button type="primary" @click="drawRectangle">绘制多边形</el-button>
    <el-button type="primary" @click="editRectangle">编辑多边形</el-button>
    <el-button type="primary" @click="deleRectangle">删除多边形</el-button>
    <div id="amapContainer"></div>
  </div>
</template>

<script>
export default {
  name: 'amapFence',
  data () {
    return {
      path: [], // 当前绘制的多边形经纬度数组
      polygonItem: [], // 地图上绘制的所有多边形对象
      polyEditors: []  // 所有编辑对象数组
    }
  },
  props: {
    paths: {} // 编辑
  },
  mounted () {
    this.intAmap(() => {
      if (this.paths) {
        this.editRectangle(this.paths);
      }
    });
  },
  methods: {
    // 地图初始化
    intAmap (callBack) {
      this.AMap = window.AMap;
      this.AMap.plugin(['AMap.MouseTool', 'AMap.PolyEditor', 'AMap.ControlBar'], function () {
        //TODO  创建控件并添加
      });
      this.map = new this.AMap.Map("amapContainer", {
        center: [116.434381, 39.898515],
        zoom: 14,
        mapStyle: "amap://styles/darkblue",
        pitch: 80,
        rotation: -15,
        viewMode: '3D',//开启3D视图,默认为关闭
        buildingAnimation: true,//楼块出现是否带动画
      });
      this.map.addControl(new this.AMap.ControlBar());
      if (callBack && typeof callBack == 'function') {
        callBack();
      }
    },
    // 编辑围栏
    editRectangle (paths) {
      const path = paths;
      const AMap = window.AMap;
      var polygon = new this.AMap.Polygon({
        path: path,
        strokeColor: "#FF33FF",
        strokeWeight: 6,
        strokeOpacity: 0.2,
        fillOpacity: 0.4,
        fillColor: '#1791fc',
        zIndex: 50,
      });

      this.map.add(polygon);
      this.polygonItem.push(polygon);
      // 缩放地图到合适的视野级别
      this.map.setFitView([polygon]);

      this.polyEditor = new AMap.PolyEditor(this.map, polygon);
      this.polyEditor.open();
      this.polyEditors.push(this.polyEditor);

      this.polyEditor.on('addnode', function (event) {
        console.info('触发事件:addnode', event)
        console.info('修改后的经纬度:', polygon.getPath())
      });

      this.polyEditor.on('adjust', function (event) {
        console.info('触发事件:adjust', event)
        console.info('修改后的经纬度:', polygon.getPath())
      });

      this.polyEditor.on('removenode', function (event) {
        console.info('触发事件:removenode', event)
        console.info('修改后的经纬度:', polygon.getPath())
      });

      this.polyEditor.on('end', function (event) {
        console.info('触发事件: end', event)
        console.info('修改后的经纬度:', polygon.getPath())
        // event.target 即为编辑后的多边形对象
      });
    },
    // 绘制多边形
    drawRectangle () {
      const vm = this;
      this.mouseTool = new this.AMap.MouseTool(this.map);
      const polygon = this.mouseTool.polygon({
        strokeColor: 'red',
        strokeOpacity: 0.5,
        strokeWeight: 6,
        fillColor: 'blue',
        fillOpacity: 0.5,
        // strokeStyle还支持 solid
        strokeStyle: 'solid',
        // strokeDasharray: [30,10],
      });

      this.mouseTool.on('draw', function (event) {
        // event.obj 为绘制出来的覆盖物对象
        var polygonItem = event.obj;
        var paths = polygonItem.getPath();//取得绘制的多边形的每一个点坐标
        console.log('覆盖物对象绘制完成各个点的坐标', paths);
        var path = [];  // 编辑的路径
        paths.forEach(v => {
          path.push([v.lng, v.lat])
        });
        vm.path = path;
        vm.editRectangle(vm.path);
        vm.polygonItem.push(event.obj);
        vm.map.remove(event.obj); // 删除多边形
        console.log(polygon, '------polygon-----');
      });
    },
    // 批量删除多边形
    deleRectangle () {
      // 取消编辑状态
      this.polyEditors.forEach(v => {
        v.close();
      });
      this.map.clearMap(); // 删除地图所有覆盖物
    },
  }
}
</script>

<style lang="scss" scoped>
#amapContainer {
  height: 800px;
  width: 1000px;
}
</style>

### 如何在 Vue 中使用高德地图 API 实现电子围栏功能 #### 初始化 Map 对象并加载地图 为了在 Vue 项目中集成高德地图,首先需要初始化 `Map` 对象。这一步骤通常通过引入高德地图 SDK 并配置相应的参数来完成。 ```javascript import AMapLoader from '@amap/amap-jsapi-loader'; export default { data() { return { map: null, }; }, mounted() { AMapLoader.load({ key: 'your_api_key', // 替换成自己的key version: "2.0", plugins: [] }).then((AMap) => { this.map = new AMap.Map('container', { zoom: 10, center: [116.397428, 39.90923], // 设置中心点坐标 }); }); } } ``` #### 使用 Geolocation 插件获取当前位置 一旦地图成功加载,在页面上显示用户的当前地理位置可以通过调用 `AMap.Geolocation` 来实现。此插件允许应用程序访问设备的位置服务以获得精确位置数据。 ```javascript mounted() { ... .then((AMap) => { const geolocation = new AMap.Geolocation({ enableHighAccuracy: true,// 是否使用高精度定位,默认:true timeout: 10000 // 超过10秒后停止定位,默认:无穷大 }); this.map.addControl(geolocation); geolocation.getCurrentPosition(function(status,result){ if(status=='complete'){ console.log(result.position); // 输出经纬度信息 }else{ console.error('Failed to get location'); } }); }) } ``` #### 绘制多边形表示电子围栏区域 要创建一个可视化的电子围栏,可以利用 `Polygon` 类定义一个多边形覆盖物,并将其添加到地图上作为地理边界标记。 ```javascript methods: { drawFence(points) { // points 是包含多个坐标的数组 let polygon = new AMap.Polygon({ path: points, strokeColor: "#FF33FF", strokeWeight: 6, strokeOpacity: 0.2, fillOpacity: 0.4, fillColor: '#1791fc', zIndex: 50 }); this.map.add(polygon); // 将视图调整至合适的缩放级别以便完全展示绘制好的多边形 this.map.setFitView([polygon]); } }, ... mounted(){ ... // 地图初始化完成后执行如下操作 setTimeout(() => { const fencePoints = [ [116.403322,39.920255], [116.410703,39.897555], [116.402292,39.892353], [116.389846,39.891365] ]; this.drawFence(fencePoints); }, 2000); } ``` #### 查询指定范围内的兴趣点 (POIs) 对于给定的一系列坐标点(如A1~A8),可通过 `placeSearch` 方法查找附近的 POI 数据。这些地点可能代表特定的兴趣点或地标建筑。 ```javascript methods: { searchNearbyPoi(centerPoint) { var placeSearch = new AMap.PlaceSearch({ pageSize: 5, pageIndex: 1, citylimit : false, children: 1 }); placeSearch.searchNearBy('', centerPoint, 1000, function(status, result) { if (status === 'complete') { console.log(result.poiList.pois); } }); } } // 假设已经获得了A1-A8对应的坐标列表 const poiCenters = ["国贸三期","东直门","奥体森林公园"]; poiCenters.forEach(name => { AMap.plugin(['AMap.CitySearch'], function () { var citysearch = new AMap.CitySearch(); citysearch.getLocalCity(function(status, result) { if (status === 'complete' && result.info === 'OK') { var cityName = result.city; var adcode = result.adcode; AMap.service(["AMap.Geocoder"], function() { var geocoder = new AMap.Geocoder({ city: adcode }); geocoder.getLocation(name, function(status, data) { if (status === 'complete' && data.info === 'OK') { this.searchNearbyPoi(data.geocodes[0].location); } }.bind(this)); }); } }); }); }); ```
评论 27
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值