张卓
2022-09-29 4ef1c909df36c48f7f040e9ec408fc15e6745e71
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<template>
  <div style="height:100%">
    <div id="container" />
    <div class="input-card" style="width: auto;">
      <div class="input-item">
        <button class="btn" @click="abc">显示热力图</button>
      </div>
      <div class="input-item">
        <button class="btn" @click="heatmap.hide()">关闭热力图</button>
      </div>
    </div>
  </div>
</template>
 
<script>
import { heatmapData } from './heatmapData'
// https://a.amap.com/jsapi_demos/static/resource/heatmapData.js
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: {
    abc() {
      console.log(heatmapData)
      this.heatmap.show()
    },
    initMap() {
      this.map = new AMap.Map('container', {
        resizeEnable: true,
        center: [116.480983, 39.989628],
        zoom: 11
        // mapStyle: 'amap://styles/grey' // 极夜蓝
        // 自定义地图样式:https://lbs.amap.com/dev/mapstyle/index
      })
    },
    // 判断浏览区是否支持canvas
    isSupportCanvas() {
      const elem = document.createElement('canvas')
      return !!(elem.getContext && elem.getContext('2d'))
    },
    createHeatMap() {
      console.log('这是json数据')
      console.log(heatmapData)
      if (!this.isSupportCanvas()) {
        return this.$msg.error(
          '热力图仅对支持canvas的浏览器适用,您所使用的浏览器不能使用热力图功能,请换个浏览器试试。'
        )
      }
      const __this = this
      this.map.plugin(['AMap.Heatmap'], function() {
        // 初始化heatmap对象
        __this.heatmap = new AMap.Heatmap(__this.map, {
          visible: false,
          radius: 50, // 给定半径
          opacity: [0, 0.8]
        })
        // 设置数据集:该数据为北京部分“公园”数据
        __this.heatmap.setDataSet({
          data: heatmapData,
          max: 100
        })
      })
    }
  }
}
</script>
 
<style lang="less" scoped>
@import url("https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css");
 
#container {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}
.input-card .btn {
  margin-right: 1.2rem;
  width: 9rem;
}
</style>