4.封装工厂类以及进行require.context导入多模块

550 阅读5分钟

插件git地址为 github.com/spiritJun/T…

demo的git地址为 github.com/spiritJun/t…

场景:

我其实是先封装的工厂后封装的功能,因为没有功能业务需求谁也不会想到要做那么多东西~工厂的类名为TrackFactory。

首先需要传入的props以及__proto__方法如下图所示:

这里面几个方法可以重点说下 

1.mapDestroy只是将地图'初始化'了重新定位到了故宫并且把地图上的画线以及Marker删掉了而已并不会重新构造地图

2.轨迹画线这个drawHisTory类我其实用到了单例模式因为整个地图中只可以进行一次实例化这个构造函数,这样就方便后续的追加点的进行了也就是所谓的后端可以随时追加数据进来了

3.有一些实例化的操作其实是在这个工厂内部实施的这样就使得 用户和构造函数进行隔离 不产生耦合关系 并且在画线操作完成之后才会有后续小车移动的动画等等这样也就可以在工厂内部进行判断是否有画线完成然后把实例传入小车动画中,小车就可以获取到画线的实例数据了

4.基本上所有抛出的方法以及画线、动画等都用的Promise进行封装这样因为高德地图js-api基本上都是异步处理使用promise处理异步更方便

5.有一些是业务场景是需要等待所有异步加载完成之后才可以进行处理这里我没有把所有的方法都放进Promise进行封装因为有太多是在循环内部执行的,而且工时上也来不及了所以就用的递归定时器轮询制,方法虽然土,后期可以优化一下。。。。

require.context导入

这个其实是因为我懒得去依次导入所有工具类了就用了require进行的文件查找导入,因为我是用的是export default去导出类的,所以在解析的时候也是使用的default属性,这里特殊说一下封装类的文件名尽量要和类名统一,都要首字母大写,这样在遍历模块解析的时候更方便

代码如下所示,因为太长我就压缩了

