百度地图点聚合(遇到问题)

聚合后

1. 引入

<script type="text/javascript" src="https://api.map.baidu.com/library/TextIconOverlay/1.2/src/TextIconOverlay_min.js"></script>
<script type="text/javascript" src="https://api.map.baidu.com/library/MarkerClusterer/1.2/src/MarkerClusterer_min.js"></script>

两个js

2. 创建一个marker数组

 this.markers.forEach((item, index) => {
                //标注点默认所用的图标
                let myIcon = new BMapGL.Icon(item.icon, new BMapGL.Size(32, 37));
                const marker = new BMapGL.Marker(new BMapGL.Point(item.longitude, item.latitude), {
                    icon: myIcon
                });
                let label = new BMapGL.Label(item.name, {       // 创建文本标注
                    position: new BMapGL.Point(item.longitude, item.latitude),                          // 设置标注的地理位置
                    offset: new BMapGL.Size(-(item.name.length * 10) + 25, 20)          // 设置标注的偏移量
                })
                // bmap.addOverlay(label);  // 将文本标记添加到地图中
                label.setStyle({                              // 设置label的样式
                    color: '#000',
                    fontSize: '10px',
                    fontFamily: 'PingFangSC-Medium, PingFang SC',
                    border: 'none',
                    background: "transparent",
                    // WebkitTextStroke: "1px #fff",
                })
                // 这里在锚点上绑定业务数据,然后在click事件回调函数中处理即可,弹窗组件我已封装好,注入数据即可
                marker.infoData = item;
                that.markersList.push(marker)//将marker添加到一个数组中去
                bmap.map.addOverlay(marker);
                marker.zIndex = 99; //设置marker层级
                marker.setLabel(label)//设置markle的label
            });

3. 创建聚合点

this.markerClusterer = new BMapLib.MarkerClusterer(bmap.map, {
                markers: that.markersList,
                styles: [{
                    url: that.markersList[0].infoData.icon,//点聚合图标背景图(我这边用了自己聚合点的样式,不传入就是默认样式
                    size: new BMapGL.Size(32, 37),//点聚合图标大小
                }]
            });

4. 清除聚合点 this.markerClusterer.clearMarkers()

注意: 网上看了很多都是这样就好了,但是我的怎么也出不来,后来发现我项目里用的是BMapGL 而引入的两个js是用的BMap 所以要将两个js放到本地,然后将里面的两个js里面的BMap全部替换成BMapGL,这样功能就实现了,但是我要按照设计稿还原,所以就将TextIconOverlay_min.js做了一些改动,还有就是,可以看到我的marker点上是带有label的,但是使用点聚合后label就没有了,所以又对MarkerClusterer_min.js做了改动来实现我的具体业务需求(合并掉的点lable不显示,释放出来后再显示label)

修改后的连个js

TextIconOverlay_min.js

