基于flash-marker.js的 openlayers 闪烁点的实现方式

在应急管理系统中,经常会有需求,需要在地图上对隐患点或者预警点做闪烁效果。无奈技术渣,只会搬砖,这次就决定搬用flash-marker.js做闪烁点的效果。

参考文章
https://www.cnblogs.com/webgis-mc/p/10455731.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" type="text/css" href="css/ol.css"/>
    <script src="js/ol.js"></script>
    <script src="js/flash-marker.js"></script>
</head>
<body>
<div id="map"></div>
</body>

<script>
    var projection = ol.proj.get('EPSG:4326');
    var projectionExtent = projection.getExtent();
    var size = ol.extent.getWidth(projectionExtent) / 256;
    var resolutions = new Array(19);
    var matrixIds = new Array(19);
    for (var z = 1; z < 19; ++z) {
        resolutions[z] = size / Math.pow(2, z);
        matrixIds[z] = z;
    }

    var map = new ol.Map({
        target: 'map',
        layers: [
            new ol.layer.Tile({
                source: new ol.source.WMTS({
                    name: "天地图影像地图",
                    url: "http://t{0-7}.tianditu.gov.cn/img_c/wmts?tk=38714c443b01bbf3f85d0c036e7c6411",
                    layer: "img",
                    style: "default",
                    matrixSet: "c",
                    format: "tiles",
                    wrapX: true,
                    tileGrid: new ol.tilegrid.WMTS({
                        origin: ol.extent.getTopLeft(projectionExtent),
                        resolutions: resolutions,
                        matrixIds: matrixIds
                    })
                }),
                maxResolution: resolutions[0],
                minResolution: resolutions[18]
            })
        ],
        view: new ol.View({
            projection: 'EPSG:4326',
            center: [113.53450137499999, 34.44104525],
            zoom: 5
        })
    });



    //数据
    let lnglat=[113.53450137499999, 34.44104525];//坐标值[x,y]
    let citys = [{
        name: '',
        lnglat: lnglat,
        color: '#5070FF',
        type: 'circle',
        speed: 0.5,
    }];
    var flashMarker = new window.FlashMarker(map, citys);

</script>
</html>

按上图所示即可完成闪烁点的展示。但是实际使用,并不是这样子简单。

问题一:闪烁点无法点击

首先,这个闪烁点无法点击,这就意味着,不能有查看详情的操作,这里,我的解决方法是在图层上叠加一个固定的点,该点的中心就是闪烁点的中心,颜色与闪烁点颜色相同。

问题二:频繁的调用close和new FlashMatker 导致一大堆的canvas元素被添加到网页上,造成网页卡顿,甚至崩溃。

解决办法是创建一个变量canvasList={},用来存储通过FlashMarker创建的canvas对象。
修改创建canvas元素的代码

canvas = this.canvas = document.createElement('canvas');
//修改为
if(!!canvasList[this.canvasId]){
            canvas = this.canvas = canvasList[this.canvasId];
        }else{
            canvas = this.canvas = document.createElement('canvas');
            canvas.id = this.canvasId;
            canvasList[this.canvasId]=canvas;
        }

问题三 没有提供移除闪烁点和新增单个闪烁点的方法,导致每次有新的闪烁点需要加载时,都要close 然后重新new FlashMarker

解决办法是,新增addFlashMarker以及removeFlashMarker的方法
代码如下:

FlashMarker.prototype.addFlashMarker = function(opt){//添加新的闪烁点
        flashMarkerId++;
        opt['id']=flashMarkerId;
        var marker = new Marker(opt);
        opt["marker"] = marker;
        this.dataSet.push(opt);
        this.markers.push(marker);
        return flashMarkerId;
    }

    FlashMarker.prototype.removeFlashMarker = function(opt){
        var index = -1;
        $.each(this.dataSet,function(i,data){
            if(data["id"] == opt.id){
                index = i;
                return false;
            }
        })
        this.dataSet.splice(index,1);
        this.markers.splice(index,1);
    }

最终改造完成的js代码如下

