fence.js 12.3 KB
import EventBus from '@/event-bus'
import mapService from './mapService.js'
import MAPGEO from './mapgeo'

//电子围栏
const fence = {
    polygons: [],
    circle: null,
    isEditMode: true,
    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) {
                    this.polygonPath = data.path;
                    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) {
            this.polygons && MAP.remove(this.polygons);
            this.circle && MAP.remove(this.circle);
            this.circleEditor && this.circleEditor.close();//MAP.remove(this.circleEditor);
            this.polygons = [];
            this.polyEditor && this.polyEditor.close()
            this.mouseTool && this.mouseTool.close()
            this.polygon && MAP.remove(this.polygon)
        }
        //this.clearTimeoutIds();
    },

    // 行政区域
    drawDistrict(data) {
        if (!data || data.length <= 0) {
            return false;
        }
        const MAP = mapService.map;
        this.destroy();

        var opts = {
            subdistrict: 0,   //返回下一级行政区
            extensions: 'all',
            showbiz: false  //最后一级返回街道信息
        };
        let oParams = data[data.length - 1];
        //data == "中国" ? delete opts.extensions : delete opts.showbiz;
        let district = new AMap.DistrictSearch(opts);
        switch (data.length) {
            case 1:
                district.setLevel('province');
                break;
            case 2:
                district.setLevel('city');
                break;
            default:
                district.setLevel('district');
                break;
        }

        //EventBus.$emit('uiMap.fence.loading', true);
        //行政区查询
        district.search(oParams, function (status, result) {
            console.log(result)
            const dst = result.districtList[0];
            var bounds = dst.boundaries;
            let lng = dst.center.lng;
            let lat = dst.center.lat;

            if (bounds) {
                for (var i = 0, l = bounds.length; i < l; i++) {
                    //生成行政区划polygon
                    var polygon = new AMap.Polygon({
                        map: MAP,
                        strokeWeight: 1,
                        path: bounds[i],
                        fillOpacity: 0.7,
                        fillColor: '#CCF3FF',
                        strokeColor: '#CC66CC',

                    });
                    fence.polygons.push(polygon);
                }
                let center = mapService.getLngLat(lng, lat);
                mapService.setFitView();
                //EventBus.$emit('uiMap.fence.loading', false);
            }

        });
    },
    createFenceCircle(data) {
        let _this = this
        const MAP = mapService.map;
        _this.destroy();
        let mapInterval = setInterval(() => {
            if (MAP) {
                clearInterval(mapInterval)
                console.log(data)
                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
                }
                _this.circle = new AMap.Circle({
                    map: MAP,
                    center: mapService.getLngLat(lng, lat),
                    radius: data.radius * 1,
                    strokeColor: "#F33",
                    strokeOpacity: 1,
                    strokeWeight: 3,
                    fillColor: "ee2200",
                    fillOpacity: 0.35,
                    zIndex: 0,
                });

                _this.circleEditor = new AMap.CircleEditor(MAP, _this.circle);
                _this.circleEditor.on('adjust', function (e) {
                    console.log('监听圆心改变', e)
                    EventBus.$emit('uiMap.fence.onFenceRadiusChange', e.radius / 1)
                })

                _this.circleEditor.on('move', function (e) {
                    EventBus.$emit('uiMap.fence.onFenceLngLatChange', {
                        lng: e.lnglat.lng,
                        lat: e.lnglat.lat
                    });
                })

                if (_this.isEditMode) {
                    _this.circleEditor.open();
                } else {
                    _this.circleEditor.close();
                }
                mapService.setFitView()
                MAP.setZoom(14);
                _this.bindContextMenu()
            }
        }, 100);

    },
    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 MAP = mapService.map;
        //MAPGEO.transferAddressByGroup(this, ()=>{
        //data.transferAddressGPS = this.data[0].transferAddress;
        // if(this.data.length > 1){
        //     data.transferAddressBase = this.data[1].transferAddress;
        // }
        console.log(data)
        let marker = mapService.createCarMarker([data.lngGPS, data.latGPS], MAP);
        let infoWindow = mapService.bindFenceInfoWindow(marker, MAP, data);
        //});
    },
    drawPolygon() {
        const MAP = mapService.map;
        const self = this;
        this.destroy();

        if (this.polygonPath.length) {
            self.polygon = new AMap.Polygon({
                path: this.polygonPath,
                strokeColor: "#FF33FF",
                strokeWeight: 6,
                strokeOpacity: 0.2,
                fillOpacity: 0.4,
                fillColor: '#1791fc',
                zIndex: 50,
            })

            MAP.add(self.polygon)
            MAP.setFitView([self.polygon])

            self.polyEditor = new AMap.PolyEditor(MAP, self.polygon)
            if (self.isEditMode) {
                self.polyEditor.open()
            } else {
                self.polyEditor.close()
            }

            self.bindPolyEvent(self.polyEditor)
        } else if (self.isEditMode) {
            self.mouseTool = new AMap.MouseTool(MAP)

            self.mouseTool.polygon({
                strokeColor: "#FF33FF",
                strokeOpacity: 1,
                strokeWeight: 6,
                strokeOpacity: 0.2,
                fillColor: '#1791fc',
                fillOpacity: 0.4,
                // 线样式还支持 'dashed'
                strokeStyle: "solid",
                // strokeStyle是dashed时有效
                // strokeDasharray: [30,10],
            })

            self.mouseTool.on('draw', function (event) {
                // event.obj 为绘制出来的覆盖物对象
                self.polygon = event.obj;
                self.polyEditor = new AMap.PolyEditor(MAP, self.polygon)
                self.polyEditor.open()
                self.bindPolyEvent(self.polyEditor)
                self.mouseTool.close()
                self.emitPolyEvent()
            })

        }

    },
    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() {
        let pathArr = this.polygon.getPath()

        let resultArr = pathArr.map((item) => {
            return [item.lng, item.lat]
        })

        this.polygonPath = resultArr
        EventBus.$emit('uiMap.fence.polygonChange', {
            polygonPath: this.polygonPath
        });
        console.log(resultArr.join('|'))
    },
    clearTimeoutIds() {
        this.timeoutIds && this.timeoutIds.forEach((item) => {
            item && window.clearTimeout(item);
        });
        this.timeoutIds = []
    },

    // 地图增加右键功能
    bindContextMenu() {
        const self = this;
        const MAP = mapService.map;
        var contextMenu = new AMap.ContextMenu();
        contextMenu.addItem(
            "设置围栏中心",
            function () {
                self.moveCenter();
            },
            0
        );
        //地图绑定鼠标右击事件——弹出右键菜单
        MAP.on("rightclick", function (e) {
            contextMenu.open(MAP, e.lnglat);
            self.contextMenuPositon = e.lnglat;
        });
    },

    // 改变圆心
    moveCenter() {
        this.lng = this.contextMenuPositon.lng;
        this.lat = this.contextMenuPositon.lat;
        let center = mapService.getLngLat(this.lng, this.lat);
        this.circle.setCenter(center);
        EventBus.$emit('uiMap.fence.onFenceLngLatChange', {
            lng: this.lng,
            lat: this.lat,
        });
    },

    // 更新围栏
    updateFenceInfo(data) {
        let _this = this;
        const MAP = mapService.map;
        let mapInterval = setInterval(function () {
            if (MAP) {
                clearInterval(mapInterval);
                MAP.clearMap();

                _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);
                    return false;
                }

                // 更新行政区域围栏
                if (data.fenceType === "area") {
                    _this.areaCode = data.areaCode;
                    _this.drawDistrict(data);
                    return false
                }

                // 更新多边形围栏
                if (data.fenceType === "polygon") {
                    if (data) {
                        if (Array.isArray(data)) {
                            this.polygonPath = data;
                            this.isEditMode = true;
                        } else if (('isEdit' in data) && !data.isEdit) {
                            this.polygonPath = data.path;
                            this.isEditMode = false;
                        }
                    }
                    _this.drawPolygon();
                }
                mapService.setFitView()
                MAP.setZoom(14);
            }
        }, 100);
    }

}

export default fence;