var BMapLib = window.BMapLib = BMapLib || {};
(function() {
    var d, c = d = c || {
        version: "1.3.8"
    };
    (function() {
        c.guid = "$BAIDU$";
        window[c.guid] = window[c.guid] || {};
        c.dom = c.dom || {};
        c.dom.g = function(f) {
            if ("string" == typeof f || f instanceof String) {
                return document.getElementById(f)
            } else {
                if (f && f.nodeName && (f.nodeType == 1 || f.nodeType == 9)) {
                    return f
                }
            }
            return null
        }
        ;
        c.g = c.G = c.dom.g;
        c.dom.getDocument = function(f) {
            f = c.dom.g(f);
            return f.nodeType == 9 ? f : f.ownerDocument || f.document
        }
        ;
        c.lang = c.lang || {};
        c.lang.isString = function(f) {
            return "[object String]" == Object.prototype.toString.call(f)
        }
        ;
        c.isString = c.lang.isString;
        c.dom._g = function(f) {
            if (c.lang.isString(f)) {
                return document.getElementById(f)
            }
            return f
        }
        ;
        c._g = c.dom._g;
        c.browser = c.browser || {};
        if (/msie (\d+\.\d)/i.test(navigator.userAgent)) {
            c.browser.ie = c.ie = document.documentMode || +RegExp["\x241"]
        }
        c.dom.getComputedStyle = function(g, f) {
            g = c.dom._g(g);
            var i = c.dom.getDocument(g), h;
            if (i.defaultView && i.defaultView.getComputedStyle) {
                h = i.defaultView.getComputedStyle(g, null);
                if (h) {
                    return h[f] || h.getPropertyValue(f)
                }
            }
            return ""
        }
        ;
        c.dom._styleFixer = c.dom._styleFixer || {};
        c.dom._styleFilter = c.dom._styleFilter || [];
        c.dom._styleFilter.filter = function(g, k, l) {
            for (var f = 0, j = c.dom._styleFilter, h; h = j[f]; f++) {
                if (h = h[l]) {
                    k = h(g, k)
                }
            }
            return k
        }
        ;
        c.string = c.string || {};
        c.string.toCamelCase = function(f) {
            if (f.indexOf("-") < 0 && f.indexOf("_") < 0) {
                return f
            }
            return f.replace(/[-_][^-_]/g, function(g) {
                return g.charAt(1).toUpperCase()
            })
        }
        ;
        c.dom.getStyle = function(h, g) {
            var j = c.dom;
            h = j.g(h);
            g = c.string.toCamelCase(g);
            var i = h.style[g] || (h.currentStyle ? h.currentStyle[g] : "") || j.getComputedStyle(h, g);
            if (!i) {
                var f = j._styleFixer[g];
                if (f) {
                    i = f.get ? f.get(h) : c.dom.getStyle(h, f)
                }
            }
            if (f = j._styleFilter) {
                i = f.filter(g, i, "get")
            }
            return i
        }
        ;
        c.getStyle = c.dom.getStyle;
        if (/opera\/(\d+\.\d)/i.test(navigator.userAgent)) {
            c.browser.opera = +RegExp["\x241"]
        }
        c.browser.isWebkit = /webkit/i.test(navigator.userAgent);
        c.browser.isGecko = /gecko/i.test(navigator.userAgent) && !/like gecko/i.test(navigator.userAgent);
        c.browser.isStrict = document.compatMode == "CSS1Compat";
        c.dom.getPosition = function(f) {
            f = c.dom.g(f);
            var o = c.dom.getDocument(f), i = c.browser, l = c.dom.getStyle, h = i.isGecko > 0 && o.getBoxObjectFor && l(f, "position") == "absolute" && (f.style.top === "" || f.style.left === ""), m = {
                left: 0,
                top: 0
            }, k = (i.ie && !i.isStrict) ? o.body : o.documentElement, p, g;
            if (f == k) {
                return m
            }
            if (f.getBoundingClientRect) {
                g = f.getBoundingClientRect();
                m.left = Math.floor(g.left) + Math.max(o.documentElement.scrollLeft, o.body.scrollLeft);
                m.top = Math.floor(g.top) + Math.max(o.documentElement.scrollTop, o.body.scrollTop);
                m.left -= o.documentElement.clientLeft;
                m.top -= o.documentElement.clientTop;
                var n = o.body
                  , q = parseInt(l(n, "borderLeftWidth"))
                  , j = parseInt(l(n, "borderTopWidth"));
                if (i.ie && !i.isStrict) {
                    m.left -= isNaN(q) ? 2 : q;
                    m.top -= isNaN(j) ? 2 : j
                }
            } else {
                p = f;
                do {
                    m.left += p.offsetLeft;
                    m.top += p.offsetTop;
                    if (i.isWebkit > 0 && l(p, "position") == "fixed") {
                        m.left += o.body.scrollLeft;
                        m.top += o.body.scrollTop;
                        break
                    }
                    p = p.offsetParent
                } while (p && p != f);
                if (i.opera > 0 || (i.isWebkit > 0 && l(f, "position") == "absolute")) {
                    m.top -= o.body.offsetTop
                }
                p = f.offsetParent;
                while (p && p != o.body) {
                    m.left -= p.scrollLeft;
                    if (!i.opera || p.tagName != "TR") {
                        m.top -= p.scrollTop
                    }
                    p = p.offsetParent
                }
            }
            return m
        }
        ;
        c.event = c.event || {};
        c.event._listeners = c.event._listeners || [];
        c.event.on = function(g, j, l) {
            j = j.replace(/^on/i, "");
            g = c.dom._g(g);
            var k = function(n) {
                l.call(g, n)
            }, f = c.event._listeners, i = c.event._eventFilter, m, h = j;
            j = j.toLowerCase();
            if (i && i[j]) {
                m = i[j](g, j, k);
                h = m.type;
                k = m.listener
            }
            if (g.addEventListener) {
                g.addEventListener(h, k, false)
            } else {
                if (g.attachEvent) {
                    g.attachEvent("on" + h, k)
                }
            }
            f[f.length] = [g, j, l, k, h];
            return g
        }
        ;
        c.on = c.event.on;
        (function() {
            var f = window[c.guid];
            c.lang.guid = function() {
                return "TANGRAM__" + (f._counter++).toString(36)
            }
            ;
            f._counter = f._counter || 1
        }
        )();
        window[c.guid]._instances = window[c.guid]._instances || {};
        c.lang.isFunction = function(f) {
            return "[object Function]" == Object.prototype.toString.call(f)
        }
        ;
        c.lang.Class = function(f) {
            this.guid = f || c.lang.guid();
            window[c.guid]._instances[this.guid] = this
        }
        ;
        window[c.guid]._instances = window[c.guid]._instances || {};
        c.lang.Class.prototype.dispose = function() {
            delete window[c.guid]._instances[this.guid];
            for (var f in this) {
                if (!c.lang.isFunction(this[f])) {
                    delete this[f]
                }
            }
            this.disposed = true
        }
        ;
        c.lang.Class.prototype.toString = function() {
            return "[object " + (this._className || "Object") + "]"
        }
        ;
        c.lang.Event = function(f, g) {
            this.type = f;
            this.returnValue = true;
            this.target = g || null;
            this.currentTarget = null
        }
        ;
        c.lang.Class.prototype.addEventListener = function(i, h, g) {
            if (!c.lang.isFunction(h)) {
                return
            }
            !this.__listeners && (this.__listeners = {});
            var f = this.__listeners, j;
            if (typeof g == "string" && g) {
                if (/[^\w\-]/.test(g)) {
                    throw ("nonstandard key:" + g)
                } else {
                    h.hashCode = g;
                    j = g
                }
            }
            i.indexOf("on") != 0 && (i = "on" + i);
            typeof f[i] != "object" && (f[i] = {});
            j = j || c.lang.guid();
            h.hashCode = j;
            f[i][j] = h
        }
        ;
        c.lang.Class.prototype.removeEventListener = function(i, h) {
            if (typeof h != "undefined") {
                if ((c.lang.isFunction(h) && !(h = h.hashCode)) || (!c.lang.isString(h))) {
                    return
                }
            }
            !this.__listeners && (this.__listeners = {});
            i.indexOf("on") != 0 && (i = "on" + i);
            var g = this.__listeners;
            if (!g[i]) {
                return
            }
            if (typeof h != "undefined") {
                g[i][h] && delete g[i][h]
            } else {
                for (var f in g[i]) {
                    delete g[i][f]
                }
            }
        }
        ;
        c.lang.Class.prototype.dispatchEvent = function(j, f) {
            if (c.lang.isString(j)) {
                j = new c.lang.Event(j)
            }
            !this.__listeners && (this.__listeners = {});
            f = f || {};
            for (var h in f) {
                j[h] = f[h]
            }
            var h, g = this.__listeners, k = j.type;
            j.target = j.target || this;
            j.currentTarget = this;
            k.indexOf("on") != 0 && (k = "on" + k);
            c.lang.isFunction(this[k]) && this[k].apply(this, arguments);
            if (typeof g[k] == "object") {
                for (h in g[k]) {
                    g[k][h].apply(this, arguments)
                }
            }
            return j.returnValue
        }
        ;
        c.lang.inherits = function(l, j, i) {
            var h, k, f = l.prototype, g = new Function();
            g.prototype = j.prototype;
            k = l.prototype = new g();
            for (h in f) {
                k[h] = f[h]
            }
            l.prototype.constructor = l;
            l.superClass = j.prototype;
            if ("string" == typeof i) {
                k._className = i
            }
        }
        ;
        c.inherits = c.lang.inherits
    }
    )();
    var b = "http://api.map.baidu.com/library/TextIconOverlay/1.2/src/images/m";
    var a = "png";
    var e = BMapLib.TextIconOverlay = function(f, h, g) {
        this._position = f;
        this._text = h;
        this._options = g || {};
        this._styles = this._options.styles || [];
        (!this._styles.length) && this._setupDefaultStyles()
    }
    ;
    d.lang.inherits(e, BMapGL.Overlay, "TextIconOverlay");
    e.prototype._setupDefaultStyles = function() {
        var h = [53, 56, 66, 78, 90];
        for (var g = 0, f; f = h[g]; g++) {
            this._styles.push({
                url: b + g + "." + a,
                size: new BMapGL.Size(f,f)
            })
        }
    }
    ;
    e.prototype.initialize = function(f) {
        this._map = f;
        this._domElement = document.createElement("div");
        this._updateCss();
        this._updateText();
        this._updatePosition();
        this._bind();
        this._map.getPanes().markerPane.appendChild(this._domElement);
        return this._domElement
    }
    ;
    e.prototype.draw = function() {
        this._map && this._updatePosition()
    }
    ;
    e.prototype.getText = function() {
        return this._text
    }
    ;
    e.prototype.setText = function(f) {
        if (f && (!this._text || (this._text.toString() != f.toString()))) {
            this._text = f;
            this._updateText();
            this._updateCss();
            this._updatePosition()
        }
    }
    ;
    e.prototype.getPosition = function() {
        return this._position
    }
    ;
    e.prototype.setPosition = function(f) {
        if (f && (!this._position || !this._position.equals(f))) {
            this._position = f;
            this._updatePosition()
        }
    }
    ;
    e.prototype.getStyleByText = function(i, h) {
        var g = parseInt(i);
        var f = parseInt(g / 10);
        f = Math.max(0, f);
        f = Math.min(f, h.length - 1);
        return h[f]
    }
    ;
    e.prototype._updateCss = function() {
        var f = this.getStyleByText(this._text, this._styles);
        this._domElement.style.cssText = this._buildCssText(f)
    }
    ;
    e.prototype._updateText = function() {
        if (this._domElement) {
            //在聚合数量这边加了个div,来实现数量定位到右上角的样式,在css中给info-num添加样式就好了
            this._domElement.innerHTML = '<div class="info-num">' + this._text + '</div>'
        }
    }
    ;
    e.prototype._updatePosition = function() {
        if (this._domElement && this._position) {
            var f = this._domElement.style;
            var g = this._map.pointToOverlayPixel(this._position);
            g.x -= Math.ceil(parseInt(f.width) / 2);
            g.y -= Math.ceil(parseInt(f.height) / 2);
            f.left = g.x + "px";
            f.top = g.y + "px"
        }
    }
    ;
    e.prototype._buildCssText = function(g) {
        var h = g.url;
        var n = g.size;
        var k = g.anchor;
        var j = g.offset;
        var l = g.textColor || "black";
        var f = g.textSize || 10;
        var m = [];
        if (d.browser.ie < 7) {
            m.push('filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src="' + h + '");')
        } else {
            m.push("background-image:url(" + h + ");background-size:100%;");
            var i = "0 0";
            (j instanceof BMapGL.Size) && (i = j.width + "px " + j.height + "px");
            m.push("background-position:" + i + ";")
        }
        if (n instanceof BMapGL.Size) {
            if (k instanceof BMapGL.Size) {
                if (k.height > 0 && k.height < n.height) {
                    m.push("height:" + (n.height - k.height) + "px; padding-top:" + k.height + "px;")
                }
                if (k.width > 0 && k.width < n.width) {
                    m.push("width:" + (n.width - k.width) + "px; padding-left:" + k.width + "px;")
                }
            } else {
                m.push("height:" + n.height + "px; line-height:" + n.height + "px;");
                m.push("width:" + n.width + "px; text-align:center;")
            }
        }
        m.push("cursor:pointer; color:" + l + "; position:absolute; font-size:" + f + "px; font-family:Arial,sans-serif; font-weight:bold");
        return m.join("")
    }
    ;
    e.prototype._bind = function() {
        if (!this._domElement) {
            return
        }
        var g = this;
        var i = this._map;
        var f = d.lang.Event;
        function h(m, l) {
            var k = m.srcElement || m.target;
            var j = m.clientX || m.pageX;
            var o = m.clientY || m.pageY;
            if (m && l && j && o && k) {
                var n = d.dom.getPosition(i.getContainer());
                l.pixel = new BMapGL.Pixel(j - n.left,o - n.top);
                l.point = i.pixelToPoint(l.pixel)
            }
            return l
        }
        d.event.on(this._domElement, "mouseover", function(j) {
            g.dispatchEvent(h(j, new f("onmouseover")))
        });
        d.event.on(this._domElement, "mouseout", function(j) {
            g.dispatchEvent(h(j, new f("onmouseout")))
        });
        d.event.on(this._domElement, "click", function(j) {
            g.dispatchEvent(h(j, new f("onclick")))
        })
    }
}
)();

