高德地图-点聚合-点击事件(弹出窗口)-vue

说明

高德地图2.0  +  vue

初始化地图

/**  初始化地图  **/
    initMap(){
      AMapLoader.load({
        key:"",  // 申请好的Web端开发者Key,首次调用 load 时必填
        version:"2.0",      // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
        // plugins:[''],       // 需要使用的的插件列表,如比例尺'AMap.Scale'等
        plugins: ['AMap.ToolBar','AMap.Scale', 'AMap.HawkEye','AMap.MapType','AMap.Geolocation','AMap.AutoComplete','AMap.PlaceSearch','AMap.MarkerCluster'],     // 需要使用的的插件列表,如比例尺'AMap.Scale'等
      }).then((AMap)=>{
        this.map = new AMap.Map("container",{  //设置地图容器id
          viewMode:"3D",    //是否为3D地图模式
          zoom:12,           //初始化地图级别
          center:[116.39, 39.92], //初始化地图中心点位置
          // mapStyle: "amap://styles/whitesmoke", //设置地图的显示样式
        });

        this.getRealTimeWarnEquList()
        // 创建一个地图信息窗体(InfoWindow)的实例,并设置了偏移量
        this.infoWindow = new AMap.InfoWindow({ offset: new AMap.Pixel(0, -30) });
      }).catch(e=>{
        console.log(e);
      })
    },

获取数据并将经纬度等信息添加到地图标记点中


    //获取实时告警设备列表
    getRealTimeWarnEquList(){
      realTimeWarnEquList().then(response => {

        this.realTimeWarnEqus = response.rows;

        var points = []
        // 添加标记点   后续弹窗 需要用到添加的信息
        if (this.realTimeWarnEqus){
          for (const data of this.realTimeWarnEqus) {
            var address = data.dept.deptName + " " + data.address
            if (data.longitude!=undefined && data.latitude!=undefined){
              // this.addMarkers(data.equipment.userName,data.equipment.userPhone,data.startTime,address,data.equipment.longitude,data.equipment.latitude);
              var dataInfo = {
                userName: data.userName,
                userPhone: data.userPhone,
                startTime: "2024-02-23 14:15:00",
                address: address,
                longitude: data.longitude,
                latitude: data.latitude
              }
              points.push({ lnglat: [data.longitude, data.latitude] , dataInfo: dataInfo });
            }
          }
        }
        this.points = points
        this.gridSize = 60

        // 地图标记点样式
        this.addCluster(2);
      });
    },

地图标记点样式


    addCluster(tag) {
      if (this.cluster) {
        this.cluster.setMap(null);
      }
      if (tag == 2) {//完全自定义
        this.cluster = new AMap.MarkerCluster(this.map, this.points, {
          gridSize: this.gridSize, // 设置网格像素大小
          renderClusterMarker: this._renderClusterMarker, // 自定义聚合点样式
          renderMarker: this._renderMarker, // 自定义非聚合点样式
          //*****
          maxZoom: 20 // 设置缩放级别  当两个坐标点重合时 也能将其聚合
        });
      } else if (tag == 1) {//自定义图标
        var sts = [{
          url: "//a.amap.com/jsapi_demos/static/images/blue.png",
          size: new AMap.Size(32, 32),
          offset: new AMap.Pixel(-16, -16)
        }, {
          url: "//a.amap.com/jsapi_demos/static/images/green.png",
          size: new AMap.Size(32, 32),
          offset: new AMap.Pixel(-16, -16)
        }, {
          url: "//a.amap.com/jsapi_demos/static/images/orange.png",
          size: new AMap.Size(36, 36),
          offset: new AMap.Pixel(-18, -18)
        }, {
          url: "//a.amap.com/jsapi_demos/static/images/red.png",
          size: new AMap.Size(48, 48),
          offset: new AMap.Pixel(-24, -24)
        }, {
          url: "//a.amap.com/jsapi_demos/static/images/darkRed.png",
          size: new AMap.Size(48, 48),
          offset: new AMap.Pixel(-24, -24)
        }];
        this.cluster = new AMap.MarkerCluster(this.map, this.points, {
          styles: sts,
          gridSize: this.gridSize
        });
      } else {//默认样式
        this.cluster = new AMap.MarkerCluster(this.map, this.points, {gridSize: this.gridSize});
      }
    },

