自律给你自由
需求
今天公司有一个小需求,将热力图显示在地图上,由于没有精准的世界地图数据,也没有对接百度/高德的地图数据,仅仅使用geojson渲染出一个大致的世界地图,然后将热力图根据坐标显示在这个echarts渲染的地图上。
思路
- 将世界地图的geojson数据注入到echarts中使其渲染出地图
- 将热力图地理坐标数据重新组合为数组形式
- 将组合完的热力图数据匹配到地图上
代码
<!doctype html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport"content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>echarts上热力下地图</title>
</head>
<body>
<div style="width: 800px;height: 500px;border: 1px solid #ddd;" id="main"></div>
<!-- 引用BootCDN的jq -->
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
<!-- 引用BootCDN的echarts -->
<script src="https://cdn.bootcdn.net/ajax/libs/echarts/4.6.0/echarts.min.js"></script>
<script>var geoCoordMap = {"zh":[113.65,34.76],"za":[13.65,3.76],"zb":[50.65,35.6],"zc":[36.65,54.76],"zd":[11.65,74.76],"ze":[48.65,45.76],"zf":[52.65,86.76],"zg":[55.65,99.76],"zi":[55.65,76],};/*** 将坐标数据封装成为数组* */var convertData = function (data) {var res = [];for (var i = 0; i < data.length; i++) {var geoCoord = geoCoordMap[data[i].name];if (geoCoord) {res.push(geoCoord.concat(data[i].value));}}return res;};var myChart = echarts.init(document.getElementById('main'));$.get('world.json', function (geoJson) {echarts.registerMap('world', geoJson);var option = {visualMap: {min: 0,max: 500,splitNumber: 5,inRange: {color: ['#d94e5d','#eac736','#50a3ba'].reverse()},textStyle: {color: '#fff'}},geo: {map: 'world'},series: [{name: '活跃人数分布',type: 'heatmap',coordinateSystem: 'geo',data: convertData([{name: "zh"},{name: "za"},{name: "zb"},{name: "zc"},{name: "zd"},{name: "ze"},{name: "zf"},{name: "zg"},{name: "zi"}])}]};myChart.setOption(option);});</script>
</body>
</html>
效果
后续
后面还有一个需求是热力图数据与柱状图联动,这里将 geoCoordMap 变量抽出来,变成全局变量,当柱状图被点击时,将其中数据更换,重新渲染即可。