MarkerClusterer_min.js


var BMapLib = window.BMapLib = BMapLib || {};

(function () {

    /**

     * 获取一个扩展的视图范围,把上下左右都扩大一样的像素值。

     * @param {Map} map BMapGL.Map的实例化对象

     * @param {BMapGL.Bounds} bounds BMapGL.Bounds的实例化对象

     * @param {Number} gridSize 要扩大的像素值

     *

     * @return {BMapGL.Bounds} 返回扩大后的视图范围。

     */

    var getExtendedBounds = function (map, bounds, gridSize) {

        bounds = cutBoundsInRange(bounds);

        var pixelNE = map.pointToPixel(bounds.getNorthEast());

        var pixelSW = map.pointToPixel(bounds.getSouthWest());

        pixelNE.x += gridSize;

        pixelNE.y -= gridSize;

        pixelSW.x -= gridSize;

        pixelSW.y += gridSize;

        var newNE = map.pixelToPoint(pixelNE);

        var newSW = map.pixelToPoint(pixelSW);

        return new BMapGL.Bounds(newSW, newNE);

    };

    /**

     * 按照百度地图支持的世界范围对bounds进行边界处理

     * @param {BMapGL.Bounds} bounds BMapGL.Bounds的实例化对象

     *

     * @return {BMapGL.Bounds} 返回不越界的视图范围

     */

    var cutBoundsInRange = function (bounds) {

        var maxX = getRange(bounds.getNorthEast().lng, -180, 180);

        var minX = getRange(bounds.getSouthWest().lng, -180, 180);

        var maxY = getRange(bounds.getNorthEast().lat, -74, 74);

        var minY = getRange(bounds.getSouthWest().lat, -74, 74);

        return new BMapGL.Bounds(new BMapGL.Point(minX, minY), new BMapGL.Point(maxX, maxY));

    };

    /**

     * 对单个值进行边界处理。

     * @param {Number} i 要处理的数值

     * @param {Number} min 下边界值

     * @param {Number} max 上边界值

     *

     * @return {Number} 返回不越界的数值

     */

    var getRange = function (i, mix, max) {

        mix && (i = Math.max(i, mix));

        max && (i = Math.min(i, max));

        return i;

    };

    /**

     * 判断给定的对象是否为数组

     * @param {Object} source 要测试的对象

     *

     * @return {Boolean} 如果是数组返回true,否则返回false

     */

    var isArray = function (source) {

        return '[object Array]' === Object.prototype.toString.call(source);

    };

    /**

     * 返回item在source中的索引位置

     * @param {Object} item 要测试的对象

     * @param {Array} source 数组

     *

     * @return {Number} 如果在数组内,返回索引,否则返回-1

     */

    var indexOf = function (item, source) {

        var index = -1;

        if (isArray(source)) {

            if (source.indexOf) {

                index = source.indexOf(item);

            } else {

                for (var i = 0, m; m = source[i]; i++) {

                    if (m === item) {

                        index = i;

                        break;

                    }

                }

            }

        }

        return index;

    };

    /**

     *@exports MarkerClusterer as BMapLib.MarkerClusterer

     */

    var MarkerClusterer =

        /**

         * MarkerClusterer

         * @class 用来解决加载大量点要素到地图上产生覆盖现象的问题,并提高性能

         * @constructor

         * @param {Map} map 地图的一个实例。

         * @param {Json Object} options 可选参数,可选项包括:<br />

         *    markers {Array<Marker>} 要聚合的标记数组<br />

         *    girdSize {Number} 聚合计算时网格的像素大小,默认60<br />

         *    maxZoom {Number} 最大的聚合级别,大于该级别就不进行相应的聚合<br />

         *    minClusterSize {Number} 最小的聚合数量,小于该数量的不能成为一个聚合,默认为2<br />

         *    isAverangeCenter {Boolean} 聚合点的落脚位置是否是所有聚合在内点的平均值,默认为否,落脚在聚合内的第一个点<br />

         *    styles {Array<IconStyle>} 自定义聚合后的图标风格,请参考TextIconOverlay类<br />

         */

        BMapLib.MarkerClusterer = function (map, options) {

            if (!map) {

                return;

            }

            this._map = map;

            this._markers = [];

            this._clusters = [];

            var opts = options || {};

            this._gridSize = opts["gridSize"] || 60;

            this._maxZoom = opts["maxZoom"] || 18;

            this._minClusterSize = opts["minClusterSize"] || 2;

            this._isAverageCenter = false;

            if (opts['isAverageCenter'] != undefined) {

                this._isAverageCenter = opts['isAverageCenter'];

            }

            this._styles = opts["styles"] || [];

            var that = this;

            this._map.addEventListener("zoomend", function () {

                that._redraw();

            });

            this._map.addEventListener("moveend", function () {

                that._redraw();

            });

            var mkrs = opts["markers"];

            isArray(mkrs) && this.addMarkers(mkrs);

        };

    /**

     * 添加要聚合的标记数组。

     * @param {Array<Marker>} markers 要聚合的标记数组

     *

     * @return 无返回值。

     */

    MarkerClusterer.prototype.addMarkers = function (markers) {

        for (var i = 0, len = markers.length; i < len; i++) {

            this._pushMarkerTo(markers[i]);

        }

        this._createClusters();

    };

    /**

     * 把一个标记添加到要聚合的标记数组中

     * @param {BMapGL.Marker} marker 要添加的标记

     *

     * @return 无返回值。

     */

    MarkerClusterer.prototype._pushMarkerTo = function (marker) {

        var index = indexOf(marker, this._markers);

        if (index === -1) {

            marker.isInCluster = false;

            this._markers.push(marker);//Marker拖放后enableDragging不做变化,忽略

        }

    };

    /**

     * 添加一个聚合的标记。

     * @param {BMapGL.Marker} marker 要聚合的单个标记。

     * @return 无返回值。

     */

    MarkerClusterer.prototype.addMarker = function (marker) {

        this._pushMarkerTo(marker);

        this._createClusters();

    };

    /**

     * 根据所给定的标记,创建聚合点

     * @return 无返回值

     */

    MarkerClusterer.prototype._createClusters = function () {

        var mapBounds = this._map.getBounds();

        var extendedBounds = getExtendedBounds(this._map, mapBounds, this._gridSize);

        for (var i = 0, marker; marker = this._markers[i]; i++) {

            if (!marker.isInCluster && extendedBounds.containsPoint(marker.getPosition())) {
                let tmplabel = marker.getLabel();
                if (tmplabel !== null) {
                    tmplabel.setStyle({
                        display: 'none'
                    })
                }

                this._addToClosestCluster(marker);

            }

        }

    };

    /**

     * 根据标记的位置,把它添加到最近的聚合中

     * @param {BMapGL.Marker} marker 要进行聚合的单个标记

     *

     * @return 无返回值。

     */

    MarkerClusterer.prototype._addToClosestCluster = function (marker) {

        var distance = 4000000;

        var clusterToAddTo = null;

        var position = marker.getPosition();

        for (var i = 0, cluster; cluster = this._clusters[i]; i++) {

            var center = cluster.getCenter();

            if (center) {

                var d = this._map.getDistance(center, marker.getPosition());

                if (d < distance) {

                    distance = d;

                    clusterToAddTo = cluster;

                }

            }

        }

        if (clusterToAddTo && clusterToAddTo.isMarkerInClusterBounds(marker)) {
            let tmplabel = marker.getLabel();
                if (tmplabel !== null) {
                    tmplabel.setStyle({
                        display: 'none'
                    })
                }

            clusterToAddTo.addMarker(marker);

        } else {

            var cluster = new Cluster(this);
            let tmplabel = marker.getLabel();
                if (tmplabel !== null) {
                    tmplabel.setStyle({
                        display: 'none'
                    })
                }

            cluster.addMarker(marker);

            this._clusters.push(cluster);

        }

    };

    /**

     * 清除上一次的聚合的结果

     * @return 无返回值。

     */

    MarkerClusterer.prototype._clearLastClusters = function () {

        for (var i = 0, cluster; cluster = this._clusters[i]; i++) {

            cluster.remove();

        }

        this._clusters = [];//置空Cluster数组

        this._removeMarkersFromCluster();//把Marker的cluster标记设为false

    };

    /**

     * 清除某个聚合中的所有标记

     * @return 无返回值

     */

    MarkerClusterer.prototype._removeMarkersFromCluster = function () {

        for (var i = 0, marker; marker = this._markers[i]; i++) {

            marker.isInCluster = false;

        }

    };

    /**

     * 把所有的标记从地图上清除

     * @return 无返回值

     */

    MarkerClusterer.prototype._removeMarkersFromMap = function () {

        for (var i = 0, marker; marker = this._markers[i]; i++) {

            marker.isInCluster = false;

            let tmplabel = marker.getLabel();


            this._map.removeOverlay(marker);
            if (tmplabel !== null) {
                tmplabel.setStyle({
                    display: 'none'
                })
            }

            marker.setLabel(tmplabel);

        }

    };

    /**

     * 删除单个标记

     * @param {BMapGL.Marker} marker 需要被删除的marker

     *

     * @return {Boolean} 删除成功返回true,否则返回false

     */

    MarkerClusterer.prototype._removeMarker = function (marker) {

        var index = indexOf(marker, this._markers);

        if (index === -1) {

            return false;

        }

        let tmplabel = marker.getLabel();

        this._map.removeOverlay(marker);
        if (tmplabel !== null) {
            tmplabel.setStyle({
                display: 'none'
            })
        }

        marker.setLabel(tmplabel);

        this._markers.splice(index, 1);

        return true;

    };

    /**

     * 删除单个标记

     * @param {BMapGL.Marker} marker 需要被删除的marker

     *

     * @return {Boolean} 删除成功返回true,否则返回false

     */

    MarkerClusterer.prototype.removeMarker = function (marker) {

        var success = this._removeMarker(marker);

        if (success) {

            this._clearLastClusters();

            this._createClusters();

        }

        return success;

    };

    /**

     * 删除一组标记

     * @param {Array<BMapGL.Marker>} markers 需要被删除的marker数组

     *

     * @return {Boolean} 删除成功返回true,否则返回false

     */

    MarkerClusterer.prototype.removeMarkers = function (markers) {

        var success = false;

        for (var i = 0; i < markers.length; i++) {

            var r = this._removeMarker(markers[i]);

            success = success || r;

        }

        if (success) {

            this._clearLastClusters();

            this._createClusters();

        }

        return success;

    };

    /**

     * 从地图上彻底清除所有的标记

     * @return 无返回值

     */

    MarkerClusterer.prototype.clearMarkers = function () {

        this._clearLastClusters();

        this._removeMarkersFromMap();

        this._markers = [];

    };

    /**

     * 重新生成,比如改变了属性等

     * @return 无返回值

     */

    MarkerClusterer.prototype._redraw = function () {

        this._clearLastClusters();

        this._createClusters();

    };

    /**

     * 获取网格大小

     * @return {Number} 网格大小

     */

    MarkerClusterer.prototype.getGridSize = function () {

        return this._gridSize;

    };

    /**

     * 设置网格大小

     * @param {Number} size 网格大小

     * @return 无返回值

     */

    MarkerClusterer.prototype.setGridSize = function (size) {

        this._gridSize = size;

        this._redraw();

    };

    /**

     * 获取聚合的最大缩放级别。

     * @return {Number} 聚合的最大缩放级别。

     */

    MarkerClusterer.prototype.getMaxZoom = function () {

        return this._maxZoom;

    };

    /**

     * 设置聚合的最大缩放级别

     * @param {Number} maxZoom 聚合的最大缩放级别

     * @return 无返回值

     */

    MarkerClusterer.prototype.setMaxZoom = function (maxZoom) {

        this._maxZoom = maxZoom;

        this._redraw();

    };

    /**

     * 获取聚合的样式风格集合

     * @return {Array<IconStyle>} 聚合的样式风格集合

     */

    MarkerClusterer.prototype.getStyles = function () {

        return this._styles;

    };

    /**

     * 设置聚合的样式风格集合

     * @param {Array<IconStyle>} styles 样式风格数组

     * @return 无返回值

     */

    MarkerClusterer.prototype.setStyles = function (styles) {

        this._styles = styles;

        this._redraw();

    };

    /**

     * 获取单个聚合的最小数量。

     * @return {Number} 单个聚合的最小数量。

     */

    MarkerClusterer.prototype.getMinClusterSize = function () {

        return this._minClusterSize;

    };

    /**

     * 设置单个聚合的最小数量。

     * @param {Number} size 单个聚合的最小数量。

     * @return 无返回值。

     */

    MarkerClusterer.prototype.setMinClusterSize = function (size) {

        this._minClusterSize = size;

        this._redraw();

    };

    /**

     * 获取单个聚合的落脚点是否是聚合内所有标记的平均中心。

     * @return {Boolean} true或false。

     */

    MarkerClusterer.prototype.isAverageCenter = function () {

        return this._isAverageCenter;

    };

    /**

     * 获取聚合的Map实例。

     * @return {Map} Map的示例。

     */

    MarkerClusterer.prototype.getMap = function () {

        return this._map;

    };

    /**

     * 获取所有的标记数组。

     * @return {Array<Marker>} 标记数组。

     */

    MarkerClusterer.prototype.getMarkers = function () {

        return this._markers;

    };

    /**

     * 获取聚合的总数量。

     * @return {Number} 聚合的总数量。

     */

    MarkerClusterer.prototype.getClustersCount = function () {

        var count = 0;

        for (var i = 0, cluster; cluster = this._clusters[i]; i++) {

            cluster.isReal() && count++;

        }

        return count;

    };

    /**

     * @ignore

     * Cluster

     * @class 表示一个聚合对象,该聚合,包含有N个标记,这N个标记组成的范围,并有予以显示在Map上的TextIconOverlay等。

     * @constructor

     * @param {MarkerClusterer} markerClusterer 一个标记聚合器示例。

     */

    function Cluster(markerClusterer) {

        this._markerClusterer = markerClusterer;

        this._map = markerClusterer.getMap();

        this._minClusterSize = markerClusterer.getMinClusterSize();

        this._isAverageCenter = markerClusterer.isAverageCenter();

        this._center = null;//落脚位置

        this._markers = [];//这个Cluster中所包含的markers

        this._gridBounds = null;//以中心点为准,向四边扩大gridSize个像素的范围,也即网格范围

        this._isReal = false; //真的是个聚合

        this._clusterMarker = new BMapLib.TextIconOverlay(this._center, this._markers.length, { "styles": this._markerClusterer.getStyles() });

        //this._map.addOverlay(this._clusterMarker);

    }

    /**

     * 向该聚合添加一个标记。

     * @param {Marker} marker 要添加的标记。

     * @return 无返回值。

     */

    Cluster.prototype.addMarker = function (marker) {

        if (this.isMarkerInCluster(marker)) {

            return false;

        }//也可用marker.isInCluster判断,外面判断OK,这里基本不会命中

        if (!this._center) {

            this._center = marker.getPosition();

            this.updateGridBounds();//

        } else {

            if (this._isAverageCenter) {

                var l = this._markers.length + 1;

                var lat = (this._center.lat * (l - 1) + marker.getPosition().lat) / l;

                var lng = (this._center.lng * (l - 1) + marker.getPosition().lng) / l;

                this._center = new BMapGL.Point(lng, lat);

                this.updateGridBounds();

            }//计算新的Center

        }

        marker.isInCluster = true;

        this._markers.push(marker);

        var len = this._markers.length;

        if (len < this._minClusterSize) {
            let tmplabel = marker.getLabel();
            if (tmplabel !== null) {
                tmplabel.setStyle({
                    display: 'block'
                })
            }


            this._map.addOverlay(marker);

            //this.updateClusterMarker();

            return true;

        } else if (len === this._minClusterSize) {

            for (var i = 0; i < len; i++) {

                let tmplabel = this._markers[i].getLabel();
                tmplabel.setStyle({
                    display: 'none'
                })

                this._markers[i].getMap() && this._map.removeOverlay(this._markers[i]);

                this._markers[i].setLabel(tmplabel);

            }

        }

        this._map.addOverlay(this._clusterMarker);

        this._isReal = true;

        this.updateClusterMarker();

        return true;

    };

    /**

     * 判断一个标记是否在该聚合中。

     * @param {Marker} marker 要判断的标记。

     * @return {Boolean} true或false。

     */

    Cluster.prototype.isMarkerInCluster = function (marker) {

        if (this._markers.indexOf) {

            return this._markers.indexOf(marker) != -1;

        } else {

            for (var i = 0, m; m = this._markers[i]; i++) {

                if (m === marker) {

                    return true;

                }

            }

        }

        return false;

    };

    /**

     * 判断一个标记是否在该聚合网格范围中。

     * @param {Marker} marker 要判断的标记。

     * @return {Boolean} true或false。

     */

    Cluster.prototype.isMarkerInClusterBounds = function (marker) {

        return this._gridBounds.containsPoint(marker.getPosition());

    };

    Cluster.prototype.isReal = function (marker) {

        return this._isReal;

    };

    /**

     * 更新该聚合的网格范围。

     * @return 无返回值。

     */

    Cluster.prototype.updateGridBounds = function () {

        var bounds = new BMapGL.Bounds(this._center, this._center);

        this._gridBounds = getExtendedBounds(this._map, bounds, this._markerClusterer.getGridSize());

    };

    /**

     * 更新该聚合的显示样式,也即TextIconOverlay。

     * @return 无返回值。

     */

    Cluster.prototype.updateClusterMarker = function () {

        if (this._map.getZoom() > this._markerClusterer.getMaxZoom()) {

            this._clusterMarker && this._map.removeOverlay(this._clusterMarker);

            for (var i = 0, marker; marker = this._markers[i]; i++) {
                let tmplabel = marker.getLabel();
                if (tmplabel !== null) {
                    tmplabel.setStyle({
                        display: 'block'
                    })
                }
                this._map.addOverlay(marker);

            }

            return;

        }

        if (this._markers.length < this._minClusterSize) {

            this._clusterMarker.hide();

            return;

        }

        this._clusterMarker.setPosition(this._center);

        this._clusterMarker.setText(this._markers.length);

        var thatMap = this._map;

        var thatBounds = this.getBounds();

        this._clusterMarker.addEventListener("click", function (event) {

            thatMap.setViewport(thatBounds);

        });

    };

    /**

     * 删除该聚合。

     * @return 无返回值。

     */

    Cluster.prototype.remove = function () {

        for (var i = 0, m; m = this._markers[i]; i++) {

            let tmplabel = this._markers[i].getLabel();

            this._markers[i].getMap() && this._map.removeOverlay(this._markers[i])
            if (tmplabel !== null) {
                tmplabel.setStyle({
                    display: 'none'
                })
            }
            this._markers[i].setLabel(tmplabel)

        }//清除散的标记点

        this._map.removeOverlay(this._clusterMarker);

        this._markers.length = 0;

        delete this._markers;

    }

    /**

     * 获取该聚合所包含的所有标记的最小外接矩形的范围。

     * @return {BMapGL.Bounds} 计算出的范围。

     */

    Cluster.prototype.getBounds = function () {

        var bounds = new BMapGL.Bounds(this._center, this._center);

        for (var i = 0, marker; marker = this._markers[i]; i++) {

            bounds.extend(marker.getPosition());

        }

        return bounds;

    };

    /**

     * 获取该聚合的落脚点。

     * @return {BMapGL.Point} 该聚合的落脚点。

     */

    Cluster.prototype.getCenter = function () {

        return this._center;

    };

})();

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
要在Vue中实现百度地图聚合,可以按照以下步骤进行操作: 1. 首先,在Vue项目中安装百度地图JavaScript API。可以通过在`index.html`文件中添加以下代码来引入百度地图的API: ```html <script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&ak=YOUR_API_KEY"></script> ``` 确保替换`YOUR_API_KEY`为你自己的百度地图API密钥。 2. 在Vue组件中创建地图容器,并初始化地图。可以在`mounted`钩子函数中添加以下代码: ```javascript mounted() { const map = new BMap.Map("map-container"); // 创建地图实例 const point = new BMap.Point(经度, 纬度); // 设置地图中心坐标 map.centerAndZoom(point, 15); // 初始化地图,设置地图缩放级别 this.map = map; // 将地图实例保存到组件数据中 } ``` 确保替换`经度`和`纬度`为你希望地图显示的中心坐标。 3. 获取需要聚合的标记数据,并使用百度地图的`MarkerClusterer`类进行聚合。可以在`mounted`钩子函数中添加以下代码: ```javascript mounted() { // ... const markers = []; // 存储标记的数组 // 添加标记到地图和markers数组中 yourData.forEach((item) => { const point = new BMap.Point(item.lng, item.lat); const marker = new BMap.Marker(point); map.addOverlay(marker); markers.push(marker); }); // 创建聚合器并设置参数 const markerClusterer = new BMapLib.MarkerClusterer(map, { markers: markers, }); // ... } ``` 确保替换`yourData`为你的标记数据数组,每个标记的经度和纬度分别存储在`item.lng`和`item.lat`中。 4. 在Vue组件中添加地图容器的HTML代码。可以在组件模板中添加以下代码: ```html <template> <div id="map-container" style="width: 100%; height: 400px;"></div> </template> ``` 确保根据需要设置地图容器的宽度和高度。 通过以上步骤,你就可以在Vue项目中实现百度地图聚合效果了。记得在百度地图开放平台申请并获取到API密钥,并替换代码中的`YOUR_API_KEY`。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值