vue 高德地图使用热力图

在这里插入图片描述

代码

  • 在public/index.html中加入:
  • <script src="https://webapi.amap.com/maps?v=1.4.15&key=您申请的key值"></script>
    
    <template>
      <div class="box">
        <div id="container"></div>
        <div class="input-card" style="width: auto;">
          <div class="input-item">
            <button class="btn" @click="heatmap.show()">显示热力图</button>
          </div>
          <div class="input-item">
            <button class="btn" @click="heatmap.hide()">关闭热力图</button>
          </div>
        </div>
      </div>
    </template>
    
    <script>
    // https://a.amap.com/jsapi_demos/static/resource/heatmapData.js
    // 下面数据为热力图数据,可以下载上面网址数据进行测试
    import heatmapData  from '@/assets/js/heatmapData'; 
    
    export default {
      data() {
        return {
          map: null,
          heatmap: null
        };
      },
      mounted() {
        // 延迟加载,防止出现AMap not defined
        setTimeout(() => {
          this.initMap();
          this.createHeatMap();
        }, 1000);
      },
      beforeDestroy() {
        this.map && this.map.destroy();
      },
      methods: {
        initMap() {
          this.map = new AMap.Map("container", {
            resizeEnable: true,
            center: [116.480983, 39.989628],
            zoom: 11,
            mapStyle: 'macaron', // 马卡龙(其他样式可在高德api中查找进行修改)
            //自定义地图样式:https://lbs.amap.com/dev/mapstyle/index
          });
        },
        //判断浏览区是否支持canvas
        isSupportCanvas() {
          let elem = document.createElement("canvas");
          return !!(elem.getContext && elem.getContext("2d"));
        },
        createHeatMap() {
          if (!this.isSupportCanvas()) {
            return this.$message({
              message: '热力图仅对支持canvas的浏览器适用,您所使用的浏览器不能使用热力图功能,请换个浏览器试试。',
              type: 'warning'
            });
          }
          let __this = this;
          this.map.plugin(["AMap.Heatmap"], function() {
            //初始化heatmap对象
            __this.heatmap = new AMap.Heatmap(__this.map, {
              radius: 25, //给定半径
              opacity: [0, 0.8],
            });
            //设置数据集:该数据为北京部分“公园”数据
            __this.heatmap.setDataSet({
              data: heatmapData,
              max: 100
            });
          });
        }
      }
    };
    </script>
    
    <style scoped>
    @import url("https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css");
    
    .box{
      width: 100%;
      height: 600px;
      border-radius: 12px;
      background: #fff;
    }
    #container {
      margin: 0;
      padding: 0;
      width: 100%;
      height: 100%;
    }
    </style>
    
    

猜你喜欢

转载自blog.csdn.net/sinat_17775997/article/details/126452109