1. 程式人生 > 其它 >百度地圖實現聚合點展示

百度地圖實現聚合點展示

本篇文章介紹的是通過百度地圖api實現聚合點的展示,實現效果如下:

來看看它是怎麼實現的(以vue為例):

  1. 建立地圖容器
 this.baiduMapOut = new BMap.Map(document.getElementById(this.className));
  1. 設定中心點並且支援縮放
 this.baiduMapOut.enableScrollWheelZoom();
 this.baiduMapOut.centerAndZoom(\'中華人民共和國\', 5);
  1. 畫點
 if (this.markerClusterer) {
                    this.markerClusterer.clearMarkers(this.markers);
     }
     for (const point of points) {
    let imgurl = require(\'../../../../assets/images/dataMarket/location-little.png\');
    let iconStop = new BMap.Icon(imgurl, new BMap.Size(32, 34), {
                        anchor: new BMap.Size(23, 20)
                    });
    let pointStop = new BMap.Point(point.lng, point.lat);
    this.points.push(pointStop);
    let markerStop = new BMap.Marker(pointStop, { icon: iconStop });
    this.markers.push(markerStop);
    if (this.markers.length > 0) {
     this.markerClusterer = new BMapLib.MarkerClusterer(this.baiduMapOut, {
                        markers: this.markers
                    });
     }
上述程式碼中 points為從後臺介面中獲取的點的經緯度的集合
關鍵點在於:new BMapLib.MarkerClusterer 將新增的標註markers轉成聚合點展示
注意: 此時會存在地圖初始化 和 畫點的先後順序問題 ,可能導致某些坑,所以務必保證畫點 
      的時候地圖已經完全載入完畢.可以加延時來解決