自定义标记点 聚合/非聚合 样式


    /**聚合点样式*/
    _renderClusterMarker(context) {

      var factor = Math.pow(context.count / this.points.length, 1 / 18);
      var div = document.createElement('div');
      var Hue = 180 - factor * 180;
      var bgColor = 'hsla(' + Hue + ',100%,40%,0.7)';
      var fontColor = 'hsla(' + Hue + ',100%,90%,1)';
      var borderColor = 'hsla(' + Hue + ',100%,40%,1)';
      var shadowColor = 'hsla(' + Hue + ',100%,90%,1)';
      div.style.backgroundColor = bgColor;
      var size = Math.round(30 + Math.pow(context.count / this.points.length, 1 / 5) * 15);
      div.style.width = div.style.height = size + 'px';
      div.style.border = 'solid 1px ' + borderColor;
      div.style.borderRadius = size / 2 + 'px';
      div.style.boxShadow = '0 0 5px ' + shadowColor;
      div.innerHTML = context.count;
      div.style.lineHeight = size + 'px';
      div.style.color = fontColor;
      div.style.fontSize = '14px';
      div.style.textAlign = 'center';

      context.marker.on('click', () => {
          var info = [];
          info.push("<div class='input-cardcontent-window-card' style='width: 350px;'>")
          info.push("<div style='padding:0px 0px 0px 0px;'>")
          info.push("<div style='line-height:30px ;'><img style='float: left;height: 25px' src='/images/warn.png'/><span style='color: red;line-height: 30px;'><i style='margin-right:5px;color:red;'></i>告警信息 </span></div >")
          info.push("<div style='height: 200px;overflow: auto;'>")

        // 定义一个内部方法  用于 获取聚合数据,并且将聚合的数据 添加到 弹窗中
          function setData(count,datas) {
              if (count == datas.length){
                for (let data of datas){
                  info.push("<div class='row' style='margin-top: 20px; border-bottom: 1px solid #ccc; padding-bottom: 10px;'>");
                  info.push("<div style='width: 30%;float: left'><span style='float: right;border-right: 20px;'>联系人:</span></div><div style='width: 70%;float: left;'><span style='margin-left: 20px;'>" + data.dataInfo.userName + "</span></div><br/>");
                  info.push("<div style='width: 30%;float: left'><span style='float: right;border-right: 20px;'>联系电话:</span></div><div style='width: 70%;float: left;'><span style='margin-left: 20px;'>" + data.dataInfo.userPhone + "</span></div><br/>");
                  info.push("<div style='width: 30%;float: left'><span style='float: right;border-right: 20px;'>告警地点:</span></div><div style='width: 70%;float: left;'><span style='margin-left: 20px;'>" + data.dataInfo.address + "</span></div><br/>");
                  info.push("</div>");
                  //   添加数据
                }
              }else {
                for (let data of datas){
                  setData(data._amapMarker.count,data._amapMarker.originData[0])
                }
              }
          }

          // 调用 内部方法,将 数据 添加到弹窗中
          setData(context.count,context.clusterData)
          info.push("</div></div></div>")
          this.infoWindow = new AMap.InfoWindow({
            offset: new AMap.Pixel(0, -25),//偏移量
            content: info.join("")  //使用默认信息窗体框样式,显示信息内容
          });



        // 阻止地图滚轮事件传播到地图
        this.infoWindow.on('mousewheel', (event) => {
          event.stopPropagation(); // 阻止事件传播到地图
        });

        // 监听弹窗内部的滚轮事件
        this.infoWindow.getContentDom().addEventListener('mousewheel', (event) => {
          event.stopPropagation(); // 阻止事件传播到地图
          // 处理弹窗内容的滚动
          // 你可以根据需要自定义滚动行为,例如使用滚动条等
        });

        // 在地图上打开信息窗体,并将其显示在指定的位置。
        this.infoWindow.open(this.map, context.marker.getPosition());
      });

      // 设置地图标记(Marker)的偏移量和内容。
      context.marker.setOffset(new AMap.Pixel(-size / 2, -size / 2));
      context.marker.setContent(div)
    },


    /*** 非聚合点样式*/
    _renderMarker(context) {
      var offset = new AMap.Pixel(-9, -9);
      //非聚合点样式
        let data = context.data[0].dataInfo
        let content = '<div style=" height: 30px;width:20px"><img src="http://webapi.amap.com/theme/v1.3/markers/n/mark_r.png" style="width: 100%;height:100%"/></div>';
        context.marker.setLabel({
          direction: 'bottom',
          offset: new AMap.Pixel(0, 0),  //设置文本标注偏移量
        });
        //此处 需要用  ()=>{} 否则无法触发点击数据
        context.marker.on('click', () => {
          var info = [];
          info.push("<div class='input-cardcontent-window-card' style='width: 350px;'>")
          info.push("<div style='padding:0px 0px 0px 0px;'>")
          info.push("<div style='line-height:30px ;'><img style='float: left;height: 25px' src='/images/warn.png'/><span style='color: red;line-height: 30px;'><i style='margin-right:5px;color:red;'></i>告警信息 </span></div >")
          info.push("<div class='row'>")
          info.push("<div style='width: 30%;float: left'><span style='float: right;border-right: 20px;'>联系人:</span></div><div style='width: 70%;float: left;'><span style='margin-left: 20px;'>" +  data.userName  + "</span></div><br/>")
          info.push("<div style='width: 30%;float: left'><span style='float: right;border-right: 20px;'>联系电话:</span></div><div style='width: 70%;float: left;'><span style='margin-left: 20px;'>" + data.userPhone + "</span></div><br/>")
          info.push("<div style='width: 30%;float: left'><span style='float: right;border-right: 20px;'>告警地点:</span></div><div style='width: 70%;float: left;'><span style='margin-left: 20px;'>" + data.address  + "</span></div><br/>")
          info.push("</div></div></div>")


          this.infoWindow = new AMap.InfoWindow({
            offset: new AMap.Pixel(0, -15),//弹窗与图标的偏移
            content: info.join("")  //使用默认信息窗体框样式,显示信息内容
          });




          // 阻止地图滚轮事件传播到地图
          this.infoWindow.on('mousewheel', (event) => {
            event.stopPropagation(); // 阻止事件传播到地图
          });

          // 监听弹窗内部的滚轮事件
          this.infoWindow.getContentDom().addEventListener('mousewheel', (event) => {
            event.stopPropagation(); // 阻止事件传播到地图
            // 处理弹窗内容的滚动
            // 你可以根据需要自定义滚动行为,例如使用滚动条等
          });


          this.infoWindow.open(this.map, context.marker.getPosition());
        });

      context.marker.setContent(content);
      context.marker.setOffset(offset);

    },