(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
        typeof define === 'function' && define.amd ? define(factory) :
            (global.FlashMarker = factory());
}(this, (function () { 'use strict';
    var map = null;
    var canvas = null;
    var canvasList = {};
    var flashMarkerId = 0;
    /**
     * @author lzugis
     * @Date 2017-09-29
     * */
    function CanvasLayer(options) {
        this.options = options || {};
        this.paneName = this.options.paneName || 'labelPane';
        this.zIndex = this.options.zIndex || 0;
        this._map = options.map;
        this.canvasId = options.canvasId;
        map = this._map;
        this._lastDrawTime = null;
        this.show();
    }

    CanvasLayer.prototype.initialize = function () {
        var map = this._map;
        if(!!canvasList[this.canvasId]){
            canvas = this.canvas = canvasList[this.canvasId];
        }else{
            canvas = this.canvas = document.createElement('canvas');
            canvas.id = this.canvasId;
            canvasList[this.canvasId]=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.getViewport().appendChild(canvas);
        var that = this;
        map.getView().on('propertychange',function(){
            // $(canvas).hide();
            // canvas.style.display="none";
        });
        // map.on("moveend",function(){
        //   // $(canvas).show();
        //   // canvas.style.display="block";
        //   that.adjustSize();
        //   that._draw();
        // });
    };

    CanvasLayer.prototype.adjustSize = function () {
        var size = this._map.getSize();
        // var canvas = this.canvas;
        canvas.width = size[0];
        canvas.height = size[1];
        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';
        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.getView().getCenter();
        if (center) {
            var pixel = map.getPixelFromCoordinate(center);
            this.canvas.style.left = pixel[0] - size[0] / 2 + 'px';
            this.canvas.style.top = pixel[1] - size[1] / 2 + 'px';
            this.options.update && this.options.update.call(this);
        }
    };

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

    CanvasLayer.prototype.show = function () {
        this.initialize();
        this.canvas.style.display = 'block';
    };

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

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

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

    var global = typeof window === 'undefined' ? {} : window;

    var requestAnimationFrame = global.requestAnimationFrame || global.mozRequestAnimationFrame || global.webkitRequestAnimationFrame || global.msRequestAnimationFrame || function (callback) {
        return global.setTimeout(callback, 1000 / 60);
    };

    function Marker(opts) {
        this.city = opts.name;
        this.location = [opts.lnglat[0], opts.lnglat[1]];
        this.color = opts.color;
        this.type = opts.type || 'circle';
        this.speed = opts.speed || 0.15;
        this.size = 0;
        this.max = opts.max || 20;
    }

    Marker.prototype.draw = function (context) {
        context.save();
        context.beginPath();
        switch (this.type) {
            case 'circle':
                this._drawCircle(context);
                break;
            case 'ellipse':
                this._drawEllipse(context);
                break;
            default:
                break;
        }
        context.closePath();
        context.restore();

        this.size += this.speed;
        if (this.size > this.max) {
            this.size = 0;
        }
    };

    Marker.prototype._drawCircle = function (context) {
        var pixel = this.pixel||map.getPixelFromCoordinate(this.location);
        context.strokeStyle = this.color;
        context.moveTo(pixel[0] + pixel.size, pixel[1]);
        context.arc(pixel[0], pixel[1], this.size, 0, Math.PI * 2);
        context.stroke();
    };

    Marker.prototype._drawEllipse = function (context) {
        var pixel = this.pixel || map.getPixelFromCoordinate(this.location);
        var x = pixel[0],
            y = pixel[1],
            w = this.size,
            h = this.size / 2,
            kappa = 0.5522848,

            // control point offset horizontal
            ox = w / 2 * kappa,

            // control point offset vertical
            oy = h / 2 * kappa,

            // x-start
            xs = x - w / 2,

            // y-start
            ys = y - h / 2,

            // x-end
            xe = x + w / 2,

            // y-end
            ye = y + h / 2;

        context.strokeStyle = this.color;
        context.moveTo(xs, y);
        context.bezierCurveTo(xs, y - oy, x - ox, ys, x, ys);
        context.bezierCurveTo(x + ox, ys, xe, y - oy, xe, y);
        context.bezierCurveTo(xe, y + oy, x + ox, ye, x, ye);
        context.bezierCurveTo(x - ox, ye, xs, y + oy, xs, y);
        context.stroke();
    };

    function FlashMarker(map, dataSet,canvasId) {
        this.timer = null;
        var that = this;
        var animationLayer = null,
            width = map.getSize()[0],
            height = map.getSize()[1],
            animationFlag = true;
        that.width = width;
        this.dataSet = dataSet;
        this.markers = [];
        that.height = height;
        that.canvasId = (!!canvasId?canvasId:'defaultFlashCanvas');
        this.close();

        var addMarker = function addMarker() {
            if (that.markers.length > 0) return;
            that.markers = [];
            for (var i = 0; i < that.dataSet.length; i++) {
                flashMarkerId++;
                that.dataSet[i]["id"]=flashMarkerId;
                that.markers.push(new Marker(that.dataSet[i]));
            }
        };

        //上层canvas渲染,动画效果
        var render = function render() {
            var animationCtx = animationLayer.canvas.getContext('2d');
            that.animationCtx = animationCtx;
            if (!animationCtx) {
                return;
            }

            if (!animationFlag) {
                animationCtx.clearRect(0, 0, width, height);
                return;
            }

            addMarker();

            animationCtx.fillStyle = 'rgba(0,0,0,.95)';
            var prev = animationCtx.globalCompositeOperation;
            animationCtx.globalCompositeOperation = 'destination-in';
            animationCtx.fillRect(0, 0, width, height);
            animationCtx.globalCompositeOperation = prev;

            for (var i = 0; i < that.markers.length; i++) {
                var marker = that.markers[i];
                marker.draw(animationCtx);
            }
        };
        //初始化
        var init = function init() {
            animationLayer = new CanvasLayer({
                map: map,
                canvasId:that.canvasId,
                update: render
            });

            (function drawFrame() {
                that.timer = requestAnimationFrame(drawFrame);
                render();
            })();
        };

        init();
    }

    FlashMarker.prototype.addFlashMarker = function(opt){//添加新的闪烁点
        flashMarkerId++;
        console.log(opt);
        console.log(flashMarkerId);
        opt['id']=flashMarkerId;
        var marker = new Marker(opt);
        opt["marker"] = marker;
        this.dataSet.push(opt);
        this.markers.push(marker);
        return flashMarkerId;
    }

    FlashMarker.prototype.removeFlashMarker = function(opt){
        var index = -1;
        for(var i = 0;i<this.dataSet.length;i++){
            if(this.dataSet[i]["id"] == opt.id){
                index = i;
                break;
            }
        }
        this.dataSet.splice(index,1);
        this.markers.splice(index,1);
    }

    FlashMarker.prototype.close = function() {
        cancelAnimationFrame(this.timer);
        if(this.animationCtx){
            this.animationCtx.clearRect(0, 0, this.width, this.height);
        }
    }
    return FlashMarker;

})));

愉快的玩耍了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值