import {    InitMap,    WriteHistoryLine,    TrackReplay,} from './install';/** * 工厂类  *   初始化地图类 --InitMap *   绘制历史轨迹类 --WriteHistoryLine *   轨迹回放类 --TrackReplay  * props ==> { *    el -- 绑定的元素 必填选项 *    key --url的唯一秘钥 *    initCreated --callBack 实例加载成功的回调  *    initError --callBack 实例加载失败的回调 *    carPoto --小车的图片*     isReDress --是否进行轨迹纠偏 * } * __proto__ ==>{ *    mapDestroy --callback 地图实例销毁  *    drawHisTory --callback 高德地图画线 *    trackPlay --callback 高德地图轨迹动画 *    resetMap --callback 重置地图 恢复初始化状态 定位到皇宫 *    getRunningState --callback 获取当前小车状态 停止或者开跑  *    currentTrack --callback实时轨迹开始 *    carDrivingEnd --callback小车是否已经停止了 *    locationToAddress --callback将经纬度反编译成地址  * } */export default class TrackFactory {    constructor(props) {        this.props = { ...props };        this.map = null;//地图实例        this.drawLineInstance = null;//画线实例        this.trackPlayInstance = null;//轨迹播放实例对象        this.RealTimeTrack = null;//实时轨迹播放实例对象        this.realTimeDrawLine = null;//实时轨迹画线实例对象        this.isStopRuning = false;//默认没有点暂停        if (!this.props.el) {            this.props.initError && this.props.initError('参数不正确,缺少必要的挂载元素');            return false;        } else {            this._init();        }    }    async _init () {        try {            const { el, key } = this.props;            const map = new InitMap({ el, key });            this.map = await map._initMap().catch(err => {                this.props.initError && this.props.initError(err);            });            this.props.initCreated && this.props.initCreated(this.map);        } catch (err) {            this.props.initError && this.props.initError(err);        }    }    mapDestroy () {        //地图实例销毁         this.map.destroy();    }    //画线吧 小伙儿 //默认是轨迹回放 是true    drawHisTory ({ data = null, writeError = () => { }, isShowCar = true }) {        if (!this.drawLineInstance) {            return new Promise((resolve, reject) => {                this.drawLineInstance = new WriteHistoryLine({                    map: this.map,                    carPoto: this.props.carPoto,                    data,                    isRealTime: false,                    isShowCar,                    strokeObj: this.props.strokeObj,                    isReDress: this.props.isReDress,                    AMap: window.AMap,                    writeError: (err) => {                        writeError(err);                        reject();                    }                });                resolve();            })        } else {            //追加的逻辑 可以调这个实例的其他方法 this.drawLineInstance.xxxx 这样就解耦了 舒服            if (!isShowCar) { //如果是动态轨迹的话                return new Promise((resolve, reject) => {                    this.drawLineInstance.addPoint(data, this.drawLineInstance.deepNum).then(res => {                        this.trackPlayInstance && this.trackPlayInstance.addRedressRunning();//追加了点之后需要监听一下小车是否移动                        resolve(res);                    })                })            } else {                return new Promise((resolve, reject) => {                    this.drawLineInstance.addPoint(data, this.drawLineInstance.deepNum).then(res => {                        //如果没有停车的话 有推送就跑车                        if (!this.isStopRuning) {                            this.trackPlayInstance && this.trackPlayInstance.addRedressRunning();//追加了点之后需要监听一下小车是否移动                        }                        resolve(res);                    })                })            }        }    }    //轨迹回放动画开始    trackPlay (playerr = () => { }) {        return new Promise((resolve, reject) => {            if (this.drawLineInstance) {                if (!this.trackPlayInstance) {                    this.trackPlayInstance = new TrackReplay({                        AMap: window.AMap,                        map: this.map,                        strokeObj: this.props.strokeObj,                        historyLineInstance: this.drawLineInstance,                        isRealTime: false                    })                }                setTimeout(() => {                    if (!this.trackPlayInstance.isCarDrivingEnd) {                        this.trackPlayInstance.currentMarkerBox.resumeMove();                    } else {                        this.isStopRuning = false;                        this.trackPlayInstance && this.trackPlayInstance.addRedressRunning();//追加了点之后需要监听一下小车是否移动                    }                }, 50)                resolve();            } else {                playerr('当前没有轨迹需要播放!');                reject('当前没有轨迹需要播放!');            }        })    }    //轨迹回放暂停    trackTimeOut (playerr = () => { }) {        this.isStopRuning = true;        return new Promise((resolve, reject) => {            if (this.drawLineInstance) {                this.trackPlayInstance.currentMarkerBox.pauseMove();                // this.trackPlayInstance.isCarDrivingEnd = true;                // console.log(this.trackPlayInstance)                resolve();            } else {                playerr('当前没有轨迹需要播放!');                reject('当前没有轨迹需要播放!');            }        })    }    //轨迹重新播放    trackReStart (playerr = () => { }) {        this.isStopRuning = false;        return new Promise((resolve, reject) => {            if (this.drawLineInstance) {                if (!this.trackPlayInstance) {                    this.trackPlayInstance = new TrackReplay({                        AMap: window.AMap,                        map: this.map,                        strokeObj: this.props.strokeObj,                        historyLineInstance: this.drawLineInstance,                        isRealTime: false                    });                }                this.trackPlayInstance.reStartAnimation();                // this.trackPlayInstance.addRedressRunning();//追加了点之后需要监听一下小车是否移动                // console.log(this.trackPlayInstance)                resolve();            } else {                playerr('当前没有轨迹需要播放!');                reject('当前没有轨迹需要播放!');            }        })    }    //地图清除轨迹和小车等等一切的一切 恢复初始化状态 地图不要给干掉哦~    resetMap () {        // this.drawLineInstance = null;        // this.trackPlayInstance = null;        this.drawLineInstance = null;//画线实例        this.trackPlayInstance = null;//轨迹播放实例对象        this.RealTimeTrack = null;//实时轨迹播放实例对象        this.realTimeDrawLine = null;//实时轨迹画线实例对象        this.isStopRuning = false;//默认没有点暂停        this.map.clearMap();        this.map.setZoomAndCenter(14, [116.397428, 39.90923]);//默认定位到皇宫    }    //判断小车是否跑完了 然后将状态抛出去(必须有个结束的标识 去判断这个去)    getRunningState () {        if (!this.trackPlayInstance) {            console.error('没有小车实例,无法查询小车是否正在移动!');        } else {            return this.trackPlayInstance.isCarDrivingEnd;        }    }    //实时轨迹开始方法    currentTrack ({ data = [], errorFn = () => { }, isShowCar = true }) {        return new Promise((resolve, reject) => {            if (!data.length) {                errorFn('实时轨迹数据不能为空!');                reject('实时轨迹数据不能为空!');            } else {                if (!this.realTimeDrawLine) {                    this.realTimeDrawLine = new WriteHistoryLine({                        map: this.map,                        carPoto: this.props.carPoto,                        data,                        strokeObj: this.props.strokeObj,                        isRealTime: true,                        isShowCar,                        isReDress: this.props.isReDress,                        AMap: window.AMap,                        writeError: (err) => {                            writeError(err);                            reject(err);                        }                    });                }                if (!this.RealTimeTrack) {                    this.realTimeDrawLine.searchLoopMarker(() => {                        this.RealTimeTrack = new TrackReplay({                            AMap: window.AMap,                            map: this.map,                            strokeObj: this.props.strokeObj,                            historyLineInstance: this.realTimeDrawLine,                            isRealTime: true                        });                        resolve();                    })                    // setTimeout(()=>{                    //     this.RealTimeTrack = new TrackReplay({                    //         AMap: window.AMap,                    //         map: this.map,                    //         historyLineInstance: this.realTimeDrawLine,                    //         isRealTime:true                    //     });                    //     resolve();                    // },800)                } else {                    //轨迹点的追加                    this.realTimeDrawLine.addPoint(data, this.realTimeDrawLine.deepNum).then(res => {                        this.RealTimeTrack.addRedressRunning();//追加了点之后需要监听一下小车是否移动                        resolve(res);                    })                }            }        })    }    //小车是否已经停止了 抛出去的方法    carDrivingEnd (callback) {        if (this.trackPlayInstance) {            if (!this.trackPlayInstance.isCarDrivingEnd) {                setTimeout(() => {                    this.carDrivingEnd(callback)                }, 1500);            } else {                callback();            }        }    }    //将经纬度反编译成地址    locationToAddress (lnglatArr) {        return new Promise((res, rej) => {            window.AMap.plugin('AMap.Geocoder', () => {                let geocoder = new window.AMap.Geocoder();                //    console.log(lnglatArr)                geocoder.getAddress(lnglatArr, (status, result) => {                    if (status === 'complete' && result.regeocode && result.info === 'OK') {                        let address = result.regeocode.formattedAddress;                        res(address);                    } else {                        rej('根据经纬度查询地址失败');                    }                })            })        })    }}