官方demo:http://lbsyun.baidu.com/jsdemo.htm#c1_4
上手很簡單,主要是利用第三方js包(TextIconOverlay和MarkerClusterer)實現的。其中TextIconOverlay負責樣式展示,MarkerClusterer負責聚合點邏輯計算。api地址:http://api.map.baidu.com/library/TextIconOverlay/1.2/docs/help.html
簡單的展示還是很好用,但是實際工作中,需要展示自定義文字,看完api后發現並不能滿足實際需求。沒辦法,只能嘗試着看看源碼怎么實現的,於是從http://api.map.baidu.com/library/TextIconOverlay/1.2/src/TextIconOverlay.js和http://api.map.baidu.com/library/MarkerClusterer/1.2/src/MarkerClusterer.js拷貝源碼到本地。
在MarkerClusterer.js中發現代碼:
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); }); };
注意到代碼:
this._clusterMarker.setText(this._markers.length);
於是更改為:
this._clusterMarker.setText('自定義文字'+this._markers.length);
然后前端報錯:
TypeError: Cannot read property 'url' of undefined
at BMapLib.TextIconOverlay.TextIconOverlay._buildCssText
於是去TextIconOverlay.js文件注意到代碼:
TextIconOverlay.prototype._updateCss = function () { var style = this.getStyleByText(this._text, this._styles); this._domElement.style.cssText = this._buildCssText(style); console.log(this._domElement.style.cssText); };
這里使用getStyleByText方法拿到的style為null,再看:
TextIconOverlay.prototype.getStyleByText = function (text, styles) { var count = parseInt(text); var index = parseInt(count / 10); index = Math.max(0, index); index = Math.min(index, styles.length - 1); return styles[index]; }
發現如果text為字符串時,很大概率會報NAN的錯,導致style拿到為null,修改代碼如下:
TextIconOverlay.prototype.getStyleByText = function (text, styles) { var count = 0; if (typeof text == 'number') { count = parseInt(text); } if (typeof text == 'string') { count = text.replace(/[^0-9]/ig, ""); } var index = parseInt(count / 10); index = Math.max(0, index); index = Math.min(index, styles.length - 1); return styles[index]; }
這里根據自己的需求修改代碼。我這樣改代碼是因為自定義字符串中沒有數字,如果有數字這樣改就不合適了。
這里再提供另外一種思路:TextIconOverlay其實就是一個自定義的Overlay。還可以自定義一個Overlay,結合MarkerClusterer.js完成。有興趣的朋友可以嘗試下。