<template>
    <div id="cartest" class="popup" style="display:none">
            <label for="speed" style="font-weight: bold;">
                运动速度:&nbsp;
                <input id="speed" type="range" min="1" max="8000" step="1" value="1000" ref="speed" />
            </label>
            <button id="start-animation" @click="start" ref="startButton">
                开始
            </button>
            <button id="pause-animation" @click="pause" ref="pauseButton">
                暂停
            </button>
            <!-- <button id="stop-animation" @click="stop" ref="stopButton" style="display:none">
                停止
            </button> -->
             <button id="pause-animation" @click="showNet" ref="pauseButton"
             style="display:none">
                路网
            </button>
     </div>
</template>
<script>
    import {
        Fill,
        Stroke,
        Style,
        Text,
        Icon,
        Circle
    } from 'ol/style'
    import {
        Vector as VectorLayer
    } from 'ol/layer'
    import {
        Vector as VectorSource
    } from 'ol/source'
    import {
        clearSpatial,lineShowDistant
    } from './poiQuery'
    import {
        addAlarmFlash,
        removeOverLayeById
    } from './alarmFlash'
    import turf_point from 'turf-point'
    import GeoJSON from 'ol/format/GeoJSON'
    import Feature from 'ol/Feature'
    import LineString from 'ol/geom/LineString'
    // import turf_length from '@turf/length'
    import line_intersect from '@turf/line-intersect'
    import Point from 'ol/geom/Point'
    import axios from 'axios'
    import qs from 'qs'
    import turf_along from '@turf/along'
    import turf_linestring from 'turf-linestring'
    import turf_nearestPointOnLine from '@turf/nearest-point-on-line'
    import turf_booleanPointOnLine from '@turf/boolean-point-in-polygon'
    import turf_length from '@turf/length'
    import Modify from 'ol/interaction/Modify'
    //import rbush from 'ol/structs/RBush'
    import rbush from 'rbush'
    import {addVector,twoPointsLength} from '../base/poiQuery'
    import { transform, getTransform } from 'ol/proj'
    import { wgs84Toweb3857 } from './factory'
    import {fromLonLat} from 'ol/proj'
    export default {
        name: 'carTestCLCross',
        render() {},
        data() {
            return {
                animating: false,
                geoMarker: {},
                routeLength: 0,
                routeCoords: [],
                route: [],
                allPathArray: [],
                secondFlag: false,
                routeAll: [],
                colorIndex: 0,
                colors: ['red', 'green'],
                stopMakers: [],
                perDistance: 0,
                line_length: 0,
                lineAll_length: 0,
                routeFeature: {},
                routeAllFeature: {},
                movePos: {},
                lineArr: [],
                arr: [],
                rotation: 0,
                styles: {},
                countTwo: 0,
                stopFlag: false,
                start_index: null,
                startActive: false,
                vectorLayer: {},
                geoArray: [],
                initFlag: false,
                arrAll: [],
                currentIndex: 0,
                countIndex: 0,
                lenArray: [],
                lenCountArray: [],
                addLen: 0,
                indexCir: 0,
                startObj: {},
                timer: {},
                flashingArr: [],
                clearAllFlag: false,
                multiFlag: false,
                stylesBasic: {},
                colorArr: [],
                nodeCountArr: [],
                frontObject: {},
                addCount:0,
                reverseFlag:false,
                endArr:[],
                drawRouteCompleted:false,
                nodeType:'',
                startNode:{},
                lineArr:[],
                firstName:'',
                endName:'',
                lineArr2:[],
                findlineAll:[],
                endNode:{},
                nodeCount:{},
                _styleNode:{},
                finished:false,
                line_layer:{},
                findLineArr:[],
                diguiCount:0,
                finalMergeArr:[],
                // mulitiEnterCount:0
            }
        },
        props: {
            map: {
                type: Object
            },
            serverUrl: {
                type: String
            },
            tableName: {
                type: String
            },
            stopRendingFlag:{
                type:Boolean
            }
        },
        watch: {
            position(val) { //父组件点击地图，将父组件的position传递给子组件，子组件监听父组件属性的变化
                this.pos = val
            }
        },
        //mixins: [commonMixin('overlay')],
        methods: {
            updateTableName(val){
                this.tableName = val
            },
            splitNoParen(s){
                var left= 0, right= 0, A= [], finalStr=[],
                M= s.match(/([^()]+)|([()])/g), L= M.length, next, str= '';
                for(var i= 0; i<L; i++){
                    next= M[i];
                    if(next=== '(')++left;
                    else if(next=== ')')++right;
                    if(left!== 0){
                        str+= next;
                        if(left=== right){
                            A[A.length-1]+=str;
                            left= right= 0;
                            finalStr.push(str)
                            str= '';
                        }
                    }
                    else A=A.concat(next.match(/([^,]+)/g));
                }
                // return A;
                return finalStr;
            },
            showNet(frontObj, carType,typeObject,type,countFlag,numberPos) {
                var _this = this;
                _this.diguiCount = 0;
                return new Promise(function(resolve){
                    _this.nodeType = typeObject.nodeCount
                    _this.$emit('drawLineComplete',false)
                    let routeContains = [];
                        if (frontObj.map.getLayers().array_ != undefined) {
                            for (var i = 0; i < frontObj.map.getLayers().array_.length; i++) {
                                if (frontObj.map.getLayers().array_[i].values_.id != undefined) {
                                    if (frontObj.map.getLayers().array_[i].values_.id == carType) { //包含不渲染
                                        routeContains.push(frontObj.map.getLayers().array_[i].values_.id);
                                    }
                                }
                            }
                        }
                        if (routeContains.includes(carType)) { //地图中含有已经渲染的路径不需要再渲染     
                        } else {
                                if(!_this.drawRouteCompleted){//开始画线
                                    //此处先把中间点渲染出来,后面等真实的点线出来后再把此处渲染的中间点清除
                                _this.showMediumNodeLen4(frontObj.routArr,carType,frontObj,typeObject);
                                    if(typeObject.isOnlyNode){
                                        return;
                                    }
                                    _this.colorArr.push({
                                            "carType": carType,
                                            "roadStyle": frontObj.roadStyle
                                        }) //颜色区别
                                        //节点区别
                                    _this.nodeCountArr.push({
                                            "carType": carType,
                                            "roadArr": frontObj.routArr
                                        }) //颜色区别
                                    // var _this = this;
                                    _this.addCount = 0;
                                    _this.multiFlag = false;
                                    _this.reverseFlag = false;
                                    _this.startObj = frontObj
                                    _this.countTwo = 0;
                                    _this.countIndex = 0;
                                    _this.secondFlag = false
                                    _this.arrAll.length = 0;
                                    _this.lenCountArray.length = 0;
                                    _this.currentIndex = 0;
                                    _this.arr = frontObj.routArr
                                    getImg()
                                    function getImg() { //递归
                                        if (_this.currentIndex >= _this.arr.length) {
                                            // var t=setTimeout(function(){
                                                if(type=="constantLine"){//匀速行动返回长度和时间
                                                    var line = turf_linestring(_this.arrAll);
                                                    let lineLength = turf_length(line, {
                                                            units: 'kilometers'
                                                    })
                                                    _this.$emit('drawLineComplete',{'roadArr':_this.arrAll,'length':lineLength,'type':typeObject.carType})
                                                    // resolve({'roadArr':_this.arrAll,'length':lineLength});
                                                }
                                            // },1000)
                                            return;
                                        }
                                        let x1 = _this.arr[_this.currentIndex].X;
                                        let y1 = _this.arr[_this.currentIndex].Y;
                                        let x2 = _this.arr[_this.currentIndex + 1].X;
                                        let y2 = _this.arr[_this.currentIndex + 1].Y;
                                        let postTable = _this.tableName
                                        var initData = {
                                            "posArray": [{
                                                "X": x1,
                                                "Y": y1,
                                                "tableName": postTable
                                            }, {
                                                "X": x2,
                                                "Y": y2,
                                                "tableName": postTable
                                            }]
                                        }
                                        axios.post(_this.serverUrl, qs.stringify(initData), {
                                            headers: {
                                                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                                            }
                                        }).then(res => {
                                            console.log("请求数据成功...........")
                                            console.log("*************************")
                                            _this.currentIndex = _this.currentIndex + 2;
                                            _this.addCount = 0;
                                            let geom;
                                            geom = res.data[0].st_astext;
                                            // geom = res.data[0].geom
                                            console.log(res.data)
                                            console.log(res.data[0])
                                            console.log(geom)
                                            let stringArray;
                                            _this.geoArray.length = 0;
                                            if (geom != null) {
                                                if (geom.includes(("MULTI"))) {//为多线和线为空的情况下直接连接起始点和终点
                                                     console.log("进入多线")
                                                    _this.multiFlag = true
                                                    let geomMulti = "LINESTRING(" + y1 + " " + x1 + "," + y2 + " " + x2 + ")"
                                                    stringArray = geomMulti.substring(geomMulti.indexOf("(") + 1, geomMulti.lastIndexOf(")")).split(",")
                                                    //另外一种情况
                                                    let step1 = geom.substring(geom.indexOf("(") + 1, geom.lastIndexOf(")"));
                                                    let step2 = _this.splitNoParen(step1);
                                                    var startPoint = [],endPoint = [];
                                                    var start = [],end = [];
                                                    var startNear =[],endNear=[];
                                                    let multiArr = [];
                                                    let geoJsonArr = [];
                                                    let geojsonFormat = new GeoJSON({ defaultDataProjection: "EPSG:4326" });
                                                    _this.findlineAll.length = 0;
                                                    if(step2.length!=0){
                                                        for(var i = 0;i<step2.length;i++){
                                                            let multifinalgeom = step2[i].substring(step2[i].indexOf("(") + 1, step2[i].lastIndexOf(")")).split(",")        
                                                            multiArr.push(multifinalgeom)
                                                        }
                                                        for(var k = 0;k<multiArr.length;k++){//多线中的单个线路分别渲染路网
                                                            let multiStr = multiArr[k];
                                                            let multiDataArr = []
                                                            for (var i = 0; i < multiStr.length; i++) { //每次将生成的最短路径形成路径数组geoArray
                                                                let arr = multiStr[i].split(" ");
                                                                let lon = parseFloat(arr[0]);
                                                                let lat = parseFloat(arr[1]);
                                                                multiDataArr.push([lon, lat])
                                                            } 
                                                            geoJsonArr.push(multiDataArr);
                                                            let linestring = turf_linestring(multiDataArr, { id: carType })
                                                            startPoint = turf_point([y1, x1]);//起点坐标
                                                            endPoint = turf_point([y2, x2]);//终点坐标
                                                            start.push(turf_nearestPointOnLine(linestring, startPoint, {units: 'miles'}));
                                                            end.push(turf_nearestPointOnLine(linestring, endPoint, {units: 'miles'}));
                                                            //在此处找到距离起点和终点最近的点，然后第一条线直接最近的点组和最后一个点组成数组
                                                            //最后一条线是起点和最近的点组成数组
                                                        }
                                                        let startObj = [],endObj = [],line,length;
                                                        for(let i = 0;i<start.length;i++){
                                                            line = turf_linestring([start[i].geometry.coordinates, [y1, x1]]);
                                                            length = turf_length(line, {units: 'kilometers'});
                                                            startObj.push({
                                                                len:length,
                                                                coord:start[i].geometry.coordinates
                                                            })
                                                        }
                                                        for(let i = 0;i<end.length;i++){
                                                             line = turf_linestring([end[i].geometry.coordinates, [y2, x2]]);
                                                             length = turf_length(line, {units: 'kilometers'});
                                                             endObj.push({
                                                                len:length,
                                                                coord:end[i].geometry.coordinates
                                                            })
                                                        }
                                                        let startFinal = _this.getmaxscore(startObj)
                                                        let endFinal = _this.getmaxscore(endObj)
                                                        let nearestStartPoint = startObj[startFinal];
                                                        let nearstEndPoint = endObj[endFinal];                         
                                                        let startIndex = startObj.sort(_this.compare('len')); 
                                                        let endIndex = endObj.sort(_this.compare('len'));
                                                        _this.AddturfLineString(frontObj,carType,y1,x1,startIndex,geojsonFormat)//起点连接线
                                                        _this.AddturfLineString(frontObj,carType,y2,x2,endIndex,geojsonFormat)//终点连接线
                                                        console.log(geoJsonArr)//原始坐标点
                                                        let getStartIndex = 0;
                                                        let getEndIndex = 0;
                                                        let finalArr1 = []
                                                        let finalArr2 = []
                                                        let linestringFinal;
                                                        _this.sortMuliti(geoJsonArr,numberPos)//number为起点坐标
                                                        let arr = _this.finalMergeArr
                                                        let result = _this.merge1(arr);
                                                        //此处渲染路网
                                                        // linestringFinal = turf_linestring(result, { id: carType })
                                                        // let features = geojsonFormat.readFeatures(linestringFinal)
                                                        let finalResult = [];
                                                        for(let i = 0;i<result.length;i++){
                                                            finalResult.push(fromLonLat([result[i][0],result[i][1]]))
                                                        }
                                                        linestringFinal = new LineString(finalResult);
                                                        // linestringFinal = new LineString(result);
                                                        let bufferLine = new Feature({
                                                                    id: carType,
                                                                    type: 'route',
                                                                    geometry: linestringFinal
                                                        })
                                                        // let test = wgs84Toweb3857([121.303107065764, 31.1854128430452])
                                                        // let bufferLine = features[0]
                                                        let data_line = new VectorSource()
                                                        data_line.addFeature(bufferLine);
                                                        let bufferLayer = new VectorLayer({
                                                            // id: carType+k,/
                                                            id:carType,
                                                            source: data_line,
                                                            style: new Style({
                                                                stroke: new Stroke({
                                                                    color: frontObj.roadStyle.lineColor,
                                                                    width: frontObj.roadStyle.lineWidth
                                                                })
                                                            })
                                                        })
                                                        frontObj.map.addLayer(bufferLayer)
                                                        // resolve({'mediumNode':result,'type':typeObject.carType});
                                                        resolve({'mediumNode':finalResult,'type':typeObject.carType});
                                                        if(!_this.stopRendingFlag){
                                                            getImg()
                                                        }else{
                                                            //当stopRendingFlag为true的时候返回标志
                                                            _this.$emit('diguiFlag',_this.stopRendingFlag)
                                                            // _this.drawRouteCompleted = false
                                                            _this.drawRouteCompleted = false
                                                            // return false;
                                                        }
                                                    } 
                                                } else {//单线情况
                                                //    _this.mulitiEnterCount++;
                                                    stringArray = geom.substring(geom.indexOf("(") + 1, geom.lastIndexOf(")")).split(",")
                                                    let singleArr = []
                                                    for (var i = 0; i < stringArray.length; i++) { //每次将生成的最短路径形成路径数组geoArray
                                                        _this.orderString(stringArray[i])
                                                        let arr = stringArray[i].split(" ");
                                                        let lon = parseFloat(arr[0]);
                                                        let lat = parseFloat(arr[1]);
                                                        singleArr.push([lon, lat])
                                                    }
                                                     console.log("进入单线")
                                                    //此处重新判断---此处有可能会出现起点和终点倒置的情况(如有反转需要倒置)
                                                    let startLon = _this.geoArray[0][0]
                                                    let startLat = _this.geoArray[0][1]
                                                    let endLon = _this.geoArray[_this.geoArray.length - 1][0]
                                                    let endLat = _this.geoArray[_this.geoArray.length - 1][1]
                                                    if (Math.abs(_this.geoArray[0][0] - y1) <= Math.abs(_this.geoArray[_this.geoArray.length - 1][0] - y1)) {
                                                        _this.geoArray.length = 0;
                                                        for (var i = 0; i < stringArray.length; i++) {
                                                            if(_this.multiFlag){
                                                                _this.roadStringArray(stringArray[i],y2,x2,y1,x1,stringArray,typeObject)
                                                                break;
                                                            }else{
                                                                _this.roadStringArray(stringArray[i],y2,x2,y1,x1,stringArray,typeObject)
                                                            }
                                                            
                                                        }
                                                        if (_this.multiFlag) {//已经首位相接
                                                            _this.multiFlag = false;
                                                        }
                                                        _this.reverseFlag = false;
                                                    } else {//翻转数组--反转的情况确实存在而且多次出现
                                                        _this.geoArray.length = 0;
                                                        _this.reverseFlag = true;
                                                        for (var i = stringArray.length - 1; i >= 0; i--) {
                                                            _this.roadStringArray(stringArray[i],y2,x2,y1,x1,stringArray,typeObject)
                                                        }
                                                        if (_this.multiFlag) {//已经首位相接
                                                            _this.multiFlag = false;
                                                        }
                                                    }
                                                    _this.countTwo++;
                                                    //在此处再进行是否反转的操作
                                                    let singleStartLen = twoPointsLength([[y1,x1],_this.geoArray[0]])//0和1
                                                    let singleEndLen = twoPointsLength([[y1,x1],_this.geoArray[_this.geoArray.length-1]])
                                                    if(singleStartLen<=singleEndLen){

                                                    }else{
                                                        _this.geoArray.reverse();
                                                        _this.arrAll.reverse();
                                                    }
                                                    //从第二个数据开始去除第一项，并将数组翻转
                                                    _this.initRoute(frontObj.map, _this.geoArray, _this.arrAll, initData, frontObj, carType,typeObject);
                                                    _this.geoArray.pop()
                                                    _this.geoArray.shift()
                                                    console.log("返回single")
                                                    resolve({'mediumNode':_this.geoArray,'type':typeObject.carType});
                                                    _this.$emit('roadFinish', carType + "_" + _this.countTwo)
                                                    let num = Math.round(_this.arr.length / 2);
                                                    if (_this.countTwo === num) {//画完线
                                                        _this.drawRouteCompleted = false
                                                    } else {
                                                        _this.drawRouteCompleted = true
                                                    }
                                                    if(!_this.stopRendingFlag){
                                                        getImg()
                                                    }else{
                                                        //当stopRendingFlag为true的时候返回标志
                                                        _this.$emit('diguiFlag',_this.stopRendingFlag)
                                                        // _this.drawRouteCompleted = false
                                                        _this.drawRouteCompleted = false
                                                        // return false;
                                                    }
                                                    }
                                                    
                                            } else {//当为null的时候之间连接起始点和终点坐标
                                                alert("此处没有路网!")
                                            }
                                        }, err => {
                                            _this.currentIndex = _this.currentIndex + 2;
                                            if(!_this.stopRendingFlag){
                                                    getImg()
                                            }else{
                                                    _this.$emit('diguiFlag',_this.stopRendingFlag)
                                                _this.drawRouteCompleted = false
                                            }
                                        })
                                    }
                            }
                        }
                    })
            },
            merge1(arr) {
                const result = []
                for (let i = 0; i < arr.length; i++) {
                for (let j = 0; j < arr[i].length; j++) {
                    result.push(arr[i][j])
                }
                }
                return result
            },
            getMinIndex(arr) {
                var min = arr[0];
                //声明了个变量 保存下标值
                var index = 0;
                for (var i = 0; i < arr.length; i++) {
                    if (min > arr[i]) {
                        min = arr[i];
                        index = i;
                    }
                }
                return index;
            },
            sortMuliti(multiArr,startPos){//将多线中的二维数组进行排序
                this.diguiCount = 0;
                var _this = this;
                _this.finalMergeArr.length = 0;
                return sortLine(multiArr,startPos)
                function sortLine(multiArr,startPos){
                    if(_this.diguiCount>=multiArr.length){
                        return;//此处递归结束
                    }
                    let arrStartLon,arrStartLat,arrEndLon,arrEndLat;
                    let finalMulit = [];
                    let makeArr = [];
                    for(let i = 0;i<multiArr.length;i++){
                        if(multiArr[i]!=undefined){
                            makeArr.push({
                                'index':i,
                                'makeArr':multiArr[i],
                                'lineStartPos':multiArr[i][0],
                                'lineEndPos':multiArr[i][multiArr[i].length-1]
                            })
                        }
                    }
                    let startLen,endLen;
                    let lenArr = [];
                    let mediumArr = []
                    for(let i = 0;i<makeArr.length;i++){////获取到三条线分别的起点和终点
                        //利用起点分别算出距离
                        startLen = twoPointsLength([[startPos[0],startPos[1]],makeArr[i].lineStartPos])//0和1
                        endLen = twoPointsLength([[startPos[0],startPos[1]],makeArr[i].lineEndPos])
                        lenArr.push(startLen)
                        lenArr.push(endLen)
                        mediumArr.push({
                            'index':makeArr[i].index,
                            'startAndEndLen':[startLen,endLen],
                            'Arr':makeArr[i].makeArr
                        })
                    }
                    let minIndex = _this.getMinIndex(lenArr);
                     let config = [//lenArr中序号和真实multiArr的index索引对应
                        {0:0},{1:0},{2:1},{3:1},{4:2},{5:2},{6:3},{7:3},{8:4},{9:4},{10:5},{11:5},{12:6},{13:6},{14:7},{15:7},{16:8},{17:8},{18:9},{19:9}
                        ,{20:10},{21:10},{22:11},{23:11},{24:12},{25:12},{26:13},{27:13},
                    ]
                    let getMulitiArrIndex;
                    for(let i = 0;i<config.length;i++){
                        if(minIndex==i){
                            getMulitiArrIndex = config[i][minIndex]
                        }
                    }
                    let getIndex = mediumArr[getMulitiArrIndex].index
                    let getFirstLine = multiArr[getIndex];
                    let len1,len2;
                    len1 = twoPointsLength([[startPos[0],startPos[1]],getFirstLine[0]])
                    len2 = twoPointsLength([[startPos[0],startPos[1]],getFirstLine[getFirstLine.length-1]])
                    if(len1<=len2){//不需要反转
                    }else{//反转
                        getFirstLine.reverse()
                    }
                    _this.finalMergeArr.push(getFirstLine);
                    _this.diguiCount++;//自加1
                    delete multiArr[getIndex];//不改变索引值
                    sortLine(multiArr,getFirstLine[getFirstLine.length-1]);//获取到第一条线的终点
                }
            },
            remove(array,index){//js 移除数组指定索引
                if(index<=(array.length-1)){ 
                    for(var i=index;i<array.length;i++){ 
                    array[i]=array[i+1]; 
                    } 
                }
                else{ 
                    throw new Error('超出最大索引！'); 
                } 
                array.length=array.length-1; 
                return array; 
            },
            diguiMulti(){
                this.diguiCount = 0;
                /*
                    多线的首位相接处理方式：
                    1. 先全部处理成数组。
                    2. 全体数组数>3个单独处理(2个的情况也类似)
                    3. *****以起始点为判断点，分别求出各个数组中首位和末尾与其差值最小的。找到插值最小的数组，判断是首位还是末尾，是首位不反转，末尾反转
                    4. 找到差值最小的数组，以终点为判断依据，继续查找其他数值，直到全部重合，最多四个数组吧。
                */
                var _this = this;
                makeFinalMergeArr()
                function makeFinalMergeArr(){
                    if(_this.diguiCount>=multiArr.length){
                        return;//此处递归结束
                    }
                    let arrStartLon,arrStartLat,arrEndLon,arrEndLat;
                    let finalMulit = [];
                      let makeArr = [];
                    for(let i = 0;i<multiArr.length;i++){//此处的循环是获取到各个数组的头尾经纬度坐标
                       for(let j = 0;j<multiArr[i].length;j++){ //获取到各个多个多线数组中头部和尾部
                            let chazhiArr = [];
                            if(j == 0){
                               arrStartLon = multiArr[i][j][0]
                              //arrStartLat = multiArr[i][j][1]
                            }
                            if(j ==multiArr[i].length-1){
                              arrEndLon = multiArr[i][j][0]
                              //arrEndLat = multiArr[i][j][1]
                            }
                            
                       }
                    }
                    //    //根据获取到的起始点(也可以是各个数组的起点)与上面循环获取到的获取到各个多个多线数组中头部和尾部进行判断比较反转
                    //    if(Math.abs(arrStartLon-startPos[0])<=Math.abs(arrEndLon-startPos[0])){//此种情况说明不需要反转
                    //             // multiArr[i]
                    //     }else{//需要反转multiArr[i]
                    //             // multiArr[i].resolve();
                    //     }
                    //    finalMulit.push(multiArr[i]);    
                    // }
                    this.diguiCount++;//自加1
                }
            },
            mergeArray(arr1, arr2){ 
                for (var i = 0 ; i < arr1.length ; i ++ ){
                    for(var j = 0 ; j < arr2.length ; j ++ ){
                        if (arr1[i] === arr2[j]){
                        arr1.splice(i,1); //利用splice函数删除元素，从第i个位置，截取长度为1的元素
                        }
                    }
                }
                //alert(arr1.length)
                for(var i = 0; i <arr2.length; i++){
                    arr1.push(arr2[i]);
                }
                return arr1;
            },
            findTarget(targetLayerArr,nearestStartPoint){
                for(var j = 0;j<targetLayerArr.length;j++){
                    let lineStringArr = targetLayerArr[j].getSource().getFeatures()[0].getGeometry().getCoordinates();
                    for(var k = 0;k<lineStringArr.length;k++){
                        if(nearestStartPoint[0]==lineStringArr[k][0]
                        &&nearestStartPoint[1]==lineStringArr[k][1]){
                            return targetLayerArr[j];
                            // this.findLineArr.push(targetLayerArr[j]);
                        }    
                    }
                }
            },
            arrayHasElement(array, element) {  
                for (var el of array) {
                    if (el.length === element.length) {
                    for (var index in el) {
                        if (el[index] !== element[index]) {
                            break;
                        }
                        if (index == (el.length - 1)) {    // 到最后一个元素都没有出现不相等，就说明这两个数组相等。
                            return el;
                        }
                    }
                    }
                }
                // return false;
            },
            getmaxscore(arrayobj){
                var maxi=0
                for (var i=0;i<arrayobj.length;i++){
                    if (arrayobj[maxi].len>=arrayobj[i].len)
                    {
                        maxi=i;
                    }
                }
                return maxi;
            },
            AddturfLineString(frontObj,carType,y,x,final,geojsonFormat){
                // let linestringEnd = turf_linestring([[y,x],final[0].coord], { id: carType })
                // let featuresEnd = geojsonFormat.readFeatures(linestringEnd)
                //     let bufferLineEnd = featuresEnd[0]
                //     let data_lineEnd = new VectorSource()
                //     data_lineEnd.addFeature(bufferLineEnd);
                //     let bufferLayerEnd = new VectorLayer({
                //         id: carType,
                //         source: data_lineEnd,
                //         style: new Style({
                //             stroke: new Stroke({
                //                 color: frontObj.roadStyle.lineColor,
                //                 width: frontObj.roadStyle.lineWidth
                //             })
                //         })
                //     })
                //     frontObj.map.addLayer(bufferLayerEnd)
                let result = [[y,x],final[0].coord];
                let finalResult = [];
                for(let i = 0;i<result.length;i++){
                    finalResult.push(fromLonLat([result[i][0],result[i][1]]))
                }
                let linestringFinal = new LineString(finalResult);
                let bufferLine = new Feature({
                            id: carType,
                            type: 'route',
                            geometry: linestringFinal
                })
                let data_line = new VectorSource()
                data_line.addFeature(bufferLine);
                let bufferLayer = new VectorLayer({
                    id:carType,
                    source: data_line,
                    style: new Style({
                        stroke: new Stroke({
                            color: frontObj.roadStyle.lineColor,
                            width: frontObj.roadStyle.lineWidth
                        })
                    })
                })
                frontObj.map.addLayer(bufferLayer)
            },
            compare(property){
                return function(a,b){
                    var value1 = a[property];
                    var value2 = b[property];
                    return value1 - value2;
                }
            },
            orderString(stringArray){
                  let arr = stringArray.split(" ");
                  let lon = parseFloat(arr[0]);
                  let lat = parseFloat(arr[1]);
                  this.geoArray.push([lon, lat])
                  //this.arrAll.push([lon, lat]);    
            },
            showMediumNodeLen4(nodeArr,carType,frontObj,typeObject){
                this.startNode = typeObject.startNode
                this.startNode  = typeObject.endNode
                this.startNode  = typeObject.nodeCount
                this.startNode = new Style({
                            image: new Icon({
                                anchor: [0.5, 1],
                                src: frontObj.startIcon
                            }),
                            text: new Text({
                                font: "bold 12px 黑体",
                                text: "起点",
                                fill: new Fill({
                                    color: "#aa3300"
                                }),
                                stroke: new Stroke({
                                    color: "#fff",
                                    width: 2
                                }),
                                textAlign: "left"
                            })
                        })
                this.endNode = new Style({
                            image: new Icon({
                                anchor: [0.5, 1],
                                src: frontObj.endIcon
                            }),
                            text: new Text({
                                font: "bold 12px 黑体",
                                text: "终点",
                                fill: new Fill({
                                    color: "#aa3300"
                                }),
                                stroke: new Stroke({
                                    color: "#fff",
                                    width: 2
                                }),
                                textAlign: "left"
                            })
                        })
                this.nodeCount = new Style({
                            image: new Circle({
                                radius: frontObj.nodeCircle,
                                stroke: new Stroke({
                                    color: "#FF5809",
                                    width: 2
                                }),
                                fill: new Fill({
                                    color: "#FF5809"
                                })
                            }),
                            text: new Text({
                                font: frontObj.nodeText,
                                text: "",
                                fill: new Fill({
                                    color: 'rgba(255,255,255,1)'
                                })
                            })
                        })
                for(let i = 0;i<nodeArr.length;i=i+1){
                    if(i==(nodeArr.length-1)){//终点
                        let endMarker = this.featureSymbol('','',typeObject.endNode,typeObject.endNode,new Point(wgs84Toweb3857([nodeArr[nodeArr.length-1].Y,nodeArr[nodeArr.length-1].X])),frontObj.routArr[i].attributes)
                        let endNodeMarker = new VectorSource()
                        endNodeMarker.addFeature(endMarker);
                        let endLayer = new VectorLayer({
                            id: typeObject.endNode,
                            style: this.endNode,
                           source: endNodeMarker
                        });
                        endLayer.setZIndex(frontObj.endIndex)
                        frontObj.map.addLayer(endLayer);
                    }else if(i==0){//起点
                        let startMarker = this.featureSymbol('','',typeObject.startNode,typeObject.startNode,new Point(wgs84Toweb3857([nodeArr[0].Y,nodeArr[0].X])),frontObj.routArr[i].attributes)
                        let startNodeMarker = new VectorSource()
                        startNodeMarker.addFeature(startMarker);
                        let startLayer = new VectorLayer({
                            id: typeObject.startNode,
                            style: this.startNode,
                           source: startNodeMarker
                        });
                        startLayer.setZIndex(frontObj.startIndex)
                        frontObj.map.addLayer(startLayer);
                    }else{
                        this.addMediumNode(typeObject.nodeCount,nodeArr[i].attributes.index + 1,nodeArr[i].attributes,wgs84Toweb3857([parseFloat(nodeArr[i].attributes.info.longitude),parseFloat(nodeArr[i].attributes.info.latitude)]),frontObj,typeObject)
                        //this.addMediumNode(typeObject.nodeCount,nodeArr[i+1].attributes.index + 1,nodeArr[i + 1].attributes,[parseFloat(nodeArr[i+1].attributes.info.longitude),parseFloat(nodeArr[i+1].attributes.info.latitude)],frontObj,typeObject)
                    }
                }
            },
            buildArray(stringArray,y2,x2,y1,x1,array,typeObject){
                let arr = stringArray.split(" ");
                let lon = parseFloat(arr[0]);
                let lat = parseFloat(arr[1]);
                 if(this.addCount==0){
                    this.geoAndarr([y1,x1],[lon,lat])
                }else if(this.addCount==array.length-1){
                     this.geoAndarr([lon,lat],[y2,x2])
                }else if(!typeObject.isDirectConnect){//非直连的话走路网
                    this.arrAll.push([lon,lat]);
                    this.geoArray.push([lon,lat])
                }
            },
            findRoadZY(map,tablename,name,serverUrl,roadstyle){
                var _this = this
                return new Promise(function(resolve) {
                    var postData = {
                        "data": [{
                            'name':name,
                            "tableName": tablename
                        }]
                    }
                    axios.post(serverUrl, qs.stringify(postData), {
                                headers: {
                                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                                }
                    }).then(res => {
                        let linePointArr = res.data;
                        for(var i = 0;i<linePointArr.length;i++){
                            let x1 = linePointArr[i].y1
                            let y1 = linePointArr[i].x1
                            let x2 = linePointArr[i].y2
                            let y2 = linePointArr[i].x2
                            let route = new LineString([[y1,x1],[y2,x2]]);
                            let feature =  _this.featureSymbol('findroad','',"route",'',route,'')
                            let find_line = new VectorSource()
                            find_line.addFeature(feature);
                            let lineLayer = new VectorLayer({ //轨迹线的相关图层每次创建内存地址不一样，可以在图层中添加
                                id: 'findroad',
                                source: find_line,
                                style: new Style({ // 线串的样式
                                    stroke: new Stroke({
                                        color:roadstyle.lineColor,
                                        width:roadstyle.lineWidth
                                    })
                                })
                            })
                            map.addLayer(lineLayer)
                            // return lineLayer;
                            resolve(lineLayer);
                        }
                    }, err => {
                    })
                })
            },
              findRoad(map,tablename,name,name1,serverUrl,roadstyle){
                    this.findlineAll.length = 0;
                    this.lineArr.length = 0;
                    this.lineArr2.length = 0;
                    this.firstName = name;
                    this.endName = name1;
                    var _this = this;
                    var postData = {
                        "data": [{
                            'name':name,
                            'name1':name1,
                            "tableName": tablename
                        }]
                    }
                    axios.post(serverUrl, qs.stringify(postData), {
                                headers: {
                                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                                }
                    }).then(res => {
                        let firstname = _this.firstName
                        let endname = _this.endName
                        let linePointArr = res.data;
                        for(var i = 0;i<linePointArr.length;i++){
                            let x1 = linePointArr[i].y1
                            let y1 = linePointArr[i].x1
                            let x2 = linePointArr[i].y2
                            let y2 = linePointArr[i].x2
                            let route = new LineString([[y1,x1],[y2,x2]]);
                            // if(linePointArr[i].name==firstname){
                            //     _this.lineArr.push( turf_linestring([[y1,x1],[y2,x2]]))
                            
                            // }else{
                            //     _this.lineArr2.push( turf_linestring([[y1,x1],[y2,x2]]))
                            // }
                            if(linePointArr[i].name.indexOf(firstname)>-1){
                                _this.lineArr.push( turf_linestring([[y1,x1],[y2,x2]]))
                            
                            }else{
                                _this.lineArr2.push( turf_linestring([[y1,x1],[y2,x2]]))
                            }
                            let feature =  this.featureSymbol('findroad','',"route",'',route,'')
                            let find_line = new VectorSource()
                            find_line.addFeature(feature);
                            let lineLayer = new VectorLayer({ //轨迹线的相关图层每次创建内存地址不一样，可以在图层中添加
                                id: 'findroad',
                                source: find_line,
                                style: new Style({//线串的样式
                                    stroke: new Stroke({
                                        color:roadstyle.lineColor,
                                        width:roadstyle.lineWidth
                                    })
                                })
                            })
                            //map.getView().fit(find_line.getExtent(),15)
                            map.addLayer(lineLayer)
                        }
                        for(var i= 0;i<_this.lineArr.length;i++){
                            for(var j = 0;j<_this.lineArr2.length;j++){
                                let intersects = line_intersect(_this.lineArr[i], _this.lineArr2[j]);
                                if(intersects.features.length!=0){
                                    _this.findlineAll.push(intersects);
                                }
                            }
                        }
                        let config =  {
                            "id":'intersectPoi',
                            "scale":0.9,
                            "zIndex":10,
                            "img":'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABMAAAAfCAYAAAAFkva3AAACd0lEQVR42qWU3UuTYRjG34iiw+gk6CAp2XRqsyazWRuz8c656UF/QV8URhQSNaMP5kzRudQ5Zy3zD+i0gygiZ44oogjDJJBqjMTS1Gxzm1s17+4rYmBzbXt38OPhue/r+jEG7yMQURoWZ2QHY2XGmBkm8ff0Y479er01F3N3eBPTzsQs7gQ1eJPUOETUOMzwiTvm2COH/LqyekdoK+Mz98ep4Q4XhzODPXKcH2W2rZGZupY2MiP17hWycDBXkOfec2ZzSlbXuWg39UXJPER5gx76BJmxY347EzPx/1HHy3xBD314BLF97qLYs0zG26uSQZ89VsHQ9mVUHFgh0ZuUDPrwCIfsM3OGmz/I4P0lGfTZMyvU2qaTtbd+UqHAI+ivBZf1gwnSs10q6LMnLOiuBsZ1rgjpeCCZ/gix542gvfLerXXM00FPXDJaxwKxxyMcuDSlqbEFSeNZkQz68Pz5Ampa3o3t75yl6oFY3qCHfupz0lgnS5i42hUmtTuaM8ijh35KBqovTLSp7Z+oqj+aM8ijl/YEqc+Pb2ECqq6vtM8VyQpyyKOXJgNVza8Pqy5PkbJvOSvIIZ/xpQWqcy9HKvnnV/SGM4I953zI/1e29+wLJZMs7w1RJrBHLqsMVJ55drfCFiBFz/c0MMceuZxkytNPy5hV+Y0l+hfMsc9ZBvY0+e+VtgZJ5vyWAnfMsc9LVn7qiahofkXFzsUUuGOet6zspG8D87G44zPt7l4gnLhjnrcMKE48tsmsb6mIXwWcfG/FXJKs9PijUnmTn3byE4UTd8kyUHLs4Yei69OEE/eCZPKjDwZ3tUwSzoJlsiP3RSbEGLNlfwPf80fNP6DL+QAAAABJRU5ErkJggg==',
                            }
                        if(_this.findlineAll!=undefined){
                            addVector(_this.findlineAll[0].features,map,config)
                        }
                    }, err => {
                    })
            },
            geoAndarr(pos,pos1){
                this.arrAll.push(pos);
                this.geoArray.push(pos);
                this.arrAll.push(pos1);
                this.geoArray.push(pos1);
            },
            roadStringArray(stringArray,y2,x2,y1,x1,array,typeObject){
                if (this.multiFlag) {//多线为直接连接起点和终点
                    this.arrAll.push([y1,x1]);//末尾
                    this.arrAll.push([y2,x2]);//首位
                    this.geoArray.push([y1,x1])
                    this.geoArray.push([y2,x2])
                } else {//-----单线情况
                    if(this.reverseFlag){//为翻转情况
                       this.buildArray(stringArray,y2,x2,y1,x1,array,typeObject)

                    }else{//正常情况
                       this.buildArray(stringArray,y2,x2,y1,x1,array,typeObject)
                    }
                    this.addCount++;
                }
            },
            sum(arr) {
                var s = 0;
                for (var i = arr.length - 1; i >= 0; i--) {
                    s += arr[i];
                }
                return s;
            },
            styleFunction(feature) {
                //let _style = null
                for (var i = 0; i < this.nodeCountArr.length; i++) {
                    // if (feature.values_.id == this.nodeCountArr[i].carType) {
                    if (feature.values_.id ==  this.nodeType) {
                        if (feature.get('type') === this.nodeType) {
                            if (feature.values_.order == 1 || feature.values_.order == Math.round(this.nodeCountArr[i].roadArr.length / 2)+1) {} else {
                                this._styleNode = this.nodeCount
                                if (feature.get("order")) {
                                    this._styleNode.getText().setText(feature.get("order") + '')
                                }
                            }
                        }
                        return this._styleNode
                    }
                }
            },
            addFeature(name, attr, geo, type, vectors) {
                //此处加个if判断
                let nodeMarkerCommon = new Feature({
                    type: type,
                    name: name,
                    geometry: geo,
                    attributes: attr
                })
                vectors.push(nodeMarkerCommon)
            },
            featureSymbol(id,order,type,name,geometry,attributes){
                return  new Feature({
                        id: id,
                        order: order,
                        type: type,
                        name: name,
                        geometry: geometry,
                        attributes: attributes
                })
            },
            vectorLayerSymbol(id,name,source,style){
                return new VectorLayer({ //轨迹线的相关图层每次创建内存地址不一样，可以在图层中添加
                            id: id,
                            name: name,
                            source: source,
                            style: style
                        })
            },
            vectorLayerSymbolNode(id,name,source,frontObj,order){
                return new VectorLayer({ //轨迹线的相关图层每次创建内存地址不一样，可以在图层中添加
                            id: id,
                            name: name,
                            source: source,
                            style:  new Style({
                                    image: new Circle({
                                        radius: frontObj.nodeCircle,
                                        stroke: new Stroke({
                                            color: "#FF5809",
                                            width: 2
                                        }),
                                        fill: new Fill({
                                            color: "#FF5809"
                                        })
                                    }),
                                    text: new Text({
                                        font: frontObj.nodeText,
                                        text: order+"",
                                        fill: new Fill({
                                            color: 'rgba(255,255,255,1)'
                                        })
                                    })
                        })
                        })
            },
            addMediumNode(carType,order,attr,arr,frontObj,typeObject){
                if(attr.info.timeflag!=undefined&&attr.info.timeflag=="passNode"){//如果是拖拽的中间节点
                        // let lon = evt.target.lastPointerEvent_.coordinate[0]
                        // let lat = evt.target.lastPointerEvent_.coordinate[1]
                        let passNode = new Style({
                            geometry: new Point([attr.info.longitude,attr.info.latitude]),
                            image: new Icon({
                                anchor: [0.5, 1],
                                scale:0.12,
                                src:'data:image/png;base64, '
                            })
                        })
                        var passNodeId = 'passNode'
                        let passNodeLayer = new VectorLayer({
                           id: passNodeId,
                           style: passNode,
                           source: this.line_layer.getSource()
                        });
                        passNodeLayer.setZIndex(frontObj.passNodeIndex)
                        frontObj.map.addLayer(passNodeLayer);
                }else{
                    let data_medium = new VectorSource();
                    data_medium.addFeature(this.featureSymbol(carType,order,typeObject.nodeCount,typeObject.nodeCount,new Point(arr),attr));
                    let node_layer;
                    if(typeObject.isNumber){//在此处直接添加序号，不用回调
                            //node_layer = this.vectorLayerSymbolNode(carType,typeObject.nodeCount,data_medium,this.styleFunction)
                            node_layer = this.vectorLayerSymbolNode(carType,typeObject.nodeCount,data_medium,frontObj,order)
                        }else{
                            let iconStyle = new Style({
                                image: new Icon({
                                    anchor: [0.5, 1],
                                    src: frontObj.nodeIcon,    // 设置Image对象
                                    scale: frontObj.nodeScale    // 及图标大小
                                })
                            })
                            node_layer = this.vectorLayerSymbol(carType,typeObject.nodeCount,data_medium,iconStyle)
                        }
                        node_layer.setZIndex(frontObj.nodeIndex)
                        frontObj.map.addLayer(node_layer)
                }
            },
             // 构建svg的Image对象
            // var svg = '<svg width="15px" height="15px" viewBox="0 0 15 15" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><title>Group 3</title><desc>Created with Sketch.</desc><defs></defs><g id="页面1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"><g id="以图识图_动态结果_轨迹" transform="translate(-751.000000, -630.000000)" fill="#126BD4"><g id="Group-3" transform="translate(751.000000, 630.000000)"><circle id="椭圆形复制-5" opacity="0.49882" cx="7.5" cy="7.5" r="7.5"></circle><circle id="椭圆形复制-6" cx="7.5" cy="7.5" r="4.5"></circle></g></g></g></svg>';
            // var mysvg = new Image();
            // mysvg.src = 'data:image/svg+xml,' + escape(svg);
            // let iconStyle = new Style({
            //     image: new Icon({
            //         img: mysvg,    // 设置Image对象
            //         imgSize: [30, 30]    // 及图标大小
            //     })
            // })
            // addMediumNode(carType,order,attr,arr,frontObj,typeObject){
            //     let data_medium = new VectorSource();
            //     data_medium.addFeature(this.featureSymbol(carType,order,typeObject.nodeCount,typeObject.nodeCount,new Point(arr),attr));
            //     let node_layer = this.vectorLayerSymbol(carType,typeObject.nodeCount,data_medium,this.styleFunction)
            //     node_layer.setZIndex(frontObj.nodeIndex)
            //     frontObj.map.addLayer(node_layer)
            // },
            addNumberNode(pos,frontObj,i){
                let nodeMarkerCommon = new Feature({
                    geometry: new Point([pos[0],pos[1]]),
                })
                let medium_node = new VectorSource({})
                medium_node.addFeature(nodeMarkerCommon);
                let mediumLayer = new VectorLayer({
                        id:'mediumNode',
                        source: medium_node,
                        style:  new Style({
                            image: new Circle({
                                radius: frontObj.nodeCircle,
                                stroke: new Stroke({
                                    color: "#FF5809",
                                    width: 2
                                }),
                                fill: new Fill({
                                    color: "#FF5809"
                                })
                            }),
                            text: new Text({
                                font: frontObj.nodeText,
                                text: i+"",
                                fill: new Fill({
                                    color: 'rgba(255,255,255,1)'
                                })
                            })
                        })
                })
                mediumLayer.setZIndex(12)
                frontObj.map.addLayer(mediumLayer)
            },
            addNode(vectors, arr, startName, endName, frontObj, num, carType,typeObject) {
                for (var i = 0; i < arr.length; i++) {
                    if (i == 0) {
                        //this.addMediumNode(carType,this.arr[this.countIndex].attributes.index + 1,frontObj.routArr[this.countIndex].attributes,[parseFloat(frontObj.routArr[this.countIndex].attributes.info.longitude),parseFloat(frontObj.routArr[this.countIndex].attributes.info.latitude)],frontObj)
                        if (startName === "node") {
                            // if(frontObj.routArr[this.countIndex]==undefined){
                            //     return;
                            // }
                            this.addFeature(typeObject.startNode + (this.countIndex).toString(), frontObj.routArr[this.countIndex].attributes, new Point(arr[i]), 'node', vectors)
                        } else {
                            //  if(frontObj.routArr[this.countIndex]==undefined){
                            //     return;
                            // }
                            if (num === 1) {
                                this.addFeature(startName + (this.countIndex).toString(), frontObj.routArr[this.countIndex].attributes, new Point(arr[i]), startName, vectors)
                            } else {
                                this.addFeature(startName + (this.countIndex).toString(), frontObj.routArr[this.countIndex].attributes, new Point(arr[i]), startName, vectors)
                            }
                        }
                    } else if (i == arr.length - 1) {
                        //this.addMediumNode(carType,this.arr[this.countIndex+1].attributes.index + 1,frontObj.routArr[this.countIndex + 1].attributes,[parseFloat(frontObj.routArr[this.countIndex+1].attributes.info.longitude),parseFloat(frontObj.routArr[this.countIndex+1].attributes.info.latitude)],frontObj)
                        if (endName === "node") {
                            //  if(frontObj.routArr[this.countIndex + 1]==undefined){
                            //     return;
                            // }
                            if (this.countIndex === 1) {
                                this.addFeature(typeObject.endNode + (this.countIndex + 1).toString(), frontObj.routArr[this.countIndex + 1].attributes, new Point(arr[i]), 'node', vectors)
                            } else {
                                this.addFeature(typeObject.endNode + (this.countIndex + 1).toString(), frontObj.routArr[this.countIndex + 1].attributes, new Point(arr[i]), 'node', vectors)
                            }
                        } else {
                            //  if(frontObj.routArr[this.countIndex + 1]==undefined){
                            //     return;
                            // }
                            if (num === 1) {
                                this.addFeature(endName + (this.countIndex + 1).toString(), frontObj.routArr[this.countIndex + 1].attributes, new Point(arr[i]), endName, vectors)
                            } else {
                                this.addFeature(endName + (this.countIndex + 1).toString(), frontObj.routArr[this.countIndex + 1].attributes, new Point(arr[i]), endName, vectors)
                            }
                        }
                    }
                }
            },
            initRoute(map, arr, arrAll, initData, frontObj, carType,typeObject) {
                let vectors = [];
                this.line_layer = {}
                vectors.length = 0;
                if (arr.length != 1) {
                    this.route = new LineString(arr);
                    this.routeAll = new LineString(arrAll);
                    //获取直线的坐标
                    this.routeFeature = this.featureSymbol(carType,'','route','',this.route,'')
                    let data_line = new VectorSource()
                    data_line.addFeature(this.routeFeature);
                    this.line_layer = new VectorLayer({ //轨迹线的相关图层每次创建内存地址不一样，可以在图层中添加
                        id: carType,
                        source: data_line,
                        // style: this.styleLineFunction
                        style:new Style({ // 线串的样式
                                stroke: new Stroke({
                                    color: frontObj.roadStyle.lineColor,
                                    width: frontObj.roadStyle.lineWidth
                                })
                            })
                    })
                    // map.getView().fit(data_line.getExtent(),frontObj.lineZoom)
                    this.line_layer.setZIndex(frontObj.routeIndex)
                    /*此处为需要编辑轨迹的代码*/
                    var _this = this;
                    /*此处为需要编辑轨迹的代码*/
                    map.addLayer(this.line_layer)
                    let popArray = this.routeFeature.getGeometry().getCoordinates();
                    let lengthArray = [];
                    for (var i = 0; i < popArray.length; i++) {
                        if (!popArray[i].includes(NaN)) {
                            lengthArray.push(popArray[i])
                        }
                    }
                    let turfString = turf_linestring(lengthArray)
                    let lineLength = turf_length(turfString, {
                        units: 'kilometers'
                    })
                    this.lenCountArray.push(lineLength);
                    let allLen = this.sum(this.lenCountArray)
                    this.lenArray.push({
                        "length": allLen,
                        "position": {
                            "X": initData.posArray[1].X,
                            "Y": initData.posArray[1].Y
                        },
                        "carType": carType
                    });
                    let obj = {
                        length: lineLength,
                        array: this.routeFeature.getGeometry().getCoordinates()
                    }
                    this.allPathArray.push(obj)
                    this.routeAllFeature = this.featureSymbol(carType,'','route','',this.routeAll,'')
                    let num = Math.round(this.arr.length / 2);
                    this.secondFlag = true
                        //获取直线的坐标
                    this.routeCoords = this.route.getCoordinates();
                    this.routeLength = this.routeCoords.length;
                    this.styles = {//car
                        'geoMarker': new Style({
                            image: new Icon({
                                src: frontObj.carIcon,
                                rotateWithView: false,
                                rotation: -Math.atan2(this.routeCoords[0][1] - this.routeCoords[1][1], this.routeCoords[0][0] - this.routeCoords[1][0]),
                                scale: this.startObj.carScale
                            })
                        })
                    };
                    var _this = this;
                    _this.vectorLayer = new VectorLayer({
                        id: carType,
                        style: function(feature) {
                            let _style = null
                            if (feature.get('type') === typeObject.startNode) {
                                _style = _this.startNode
                            }
                            if (feature.get('type') === typeObject.endNode) {
                                _style =  _this.endNode
                            }
                            return _style
                        },
                        source: new VectorSource({
                            features: vectors
                        })
                    });
                    map.addLayer(_this.vectorLayer);
                } else {
                    if(this.countIndex==this.arr.length-2){//endNode
                        let endMarker = this.featureSymbol('','',typeObject.endNode,typeObject.endNode,new Point([this.arrAll[this.arrAll.length-1][0],this.arrAll[this.arrAll.length-1][1]]),frontObj.routArr[this.countIndex + 1].attributes)
                        let endNodeMarker = new VectorSource()
                        endNodeMarker.addFeature(endMarker);
                        let endLayer = new VectorLayer({
                            id: carType,
                            style: this.endNode,
                           source: endNodeMarker
                    });
                     map.addLayer(endLayer);
                    }else{
                    }
                    this.countIndex = this.countIndex + 2
                }
            },
            start(carType, carzIndex, frontObj,carFlag) { //此处需要给出点击的是第几个小车，this.arr为前端传递过来的坐标值(需要找到对应的)
                if (this.arr.length == 0) {
                    alert("请先生成车辆路径");
                } else {
                    this.flashingArr.length = 0;
                    this.initObject_P()
                    this.frontObject = frontObj;
                    this.stopFlag = false;
                    this.indexCir = 0;
                    if (!this.animating) {
                        this.animating = true
                        let index = this.start_index || 1
                        this.startAnimation(index, carType, carzIndex,carFlag);
                    }
                }
            },
            styleLineFunction(feature, res) {
                var trackLine = feature.getGeometry(); //轨迹线图形
                for (var i = 0; i < this.colorArr.length; i++) {
                    if (feature.values_.id == this.colorArr[i].carType) {
                        var styles = [
                            new Style({ // 线串的样式
                                stroke: new Stroke({
                                    color: this.colorArr[i].roadStyle.lineColor,
                                    width: this.colorArr[i].roadStyle.lineWidth
                                })
                            })
                        ];
                    }
                }
                return styles;
            },
            duplicate(arr) {
                let res = {}
                arr.forEach(item => {
                    item.sort((b, a) => b - a);
                    res[item] = item;
                });
                return Object.values(res)
            },
            delete(delIndex) {
                var temArray = [];
                for (var i = 0; i < this.length; i++) {
                    if (i != delIndex) {
                        temArray.push(this[i]);
                    }
                }
                return temArray;
            },
            flashingPoint(carType) {
                for (var i = 0; i < this.lenArray.length; i++) {
                    if (this.lenArray[i].carType == carType) {
                        this.flashingArr.push(this.lenArray[i])
                    }
                }
                if (this.indexCir >= this.flashingArr) {
                    return
                } else {
                    for (this.indexCir < this.flashingArr.length;;) {
                        removeOverLayeById(this.startObj.map, 'Alarm')
                        if (this.flashingArr[this.indexCir] == undefined) {
                            if (this.timer) {
                                clearTimeout(this.timer);
                            }
                            return
                        }
                        if (this.perDistance <= this.flashingArr[this.indexCir].length) {
                            let pos = this.flashingArr[this.indexCir].position;
                            removeOverLayeById(this.startObj.map, 'Alarm')
                            this.$emit('roadFinish', this.indexCir + 2)
                                //此次的pos亮
                            addAlarmFlash(this.startObj.map, {
                                geom: {
                                    points: "" + pos.Y + ", " + pos.X + "",
                                    type: 'Point'
                                },
                                attributes: {
                                    id: 'Alarm'
                                },
                                symbol: {
                                    image: {
                                        src: this.startObj.gifUrl,
                                        size: [0, 0]
                                    }
                                }
                            })
                            break;
                        } else {
                            this.indexCir++;
                            if (this.indexCir > this.flashingArr.length - 1) {
                                break;
                            }
                            //其余的pos不亮
                            removeOverLayeById(this.startObj.map, 'Alarm')
                        }
                    }
                }
            },
            addCar(point,source,carzIndex,carFlag){
                var feature = new Feature(point);
                source.addFeature(feature);
                clearSpatial(carFlag, this.startObj.map)//import直接引入的不需要加this
                let car_layer = this.vectorLayerSymbol(carFlag,'',source,this.styles.geoMarker)
                car_layer.setZIndex(carzIndex)
                this.startObj.map.addLayer(car_layer)
            },
            startAnimation(index, carType, carzIndex,carFlag) {
                var _this = this;
                let speed = _this.startObj.speed;
                if (!_this.animating) { //点击开始
                    _this.start_index = index;
                    return
                }
                //设置显示范围
                _this.timer = setTimeout(() => { //index为运行到的第几个位置
                    if (!_this.stopFlag) {
                        _this.perDistance = speed * index / 1000; //第一次0.1km,第二次0.2km......
                    }
                    _this.routeAll = new LineString(_this.arrAll);
                    let routeAllFea = new Feature({ //line_data
                        id: carType,
                        type: 'route',
                        geometry: _this.routeAll
                    });
                    let lineAll_str = turf_linestring(routeAllFea.getGeometry().getCoordinates())
                    let lineAll_length = turf_length(lineAll_str, {
                        units: 'kilometers'
                    })
                    _this.flashingPoint(carType)
                    if (_this.perDistance >= lineAll_length) { // 运动完毕32.22026489307822km
                        _this.start_index = null;
                        _this.animating = false;
                        var endPoint = new Point(_this.arrAll[this.arrAll.length - 1]);
                        let data_end = new VectorSource()
                         _this.finished = true
                        _this.addCar(endPoint,data_end,carzIndex,carFlag)
                        _this.$emit('finish', _this.finished)
                       
                        return;
                    } else {
                        let old_p = _this.movePos.getGeometry().getCoordinates();
                        let new_p = turf_along(lineAll_str, _this.perDistance, {
                            units: 'kilometers'
                        }).geometry.coordinates
                        //此处进行线路的标红操作
                        // lineShowDistant('redLine',old_p,new_p,{"lineWidth":6,"lineColor":'#FF0000'},0,_this.startObj.map)
                        _this.movePos.setGeometry(new Point(new_p)) //movePos初始位置
                        let dx = old_p[0] - new_p[0];
                        let dy = old_p[1] - new_p[1];
                        _this.rotation = Math.atan2(dy, dx); //从一个点移动到下一个点的旋转角度
                        _this.styles.geoMarker.getImage().setRotation(-_this.rotation); //carStyle对象已经初始化过了
                        var currentPoint = new Point(new_p);
                        var feature = new Feature(currentPoint);
                        let data_c = new VectorSource()
                        data_c.addFeature(feature);
                        clearSpatial("car", _this.startObj.map)
                        let car_layer = _this.vectorLayerSymbol('car', '', data_c, _this.styles.geoMarker)
                        car_layer.setZIndex(carzIndex)
                        _this.startObj.map.addLayer(car_layer)
                        // _this.addCar(currentPoint,data_c,carzIndex,carFlag)
                        index++
                        _this.finished = false
                        _this.startAnimation(index);
                        _this.$emit('finish', _this.finished)
                        
                    }
                }, 500)
                _this.$emit('timer', _this.timer)
            },
            pause() {
                this.animating = false
                if (this.timer) {
                    clearTimeout(this.timer);
                }
            },
            initObject_L() { //初始化线
                let vectors = [];
                this.route = new LineString(this.arr);
            },
            initObject_P() { //初始化点
                this.movePos = new Feature({ //第一个坐标值
                    geometry: new Point(this.arr[0])
                })
                let p_style = new Style({
                    // 设置一个标识
                    image: new Icon({
                        src: this.startObj.carIcon,
                        // 这个是相当于是进行切图了
                        // size: [50,50],
                        // 注意这个，竟然是比例 左上[0,0]  左下[0,1]  右下[1，1]
                        anchor: [0.5, 0.5],
                        // 这个直接就可以控制大小了
                        scale: 0.5,
                        // 开启转向
                        rotateWithView: true,
                        // rotation: 0,
                    }),
                    text: new Text({
                        // 对其方式
                        textAlign: 'center',
                        // 基准线
                        textBaseline: 'middle',
                        offsetY: -30,
                        // 文字样式
                        font: 'normal 16px 黑体',
                        // 文本内容
                        text: '车牌：陕A-0p1v6',
                        // 文本填充样式
                        fill: new Fill({
                            color: 'rgba(255,255,255,1)'
                        }),
                        padding: [5, 5, 5, 5],
                        backgroundFill: new Fill({
                            color: 'rgba(0,0,255,0.6)'
                        })
                    })
                })
                this.movePos.setStyle(p_style)
            },
            setTrackCoods(routeObj, carType) {
                this.flashingArr.length = 0;
                this.pause();
                let routeType = [];
                if (this.timer) {
                    clearTimeout(this.timer);
                }
                this.start_index = null //从头开始跑
                this.arr = routeObj.routArr //前端传递过来的节点数组
                this.initObject_P(routeObj) //初始化点的坐标
                let layersArray = routeObj.map.getLayers().array_;
                let lineAll = [];
                for (var i = 0; i < this.lenArray.length; i++) {
                    if (this.lenArray[i].carType == carType) {
                        this.flashingArr.push(this.lenArray[i])
                    }
                }
                //this.routeFeature.values_.geometry.flatCoordinates
                //清除一次图层再添加一次
                if (layersArray) {
                    for (var i = 0; i < layersArray.length; i++) { //先把source数据源清除一次
                        let type = routeObj.map.getLayers().array_[i].values_;
                        if (type.id == carType) {
                            for (var j = 0; j < type.source.getFeatures().length; j++) {
                                if (type.source.getFeatures()[j].values_.type != undefined && type.source.getFeatures()[j].values_.type == "route") {
                                    let arr = routeObj.map.getLayers().array_[i].values_.source.getFeatures()[j].getGeometry().getCoordinates()
                                        lineAll.push(arr);
                                }
                            }
                        }
                    }
                }
                let finalArr = []
                for (var i = 0; i < lineAll.length; i++) {
                    for (var j = 0; j < lineAll[i].length; j++) {
                        finalArr.push(lineAll[i][j])
                    }
                }
                this.arrAll.length = 0;
                this.arrAll = finalArr;
                if (this.routeAllFeature.setGeometry != undefined) {
                    this.routeAllFeature.setGeometry(new LineString(finalArr))
                }
            }
        }
    }
</script>
<style scoped>
    .popup {
        position: absolute;
        background-color: #e0e0e057;
        border-top-left-radius: 10px;
        border-top-right-radius: 10px;
        border-bottom-left-radius: 10px;
        border-bottom-right-radius: 10px;
        border: 1px solid #ACD6FF;
        top: 12px;
        left: 80px;
        min-width: 360px;
        height: 45px;
        padding-left: 7px;
        padding-top: 5px;
    }
</style>