百度地圖Canvas實現十萬CAD數據秒級加載

背景

  前段時間工做室接到一個與地圖相關的項目,我做爲項目組成員主要負責地圖方面的設計和開發。因爲地圖部分主要涉及的是前端頁面的顯示,做爲一名Java後端的小白,第一次寫了這麼多HTML和JavaScript。javascript

  項目大概是須要將一張CAD的圖(導出大概三十萬條數據)疊加在地圖上,在接Canvas以前考慮了不少種方案,最後都否認了。首先咱們想利用百度地圖原生的JavaScript API實現線和點的加載,可是通過測試,當數據達到2000左右,加載時間就已經達到了數十秒,後來直接測試了一萬條數據,瀏覽器直接卡死了,這種方案很快就被否認了。而後咱們又準備採用分割靜態圖的方法,將整個CAD圖分割成地圖瓦片,做爲覆蓋圖層疊加在原來地圖之上,在這一步中,因爲CAD圖的信息涉及到整個城市,信息量很是巨大,幾乎沒有找到合適軟件可以導出一張這麼大的圖。後來仔細研究需求文檔後又發現須要針對圖的信息作操做,而後這種方案將近完成的時候被否認了。最後,偶然在Github上看到:https://github.com/lcosmos/map-canvas 這個實現颱風軌跡,這個數據量很是龐大,當時打開時,看到這麼多數據加載很快,感到有點震驚,而後本身研究了一番,發現做者採用的是Canvas做爲百度的自定義覆蓋層,說幹就幹,本身嘗試寫出了第一個版本,寫上Ajax請求,效果十分震撼,將近秒級加載,加了計時器測試了一番性能,發現繪畫只花了1ms左右,主要延時都在請求延時(90M左右的數據),內存佔用也很是少,這下放心多了,項目基本也能夠完成了,而後固然是搗鼓傳輸延時,GZip等都用上了,最後也有了極大優化,客戶看後以爲還十分不錯。css

 

系列文章:

CAD數據分塊校準html

 

效果圖

(因爲項目涉及國家機密,部分細節和圖片不便於展現,但已經能夠完成標題需求)
前端

具體實現

(因爲項目涉及國家機密,部分細節和圖片不便於展現,但已經能夠完成標題需求)java

HTML測試頁:jquery

<!DOCTYPE html>
<html>
<head>
    <title>百度地圖Canvas海量折線</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
    <link rel="stylesheet" href="css/style.css">
    <script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&ak=nuWah68S1WieW2AEwiT8T3Ro&s=1"></script>
    <script type="text/javascript" src="js/jquery.min.js"></script>
</head>
<body>
    <div id="map"></div>
    <script type="text/javascript" src="pointLine.js"></script>
    <script type="text/javascript">
        var map = new BMap.Map('map', {
            minZoom: 5
        });
        map.centerAndZoom(new BMap.Point(112.954699, 27.851256), 13);
        map.enableScrollWheelZoom(true);
        map.setMapStyle({
            styleJson: styleJson
        });
        $.getJSON('line.json', function (result) {
            var pointLine = new PointLine(map, {
                //線條寬度
                lineWidth: 2,
                //線條顏色
                lineStyle: '#F9815C',
                //數據源
                data: result,
                //事件
                methods: {
                    click: function (e, name) {
                        console.log('你當前點擊的是' + name);
                    },
                    // mousemove: function (e, name) {
                    //     console.log('你當前點擊的是' + name);
                    // }
                }
            });
        })
    </script>
</body>
</html>

核心JavaScript:pointLine.jsgit

