fence.js 13.2 KB
/*
 * @Author: 'wangzhihui' '1733904062@qq.com'
 * @Date: 2024-11-28 16:37:15
 * @LastEditors: 'wangzhihui' '1733904062@qq.com'
 * @LastEditTime: 2024-12-26 15:31:02
 * @FilePath: \oEshield\src\utils\fence.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import EventBus from '@/event-bus'
// import mapService from './mapService.js'
import mapService from './mapBService.js'
// import MAPGEO from './mapgeo'
import MAPGEO from './mapBgeo'

//电子围栏
const fence = {
    polygons: [],
    circle: null,
    dist:null,
    drawingManager:null,
    isEditMode: true,
    marker:'',
    bindEvent() {
        EventBus.$on('uiMap.fence.drawDistrict', (data) => {
            this.drawDistrict(data)
        });

        EventBus.$on('uiMap.fence.createFenceCircle', (data) => {
            if (('isEdit' in data) && !data.isEdit) {
                this.isEditMode = false
            } else {
                this.isEditMode = true
            }
            this.createFenceCircle(data)
        });

        EventBus.$on('uiMap.fence.updateFenceRadius', (data) => {
            console.log('监听围栏更新', data)
            this.updateFenceInfo(data)
        });
        //this.circle.setRadius(data * 1);

        EventBus.$on('uiMap.fence.createFenceMarker', (data) => {
            this.createFenceMarker(data)
        });

        EventBus.$on('uiMap.fence.drawPolygon', (data) => {
            if (data) {
                if (Array.isArray(data)) {
                    this.polygonPath = data;
                    this.isEditMode = true;
                } else if (('isEdit' in data) && !data.isEdit) {
                   let arr= data.path.map(item=>{
                        return mapService.getLngLat(item[0], item[1])
                    })
                    this.polygonPath =arr;
                    this.isEditMode = false;
                }
            }
            this.drawPolygon()
        });

        EventBus.$on('uiMap.fence.destroy', (data) => {
            this.polyEditor && this.polyEditor.close()
            this.mouseTool && this.mouseTool.close()
        });
    },
    destroy() {
        const MAP = mapService.map;
        if (MAP) {
            // // MAP.invoke('removeOverlay',this.polygons)
            // this.polygon &&MAP.invoke('removeOverlay',this.polygon);
            // this.circle &&  MAP.invoke('removeOverlay',this.circle);
            // this.drawingManager &&  MAP.invoke('removeOverlay',this.drawingManager);
            AMap.invoke('clearOverlays');
            AMap.invoke('addOverlay',this.marker)
            //清除多边形
            if(  this.drawingManager&&this.drawingManager.getOverlays().length){
                let overlays=this.drawingManager.getOverlays()[0]
                AMap.invoke('removeOverlay',overlays);
            }
            if(document.getElementById('cancelOperate')){
                document.getElementById('cancelOperate').click()
            }
         
            this.dist&& MAP.invoke('removeDistrictLayer',  this.dist)
            // this.polygons = [];
            // this.polyEditor && this.polyEditor.close()
            // this.mouseTool && this.mouseTool.close()
        }
        //this.clearTimeoutIds();
    },

    // 行政区域
    drawDistrict(data) {
        this.destroy();
        if (!data || data.length <= 0) {
            return false;
        }
      if ( this.dist) AMap.invoke('removeDistrictLayer',  this.dist)
      this.dist = AMap.invoke('DistrictLayer', {
        name: `(${data[data.length-1]})`,
        fillOpacity: 0.7,
        fillColor: '#CCF3FF',
        strokeColor: '#CC66CC',
        viewport: true
      });
      AMap.invoke('addDistrictLayer',  this.dist)
        
    },
    updateFenceCircle(data){
        console.log(data)
        let center
        AMap.invoke('circleDisableEditing')
        if( data.radius&&this.circle){
            this.circle.setRadius(data.radius * 1)
        }
        if(data.lng&&data.lat){
            center = mapService.getLngLat(data.lng, this.lat);
            this.circle&&  this.circle.setCenter(center);
           
        }
        center= this.circle&& this.circle.getCenter()
        AMap.invoke('removeOverlay', this.circle)
        AMap.invoke('addOverlay', this.circle)
        AMap.invoke('circleEnableEditing')
        AMap.invoke('panTo',center,true)
    },
    createFenceCircle(data) {
        if(!this.circle){
            let _this = this
            const  mapInstance= mapService.mapInstance
            let mapInterval = setInterval(() => {
                if (AMap) {
                    clearInterval(mapInterval)
                    let lng = data.lng || _this.lng
                    let lat = data.lat || _this.lat
                    if (data.lng) {
                        _this.lng = data.lng
                    }
                    if (data.lat) {
                        _this.lat = data.lat
                    }
                        const lnglat=mapService.getLngLat(lng, lat)
                        let options={
                            strokeColor: "#F33",
                            strokeOpacity: 1,
                            strokeWeight: 3,
                            fillColor: "ee2200",
                            fillOpacity: 0.35,
                            enableEditing:true
                        }
                        if(!_this.isEditMode) options.enableEditing=false
                        _this.circle=AMap.invoke('Circle',lnglat,data.radius * 1,options)
                        AMap.invoke('panTo',lnglat,true)
                        AMap.invoke('addOverlay',_this.circle)
                        AMap.invoke('setZoom',14)
                        _this.bindContextMenu()
                        AMap.invoke('circleAddEventListener','lineupdate',function(e){
                            let overlay=e.overlay
                        EventBus.$emit('uiMap.fence.onFenceLngLatChange', {
                                    lng:e.overlay.getCenter().lng,
                                    lat:e.overlay.getCenter().lat
                                });
                         EventBus.$emit('uiMap.fence.onFenceRadiusChange', parseInt(overlay.getRadius() / 1))   
                    })
                  
                }
            }, 2000);
        }else{
            this.destroy();
            this.updateFenceCircle(data)
        }
  

    },
    createFenceMarker(data) {
        this.data = [{
            elng: data.lngGPS,
            elat: data.latGPS
        }];
        if (data.lngBase && data.latBase) {
            this.data.push({
                elng: data.lngBase,
                elat: data.latBase
            });
        }
        const getLngLat=mapService.getLngLat(data.lngGPS,data.latGPS)
        this.marker = mapService.createCarMarker(getLngLat, AMap);
        let infoWindow = mapService.bindFenceInfoWindow( this.marker, AMap, data);
        AMap.invoke('addOverlay',this.marker)
    },
    drawPolygon() {
        const self = this;
        this.destroy();
        if (this.polygonPath.length) {
            let options={
                zIndex: 10,
                strokeColor: "#FF33FF",
                strokeWeight: 6,
                strokeOpacity: 0.2,
                fillOpacity: 0.4,
                fillColor: '#1791fc',
                enableEditing:true
            }
            if(!self.isEditMode){
                options.enableEditing=false
            }
            self.polygon=AMap.invoke('Polygon',this.polygonPath,options)
           //获取多边形的中间位置
            let lnglat=self.polygon.getBounds().getCenter()
            //地图的中心点更改为给定的点
            AMap.invoke('panTo',lnglat,true)
            AMap.invoke('polygonAddEventListener','lineupdate',function(e){
                let pathArr = self.polygon.getPath()
                self.emitPolyEvent(pathArr) 
            })
         
            AMap.invoke('addOverlay', self.polygon)
            AMap.invoke('setZoom',17)
        } else if (self.isEditMode) {
            var styleOptions = {
                strokeColor: '#FF33FF',   // 边线颜色
                fillColor: '#1791fc',     // 填充颜色。当参数为空时,圆形没有填充颜色
                strokeWeight: 6,          // 边线宽度,以像素为单位
                strokeOpacity: 0.2,         // 边线透明度,取值范围0-1
                fillOpacity: 0.4          // 填充透明度,取值范围0-1
            };
            var labelOptions = {
                borderRadius: '2px',
                background: '#FF33FF',
                border: '1px solid #E1E1E1',
                color: '#703A04',
                fontSize: '12px',
                letterSpacing: '0',
                padding: '5px'
            };
            self.drawingManager = AMap.invoke('DrawingManager', mapService.mapInstance, {
                isOpen: true,  // 是否开启绘制模式
                enableDrawingTool: true,
                enableCalculate: false, // 绘制是否进行测距测面
                enableSorption: true,   // 是否开启边界吸附功能
                sorptiondistance: 20,   // 边界吸附距离
                circleOptions: styleOptions,     // 圆的样式
                polylineOptions: styleOptions,   // 线的样式
                polygonOptions: styleOptions,    // 多边形的样式
                rectangleOptions: styleOptions,  // 矩形的样式
                labelOptions: labelOptions,      // label样式
              })   
              AMap.invoke('drawingManagerAddEventListener','polygoncomplete',function(e){
                let overlays=e
                let pathArr = e.getPath()
                console.log(pathArr)
                // let resultArr = pathArr.map((item) => {
                //     return item.latLng
                // })
                self.emitPolyEvent(pathArr)
              })
              AMap.invoke('setDrawingMode', 'polygon')

        }

    },
    bindPolyEvent(polyEditor) {
        const self = this
        polyEditor.on('addnode', function (event) {
            console.log('触发事件:addnode')
            self.emitPolyEvent()
        })

        polyEditor.on('adjust', function (event) {
            console.log('触发事件:adjust')
            self.emitPolyEvent()
        })

        polyEditor.on('removenode', function (event) {
            console.log('触发事件:removenode')
            self.emitPolyEvent()
        })

        polyEditor.on('end', function (event) {
            console.log('触发事件: end')
            self.emitPolyEvent()
            // event.target 即为编辑后的多边形对象
        })
    },
    emitPolyEvent(resultArr) {
        this.polygonPath = resultArr
        EventBus.$emit('uiMap.fence.polygonChange', {
            polygonPath: this.polygonPath
        });
    },
    clearTimeoutIds() {
        this.timeoutIds && this.timeoutIds.forEach((item) => {
            item && window.clearTimeout(item);
        });
        this.timeoutIds = []
    },

    // 地图增加右键功能
    bindContextMenu() {
        const self = this;
        const mapInstance = mapService.mapInstance;
        var contextMenu = AMap.invoke('ContextMenu');
        contextMenu.addItem(
            AMap.invoke('MenuItem',"设置围栏中心", function () {
            self.moveCenter();
        }) 
        );
        AMap.invoke('mapAddEventListener','rightclick',function (e) {
            AMap.invoke('addContextMenu',contextMenu)
                self.contextMenuPositon = e.latlng
            })
    },

    // 改变圆心
    moveCenter() {
        const MAP = mapService.map;
        AMap.invoke('circleDisableEditing')
        this.circle&&  this.circle.setCenter(this.contextMenuPositon);
        AMap.invoke('removeOverlay', this.circle)
        AMap.invoke('addOverlay', this.circle)
        AMap.invoke('circleEnableEditing')
    },

    // 更新围栏
    updateFenceInfo(data) {
        let _this = this;
        const MAP = mapService.map;
        let mapInterval = setInterval(function () {
            if (AMap) {
                clearInterval(mapInterval);
                if (_this.fenceCircle) {
                    AMap.remove(_this.fenceCircle)
                }
                _this.fenceType = data.fenceType;
                _this.polyEditor && _this.polyEditor.close();
                _this.mouseTool && _this.mouseTool.close();

                // 更新圆形围栏
                if (data.fenceType == 'circle') {
                    _this.fenceCircle = null;
                    if (data.lng) {
                        _this.lng = data.lng;
                    }
                    if (data.lat) {
                        _this.lat = data.lat;
                    }
                    if (data.radius) {
                        _this.radius = Number(data.radius);
                    }
                    console.log(data)
                    // _this.createFenceCircle(data);
                    _this.updateFenceCircle(data)
                    return false;
                }
                // mapService.setFitView()
                MAP.setZoom(14);
                AMap.invoke('setZoom',14)
            }
        }, 100);
    }

}

export default fence;