页面完整代码

<template>
  <div class="app-container">
    <el-row style="height: 100%">
        <div id="container" style="height: 100%"></div>
    </el-row>
  </div>
</template>

<script>
import {realTimeWarnEquList} from "@/api/warn/warn";
import AMapLoader from "@amap/amap-jsapi-loader"

export default {
  name: "WarnMap",
  plugins: ['AMap.ToolBar','AMap.Scale', 'AMap.HawkEye','AMap.MapType','AMap.Geolocation','AMap.AutoComplete','AMap.PlaceSearch','AMap.MarkerCluster'],
  data() {
    return {
      //定时器
      timer: undefined,
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      //实时告警设备
      realTimeWarnEqus: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      marker: undefined,
      map: null,
      gridSize: 60,
      pointsCount: 0,
      points: [],
      cluster: undefined,
      infoWindow: null,
    };
  },

  created() {
    this.initMap();
    this.startQuery();
  },

  destroyed() {
    // 销毁页面时删除定时器
    this.clearTimer();
  },

  methods: {
    // 启动定时查询,一定间隔查询一次,计算状态
    startQuery() {
      // 每隔一段时间执行一次查询函数
      this.timer = setInterval(this.getRealTimeWarnEquList, 5000) // 5000毫秒,即5秒
      // clearInterval(this.timer);
    },

    //清除定时器
    clearTimer(){
      if (this.timer){
        clearInterval(this.timer);
      }
    },

    //获取实时告警设备列表
    getRealTimeWarnEquList(){
      realTimeWarnEquList().then(response => {

        this.realTimeWarnEqus = response.rows;

        var points = []
        // 添加标记点   后续弹窗 需要用到添加的信息
        if (this.realTimeWarnEqus){
          for (const data of this.realTimeWarnEqus) {
            var address = data.dept.deptName + " " + data.address
            if (data.longitude!=undefined && data.latitude!=undefined){
              // this.addMarkers(data.equipment.userName,data.equipment.userPhone,data.startTime,address,data.equipment.longitude,data.equipment.latitude);
              var dataInfo = {
                userName: data.userName,
                userPhone: data.userPhone,
                startTime: "2024-02-23 14:15:00",
                address: address,
                longitude: data.longitude,
                latitude: data.latitude
              }
              points.push({ lnglat: [data.longitude, data.latitude] , dataInfo: dataInfo });
            }
          }
        }
        this.points = points
        this.gridSize = 60

        // 地图标记点样式
        this.addCluster(2);
      });
    },

    /**  初始化地图  **/
    initMap(){
      AMapLoader.load({
        key:"",  // 申请好的Web端开发者Key,首次调用 load 时必填
        version:"2.0",      // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
        // plugins:[''],       // 需要使用的的插件列表,如比例尺'AMap.Scale'等
        plugins: ['AMap.ToolBar','AMap.Scale', 'AMap.HawkEye','AMap.MapType','AMap.Geolocation','AMap.AutoComplete','AMap.PlaceSearch','AMap.MarkerCluster'],     // 需要使用的的插件列表,如比例尺'AMap.Scale'等
      }).then((AMap)=>{
        this.map = new AMap.Map("container",{  //设置地图容器id
          viewMode:"3D",    //是否为3D地图模式
          zoom:12,           //初始化地图级别
          center:[116.39, 39.92], //初始化地图中心点位置
          // mapStyle: "amap://styles/whitesmoke", //设置地图的显示样式
        });

        this.getRealTimeWarnEquList()
        // 创建一个地图信息窗体(InfoWindow)的实例,并设置了偏移量
        this.infoWindow = new AMap.InfoWindow({ offset: new AMap.Pixel(0, -30) });
      }).catch(e=>{
        console.log(e);
      })
    },

    /**聚合点样式*/
    _renderClusterMarker(context) {

      var factor = Math.pow(context.count / this.points.length, 1 / 18);
      var div = document.createElement('div');
      var Hue = 180 - factor * 180;
      var bgColor = 'hsla(' + Hue + ',100%,40%,0.7)';
      var fontColor = 'hsla(' + Hue + ',100%,90%,1)';
      var borderColor = 'hsla(' + Hue + ',100%,40%,1)';
      var shadowColor = 'hsla(' + Hue + ',100%,90%,1)';
      div.style.backgroundColor = bgColor;
      var size = Math.round(30 + Math.pow(context.count / this.points.length, 1 / 5) * 15);
      div.style.width = div.style.height = size + 'px';
      div.style.border = 'solid 1px ' + borderColor;
      div.style.borderRadius = size / 2 + 'px';
      div.style.boxShadow = '0 0 5px ' + shadowColor;
      div.innerHTML = context.count;
      div.style.lineHeight = size + 'px';
      div.style.color = fontColor;
      div.style.fontSize = '14px';
      div.style.textAlign = 'center';

      context.marker.on('click', () => {
          var info = [];
          info.push("<div class='input-cardcontent-window-card' style='width: 350px;'>")
          info.push("<div style='padding:0px 0px 0px 0px;'>")
          info.push("<div style='line-height:30px ;'><img style='float: left;height: 25px' src='/images/warn.png'/><span style='color: red;line-height: 30px;'><i style='margin-right:5px;color:red;'></i>告警信息 </span></div >")
          info.push("<div style='height: 200px;overflow: auto;'>")

        // 定义一个内部方法  用于 获取聚合数据,并且将聚合的数据 添加到 弹窗中
          function setData(count,datas) {
              if (count == datas.length){
                for (let data of datas){
                  info.push("<div class='row' style='margin-top: 20px; border-bottom: 1px solid #ccc; padding-bottom: 10px;'>");
                  info.push("<div style='width: 30%;float: left'><span style='float: right;border-right: 20px;'>联系人:</span></div><div style='width: 70%;float: left;'><span style='margin-left: 20px;'>" + data.dataInfo.userName + "</span></div><br/>");
                  info.push("<div style='width: 30%;float: left'><span style='float: right;border-right: 20px;'>联系电话:</span></div><div style='width: 70%;float: left;'><span style='margin-left: 20px;'>" + data.dataInfo.userPhone + "</span></div><br/>");
                  info.push("<div style='width: 30%;float: left'><span style='float: right;border-right: 20px;'>告警地点:</span></div><div style='width: 70%;float: left;'><span style='margin-left: 20px;'>" + data.dataInfo.address + "</span></div><br/>");
                  info.push("</div>");
                  //   添加数据
                }
              }else {
                for (let data of datas){
                  setData(data._amapMarker.count,data._amapMarker.originData[0])
                }
              }
          }

          // 调用 内部方法,将 数据 添加到弹窗中
          setData(context.count,context.clusterData)
          info.push("</div></div></div>")
          this.infoWindow = new AMap.InfoWindow({
            offset: new AMap.Pixel(0, -25),//偏移量
            content: info.join("")  //使用默认信息窗体框样式,显示信息内容
          });



        // 阻止地图滚轮事件传播到地图
        this.infoWindow.on('mousewheel', (event) => {
          event.stopPropagation(); // 阻止事件传播到地图
        });

        // 监听弹窗内部的滚轮事件
        this.infoWindow.getContentDom().addEventListener('mousewheel', (event) => {
          event.stopPropagation(); // 阻止事件传播到地图
          // 处理弹窗内容的滚动
          // 你可以根据需要自定义滚动行为,例如使用滚动条等
        });

        // 在地图上打开信息窗体,并将其显示在指定的位置。
        this.infoWindow.open(this.map, context.marker.getPosition());
      });

      // 设置地图标记(Marker)的偏移量和内容。
      context.marker.setOffset(new AMap.Pixel(-size / 2, -size / 2));
      context.marker.setContent(div)
    },


    /*** 非聚合点样式*/
    _renderMarker(context) {
      var offset = new AMap.Pixel(-9, -9);
      //非聚合点样式
        let data = context.data[0].dataInfo
        let content = '<div style=" height: 30px;width:20px"><img src="http://webapi.amap.com/theme/v1.3/markers/n/mark_r.png" style="width: 100%;height:100%"/></div>';
        context.marker.setLabel({
          direction: 'bottom',
          offset: new AMap.Pixel(0, 0),  //设置文本标注偏移量
        });
        //此处 需要用  ()=>{} 否则无法触发点击数据
        context.marker.on('click', () => {
          var info = [];
          info.push("<div class='input-cardcontent-window-card' style='width: 350px;'>")
          info.push("<div style='padding:0px 0px 0px 0px;'>")
          info.push("<div style='line-height:30px ;'><img style='float: left;height: 25px' src='/images/warn.png'/><span style='color: red;line-height: 30px;'><i style='margin-right:5px;color:red;'></i>告警信息 </span></div >")
          info.push("<div class='row'>")
          info.push("<div style='width: 30%;float: left'><span style='float: right;border-right: 20px;'>联系人:</span></div><div style='width: 70%;float: left;'><span style='margin-left: 20px;'>" +  data.userName  + "</span></div><br/>")
          info.push("<div style='width: 30%;float: left'><span style='float: right;border-right: 20px;'>联系电话:</span></div><div style='width: 70%;float: left;'><span style='margin-left: 20px;'>" + data.userPhone + "</span></div><br/>")
          info.push("<div style='width: 30%;float: left'><span style='float: right;border-right: 20px;'>告警地点:</span></div><div style='width: 70%;float: left;'><span style='margin-left: 20px;'>" + data.address  + "</span></div><br/>")
          info.push("</div></div></div>")


          this.infoWindow = new AMap.InfoWindow({
            offset: new AMap.Pixel(0, -15),//弹窗与图标的偏移
            content: info.join("")  //使用默认信息窗体框样式,显示信息内容
          });




          // 阻止地图滚轮事件传播到地图
          this.infoWindow.on('mousewheel', (event) => {
            event.stopPropagation(); // 阻止事件传播到地图
          });

          // 监听弹窗内部的滚轮事件
          this.infoWindow.getContentDom().addEventListener('mousewheel', (event) => {
            event.stopPropagation(); // 阻止事件传播到地图
            // 处理弹窗内容的滚动
            // 你可以根据需要自定义滚动行为,例如使用滚动条等
          });


          this.infoWindow.open(this.map, context.marker.getPosition());
        });

      context.marker.setContent(content);
      context.marker.setOffset(offset);

    },

    addCluster(tag) {
      if (this.cluster) {
        this.cluster.setMap(null);
      }
      if (tag == 2) {//完全自定义
        this.cluster = new AMap.MarkerCluster(this.map, this.points, {
          gridSize: this.gridSize, // 设置网格像素大小
          renderClusterMarker: this._renderClusterMarker, // 自定义聚合点样式
          renderMarker: this._renderMarker, // 自定义非聚合点样式
          //*****
          maxZoom: 20 // 设置缩放级别  当两个坐标点重合时 也能将其聚合
        });
      } else if (tag == 1) {//自定义图标
        var sts = [{
          url: "//a.amap.com/jsapi_demos/static/images/blue.png",
          size: new AMap.Size(32, 32),
          offset: new AMap.Pixel(-16, -16)
        }, {
          url: "//a.amap.com/jsapi_demos/static/images/green.png",
          size: new AMap.Size(32, 32),
          offset: new AMap.Pixel(-16, -16)
        }, {
          url: "//a.amap.com/jsapi_demos/static/images/orange.png",
          size: new AMap.Size(36, 36),
          offset: new AMap.Pixel(-18, -18)
        }, {
          url: "//a.amap.com/jsapi_demos/static/images/red.png",
          size: new AMap.Size(48, 48),
          offset: new AMap.Pixel(-24, -24)
        }, {
          url: "//a.amap.com/jsapi_demos/static/images/darkRed.png",
          size: new AMap.Size(48, 48),
          offset: new AMap.Pixel(-24, -24)
        }];
        this.cluster = new AMap.MarkerCluster(this.map, this.points, {
          styles: sts,
          gridSize: this.gridSize
        });
      } else {//默认样式
        this.cluster = new AMap.MarkerCluster(this.map, this.points, {gridSize: this.gridSize});
      }
    },
  }
};
</script>

截图:

  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值