(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
    typeof define === 'function' && define.amd ? define(factory) :
    (global.PointLine = factory());
}(this, (function () { 'use strict';

function CanvasLayer(options) {
    this.options = options || {};
    this.paneName = this.options.paneName || 'labelPane';
    this.zIndex = this.options.zIndex || 0;
    this._map = options.map;
    this._lastDrawTime = null;
    this.show();
}

CanvasLayer.prototype = new BMap.Overlay();

CanvasLayer.prototype.initialize = function (map) {
    this._map = map;
    var canvas = this.canvas = document.createElement('canvas');
    var ctx = this.ctx = this.canvas.getContext('2d');
    canvas.style.cssText = 'position:absolute;' + 'left:0;' + 'top:0;' + 'z-index:' + this.zIndex + ';';
    this.adjustSize();
    this.adjustRatio(ctx);
    map.getPanes()[this.paneName].appendChild(canvas);
    var that = this;
    map.addEventListener('resize', function () {
        that.adjustSize();
        that._draw();
    });
    return this.canvas;
};

CanvasLayer.prototype.adjustSize = function () {
    var size = this._map.getSize();
    var canvas = this.canvas;
    canvas.width = size.width;
    canvas.height = size.height;
    canvas.style.width = canvas.width + 'px';
    canvas.style.height = canvas.height + 'px';
};

CanvasLayer.prototype.adjustRatio = function (ctx) {
    var backingStore = ctx.backingStorePixelRatio || ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1;
    var pixelRatio = (window.devicePixelRatio || 1) / backingStore;
    var canvasWidth = ctx.canvas.width;
    var canvasHeight = ctx.canvas.height;
    ctx.canvas.width = canvasWidth * pixelRatio;
    ctx.canvas.height = canvasHeight * pixelRatio;
    ctx.canvas.style.width = canvasWidth + 'px';
    ctx.canvas.style.height = canvasHeight + 'px';
    // console.log(ctx.canvas.height, canvasHeight);
    ctx.scale(pixelRatio, pixelRatio);
};

CanvasLayer.prototype.draw = function () {
    var self = this;
    var args = arguments;

    clearTimeout(self.timeoutID);
    self.timeoutID = setTimeout(function () {
        self._draw();
    }, 15);
};

CanvasLayer.prototype._draw = function () {
    var map = this._map;
    var size = map.getSize();
    var center = map.getCenter();
    if (center) {
        var pixel = map.pointToOverlayPixel(center);
        this.canvas.style.left = pixel.x - size.width / 2 + 'px';
        this.canvas.style.top = pixel.y - size.height / 2 + 'px';
        this.dispatchEvent('draw');
        this.options.update && this.options.update.call(this);
    }
};

CanvasLayer.prototype.getContainer = function () {
    return this.canvas;
};

CanvasLayer.prototype.show = function () {
    if (!this.canvas) {
        this._map.addOverlay(this);
    }
    this.canvas.style.display = 'block';
};

CanvasLayer.prototype.hide = function () {
    this.canvas.style.display = 'none';
    //this._map.removeOverlay(this);
};

CanvasLayer.prototype.setZIndex = function (zIndex) {
    this.canvas.style.zIndex = zIndex;
};

CanvasLayer.prototype.getZIndex = function () {
    return this.zIndex;
};

var tool = {
    merge: function merge(settings, defaults) {
        Object.keys(settings).forEach(function (key) {
            defaults[key] = settings[key];
        });
    },
    //計算兩點間距離
    getDistance: function getDistance(p1, p2) {
        return Math.sqrt((p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]));
    },
    //判斷點是否在線段上
    containStroke: function containStroke(x0, y0, x1, y1, lineWidth, x, y) {
        if (lineWidth === 0) {
            return false;
        }
        var _l = lineWidth;
        var _a = 0;
        var _b = x0;
        // Quick reject
        if (y > y0 + _l && y > y1 + _l || y < y0 - _l && y < y1 - _l || x > x0 + _l && x > x1 + _l || x < x0 - _l && x < x1 - _l) {
            return false;
        }

        if (x0 !== x1) {
            _a = (y0 - y1) / (x0 - x1);
            _b = (x0 * y1 - x1 * y0) / (x0 - x1);
        } else {
            return Math.abs(x - x0) <= _l / 2;
        }
        var tmp = _a * x - y + _b;
        var _s = tmp * tmp / (_a * _a + 1);
        return _s <= _l / 2 * _l / 2;
    }
};

var PointLine = function PointLine(map, userOptions) {
    var self = this;

    self.map = map;
    self.lines = [];
    self.pixelList = [];

    //默認參數
    var options = {
        //線條寬度
        lineWidth: 1,
        //線條顏色
        lineStyle: '#F9815C'
    };

    //全局變量
    var baseLayer = null,
        width = map.getSize().width,
        height = map.getSize().height;

    function Line(opts) {
        this.name = opts.name;
        this.path = opts.path;
    }

    Line.prototype.getPointList = function () {
        var points = [],
            path = this.path;
        if (path && path.length > 0) {
            path.forEach(function (p) {
                points.push({
                    name: p.name,
                    pixel: map.pointToPixel(p.location)
                });
            });
        }
        return points;
    };

    Line.prototype.draw = function (context) {
        var pointList = this.pixelList || this.getPointList();
        context.save();
        context.beginPath();
        context.lineWidth = options.lineWidth;
        context.strokeStyle = options.lineStyle;
        context.moveTo(pointList[0].pixel.x, pointList[0].pixel.y);
        for (var i = 0, len = pointList.length; i < len; i++) {
            context.lineTo(pointList[i].pixel.x, pointList[i].pixel.y);
        }
        context.stroke();
        context.closePath();
        context.restore();
    };

    //底層canvas渲染,標註,線條
    var brush = function brush() {
        var baseCtx = baseLayer.canvas.getContext('2d');
        if (!baseCtx) {
            return;
        }

        addLine();

        baseCtx.clearRect(0, 0, width, height);

        self.pixelList = [];
        self.lines.forEach(function (line) {
            self.pixelList.push({
                name: line.name,
                data: line.getPointList()
            });
            line.draw(baseCtx);
        });
    };

    var addLine = function addLine() {
        if (self.lines && self.lines.length > 0) return;
        var dataset = options.data;
        dataset.forEach(function (l, i) {
            var line = new Line({
                name: l.name,
                path: []
            });
            l.data.forEach(function (p, j) {
                line.path.push({
                    name: p.name,
                    location: new BMap.Point(p.Longitude, p.Latitude)
                });
            });
            self.lines.push(line);
        });
    };

    self.init(userOptions, options);

    baseLayer = new CanvasLayer({
        map: map,
        update: brush
    });

    this.clickEvent = this.clickEvent.bind(this);

    this.bindEvent();
};

PointLine.prototype.init = function (settings, defaults) {
    //合併參數
    tool.merge(settings, defaults);

    this.options = defaults;
};

PointLine.prototype.bindEvent = function (e) {
    var map = this.map;
    if (this.options.methods) {
        if (this.options.methods.click) {
            map.setDefaultCursor("default");
            map.addEventListener('click', this.clickEvent);
        }
        if (this.options.methods.mousemove) {
            map.setDefaultCursor("default");
            map.addEventListener('mousemove', this.clickEvent);
        }
    }
};

PointLine.prototype.clickEvent = function (e) {
    var self = this,
        lines = self.pixelList;
    if (lines.length > 0) {
        lines.forEach(function (line, i) {
            for (var j = 0; j < line.data.length; j++) {
                var beginPt = line.data[j].pixel;
                if (line.data[j + 1] == undefined) {
                    return;
                }
                var endPt = line.data[j + 1].pixel;
                var curPt = e.pixel;
                var isOnLine = tool.containStroke(beginPt.x, beginPt.y, endPt.x, endPt.y, self.options.lineWidth, curPt.x, curPt.y);
                if (isOnLine) {
                    self.options.methods.click(e, line.name);
                    return;
                }
            }
        });
    }
};

return PointLine;

})));

測試數據:line.jsongithub

https://files.cnblogs.com/files/lcosmos/line.json.zipweb

相關文章
相關標籤/搜索