腾讯地图实现自定义icon,折叠点自动归整为正数

最终实现效果,相同的类型就会折叠:


效果图.png

js代码

    creatMap() {
      // 定义地图默认中心点坐标
      var center = new TMap.LatLng(22.971870333, 113.373452833);
      //创建map对象,初始化地图
      var map = new TMap.Map("container", {
        center: center, //设置地图中心点坐标
        zoom: 16 //设置地图缩放级别
      });
      this.map = map;
      this.markers = [];
      this.creatMarkerCluster("Battery", "1");
      this.creatMarkerCluster("Bicycle", "2");
      this.creatMarkerCluster("Cabinet", "3");
      // this.creatRegion();  生成多边形区域代码
      // this.creatPark();  生成多边形区域代码
    },
    // 生成点聚焦函数
    creatMarkerCluster(type, deviceType) {
      let imgIconList = new Array(3);
      imgIconList[0] = imgIcon1;
      imgIconList[1] = imgIcon2;
      imgIconList[2] = imgIcon3;
      // debugger
      let map = this.map;
      this.markers = [];
      // 1、标点
      let markerCluster = new TMap.MarkerCluster({
        id: "container" + type,
        map: map, //指定地图容器
        enableDefaultStyle: false, // 启用默认样式
        minimumClusterSize: 2,
        //点标记数据数组
        geometries: this.convertMarkers(deviceType), //this.markers
        zoomOnClick: true, // 点击簇时放大至簇内点分离
        gridSize: 60, // 聚合算法的可聚合距离
        averageCenter: true, // 每个聚和簇的中心是否应该是聚类中所有标记的平均值
        maxZoom: 25 // 采用聚合策略的最大缩放级别
      });

      var clusterBubbleList = [];
      var markerGeometries = [];
      var marker = null;

      // 监听聚合簇变化
      markerCluster.on("cluster_changed", function(e) {
        // 销毁旧聚合簇生成的覆盖物
        if (clusterBubbleList.length) {
          clusterBubbleList.forEach(function(item) {
            item.destroy();
          });
          clusterBubbleList = [];
        }
        markerGeometries = [];

        // 根据新的聚合簇数组生成新的覆盖物和点标记图层
        // debugger
        var clusters = markerCluster.getClusters();
        clusters.forEach((item,index) => {
          console.log(clusters,'clusters')
          if (item.geometries.length > 1) {
            let clusterBubble = new ClusterBubble({
              map,
              position: item.center,
              content: item.geometries.length
            });
            clusterBubble.on("click", () => {
              map.fitBounds(item.bounds);
            });
            clusterBubbleList.push(clusterBubble);
          } else {
            markerGeometries.push({
              position: item.center,
              properties: {
                //自定义属性
                title: `marker${index}`,
                sn: item.geometries[0].properties.sn
              }
            });
          }
        });
        if (marker) {
          // 已创建过点标记图层,直接更新数据
          marker.setGeometries(markerGeometries);
        } else {
          // 创建点标记图层
          marker = new TMap.MultiMarker({
            map,
            styles: {
              default: new TMap.MarkerStyle({
                width: 34,
                height: 42,
                anchor: {
                  x: 17,
                  y: 21
                },
                src: imgIconList[+deviceType - 1]
              })
            },
            geometries: markerGeometries
          });
          //初始化infoWindow
          var infoWindow = new TMap.InfoWindow({
            map: map,
            position: new TMap.LatLng(20, 110),
            offset: { x: -5, y: -32 } //设置信息窗相对position偏移像素
          });
          // 监听标注点击事件
          marker.on("click", function(evt) {
            // console.log(evt, "1111");
            //设置infoWindow
            infoWindow.open(); //打开信息窗
            infoWindow.setPosition(evt.geometry.position); //设置信息窗位置
            infoWindow.setContent(evt.geometry.properties.sn); //设置信息窗内容
          });
        }
      });
      // 以下代码为基于DOMOverlay实现聚合点气泡
      function ClusterBubble(options) {
        TMap.DOMOverlay.call(this, options);
      }

      ClusterBubble.prototype = new TMap.DOMOverlay();

      ClusterBubble.prototype.onInit = function(options) {
        this.content = options.content;
        this.position = options.position;
      };

      // 销毁时需要删除监听器
      ClusterBubble.prototype.onDestroy = function() {
        this.dom.removeEventListener("click", this.onClick);
        this.removeAllListeners();
      };

      ClusterBubble.prototype.onClick = function() {
        this.emit("click");
      };

      // 创建气泡DOM元素
      ClusterBubble.prototype.createDOM = function() {
        var dom = document.createElement("div");
        dom.classList.add(`clusterBubble${type}`);
        dom.innerText = this.content;
        dom.style.cssText = [
          "width: " + 40 + "px;",
          "height: " + 40 + "px;",
          "line-height: " + 40 + "px;"
        ].join(" ");

        // 监听点击事件,实现zoomOnClick
        this.onClick = this.onClick.bind(this);
        // pc端注册click事件,移动端注册touchend事件
        dom.addEventListener("click", this.onClick);
        return dom;
      };
      ClusterBubble.prototype.updateDOM = function() {
        if (!this.map) {
          return;
        }
        // 经纬度坐标转容器像素坐标
        let pixel = this.map.projectToContainer(this.position);

        // 使文本框中心点对齐经纬度坐标点
        let left = pixel.getX() - this.dom.clientWidth / 2 + "px";
        let top = pixel.getY() - this.dom.clientHeight / 2 + "px";
        this.dom.style.transform = `translate(${left}, ${top})`;

        this.emit("dom_updated");
      };
    },
    // 生成点的函数
    convertMarkers(type) {
      let markers = [];
      this.workbenchList.map((item, index) => {   // this.workbenchList起始数据
        if (item.lat && item.lng && item.lat !== "0" && !item.lng !== "0") {
          if (item.deviceType === type) {
            markers.push({
              id: item.id, //点标记唯一标识,后续如果有删除、修改位置等操作,都需要此id
              styleId: "myStyle", //指定样式id
              position: new TMap.LatLng(item.lat, item.lng), //点标记坐标位置
              properties: {
                //自定义属性
                title: `marker${index}`,
                sn: "设备编号:" + item.sn
              }
            });
          }
        }
      });
      return markers;
    },
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容