百度地图API 在使用点聚合时,如果放大、缩小或移动地图时,添加的文字标签会消失

问题:如题,百度地图API 在使用点聚合时,如果放大、缩小或移动地图时,添加的文字标签(label)会消失。
原因:API代码中的map.removeOverlay(marker),在这句话执行的时候,会自动将marker.label =null;
解决:在每次removeOverlay之前先获取到label,方法为getLabel,removeOverlay之后再设置label,方法为setLabel。
完整的代码为将http://api.map.baidu.com/library/MarkerClusterer/1.2/src/MarkerClusterer_min.js的代码完全替换为下列代码:

var BMapLib = window.BMapLib = BMapLib || {};
 (function() {
    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 BMap.Bounds(newSW, newNE)
    };
    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 BMap.Bounds(new BMap.Point(minX, minY), new BMap.Point(maxX, maxY))
    };
    var getRange = function(i, mix, max) {
        mix && (i = Math.max(i, mix));
        max && (i = Math.min(i, max));
        return i
    };
    var isArray = function(source) {
        return '[object Array]' === Object.prototype.toString.call(source)
    };
    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
    };
    var MarkerClusterer = 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)
    };
    MarkerClusterer.prototype.addMarkers = function(markers) {
        for (var i = 0,
        len = markers.length; i < len; i++) {
            this._pushMarkerTo(markers[i])
        }
        this._createClusters()
    };
    MarkerClusterer.prototype._pushMarkerTo = function(marker) {
        var index = indexOf(marker, this._markers);
        if (index === -1) {
            marker.isInCluster = false;
            this._markers.push(marker)
        }
    };
    MarkerClusterer.prototype.addMarker = function(marker) {
        this._pushMarkerTo(marker);
        this._createClusters()
    };
    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())) {
                this._addToClosestCluster(marker)
            }
        }
    };
    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)) {
            clusterToAddTo.addMarker(marker)
        } else {
            var cluster = new Cluster(this);
            cluster.addMarker(marker);
            this._clusters.push(cluster)
        }
    };
    MarkerClusterer.prototype._clearLastClusters = function() {
        for (var i = 0,
        cluster; cluster = this._clusters[i]; i++) {
            cluster.remove()
        }
        this._clusters = [];
        this._removeMarkersFromCluster()
    };
    MarkerClusterer.prototype._removeMarkersFromCluster = function() {
        for (var i = 0,
        marker; marker = this._markers[i]; i++) {
            marker.isInCluster = false
        }
    };
    MarkerClusterer.prototype._removeMarkersFromMap = function() {
        for (var i = 0,
        marker; marker = this._markers[i]; i++) {
            marker.isInCluster = false;
            tmplabel = marker.getLabel();
            this._map.removeOverlay(marker);
            marker.setLabel(tmplabel)
        }
    };
    MarkerClusterer.prototype._removeMarker = function(marker) {
        var index = indexOf(marker, this._markers);
        if (index === -1) {
            return false
        }
        tmplabel = marker.getLabel();
        this._map.removeOverlay(marker);
        marker.setLabel(tmplabel);
        this._markers.splice(index, 1);
        return true
    };
    MarkerClusterer.prototype.removeMarker = function(marker) {
        var success = this._removeMarker(marker);
        if (success) {
            this._clearLastClusters();
            this._createClusters()
        }
        return success
    };
    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
    };
    MarkerClusterer.prototype.clearMarkers = function() {
        this._clearLastClusters();
        this._removeMarkersFromMap();
        this._markers = []
    };
    MarkerClusterer.prototype._redraw = function() {
        this._clearLastClusters();
        this._createClusters()
    };
    MarkerClusterer.prototype.getGridSize = function() {
        return this._gridSize
    };
    MarkerClusterer.prototype.setGridSize = function(size) {
        this._gridSize = size;
        this._redraw()
    };
    MarkerClusterer.prototype.getMaxZoom = function() {
        return this._maxZoom
    };
    MarkerClusterer.prototype.setMaxZoom = function(maxZoom) {
        this._maxZoom = maxZoom;
        this._redraw()
    };
    MarkerClusterer.prototype.getStyles = function() {
        return this._styles
    };
    MarkerClusterer.prototype.setStyles = function(styles) {
        this._styles = styles;
        this._redraw()
    };
    MarkerClusterer.prototype.getMinClusterSize = function() {
        return this._minClusterSize
    };
    MarkerClusterer.prototype.setMinClusterSize = function(size) {
        this._minClusterSize = size;
        this._redraw()
    };
    MarkerClusterer.prototype.isAverageCenter = function() {
        return this._isAverageCenter
    };
    MarkerClusterer.prototype.getMap = function() {
        return this._map
    };
    MarkerClusterer.prototype.getMarkers = function() {
        return this._markers
    };
    MarkerClusterer.prototype.getClustersCount = function() {
        var count = 0;
        for (var i = 0,
        cluster; cluster = this._clusters[i]; i++) {
            cluster.isReal() && count++
        }
        return count
    };
    function Cluster(markerClusterer) {
        this._markerClusterer = markerClusterer;
        this._map = markerClusterer.getMap();
        this._minClusterSize = markerClusterer.getMinClusterSize();
        this._isAverageCenter = markerClusterer.isAverageCenter();
        this._center = null;
        this._markers = [];
        this._gridBounds = null;
        this._isReal = false;
        this._clusterMarker = new BMapLib.TextIconOverlay(this._center, this._markers.length, {
            "styles": this._markerClusterer.getStyles()
        })
    }
    Cluster.prototype.addMarker = function(marker) {
        if (this.isMarkerInCluster(marker)) {
            return false
        }
        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 BMap.Point(lng, lat);
                this.updateGridBounds()
            }
        }
        marker.isInCluster = true;
        this._markers.push(marker);
        var len = this._markers.length;
        if (len < this._minClusterSize) {
            this._map.addOverlay(marker);
            return true
        } else if (len === this._minClusterSize) {
            for (var i = 0; i < len; i++) {
                tmplabel = this._markers[i].getLabel();
                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
    };
    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
    };
    Cluster.prototype.isMarkerInClusterBounds = function(marker) {
        return this._gridBounds.containsPoint(marker.getPosition())
    };
    Cluster.prototype.isReal = function(marker) {
        return this._isReal
    };
    Cluster.prototype.updateGridBounds = function() {
        var bounds = new BMap.Bounds(this._center, this._center);
        this._gridBounds = getExtendedBounds(this._map, bounds, this._markerClusterer.getGridSize())
    };
    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++) {
                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)
        })
    };
    Cluster.prototype.remove = function() {
        for (var i = 0,
        m; m = this._markers[i]; i++) {
            var tmplabel = this._markers[i].getLabel();
            this._markers[i].getMap() && this._map.removeOverlay(this._markers[i]);
            this._markers[i].setLabel(tmplabel)
        }
        this._map.removeOverlay(this._clusterMarker);
        this._markers.length = 0;
        delete this._markers
    }
    Cluster.prototype.getBounds = function() {
        var bounds = new BMap.Bounds(this._center, this._center);
        for (var i = 0,
        marker; marker = this._markers[i]; i++) {
            bounds.extend(marker.getPosition())
        }
        return bounds
    };
    Cluster.prototype.getCenter = function() {
        return this._center
    }
})();
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,658评论 6 496
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,482评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,213评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,395评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,487评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,523评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,525评论 3 414
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,300评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,753评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,048评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,223评论 1 343
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,905评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,541评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,168评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,417评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,094评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,088评论 2 352

推荐阅读更多精彩内容