cesium可视化(一):热力图

146 阅读1分钟

1、原理

使用heatmap.js插件,先生成一个热力图,再在地图上创建一个盒子(如矩形),以纹理的形式把热力图填充到矩形中。

2、引入

由于通过npm安装,然后使用import引入方式存在bug,这里通过在index.html中的script标签引入,然后在使用页面声明h337。

//indet.html
//下载heatmap.js房子public下,然后通过script标签引入
<script type="text/javascript" src="/heatmap.js" ></script>

//使用页面声明h337
declare const h337;
addHeatMap(h337); //调用添加热力图方法

3、热力图实现方法

import * as Cesium from "cesium";
// 创建热力图
const createHeatMap = (max,data,h337) => {
    // 创建元素
    let heatDiv = document.createElement("div");
    heatDiv.setAttribute("style","width:1000px;height:1000px;margin:0px;display:none;");
    heatDiv.id = "heatmap";
    document.body.appendChild(heatDiv);
    //创建热力图对象-- 热力图参数
    let heatMap = h337.create({
        container: heatDiv,
        backgroundColor: "rgba(0,0,0,1)",
        radius: 15,
        maxOpacity: .5,
        minOpacity: 0,
        blur: .75,
        gradient: {
            0: "black",
            0.45: "rgb(0,0,255)",
            0.55: "rgb(0,255,255)",
            0.65: "rgb(0,255,0)",
            0.95: "yellow",
            1: "rgb(255,0,0)"
        },
    });
    // 添加数据
    heatMap.setData({
        max: max,
        data: data
    });
    return heatMap;
};
// 创建矩形 绑定热力图 
let hainanHeatMapLyr = null;
const createRectangle = (coordniate,heatMap) => {
    let obj = document.getElementById("heatmap");
    hainanHeatMapLyr = viewer.imageryLayers.addImageryProvider(
      new Cesium.SingleTileImageryProvider({
        url: obj.childNodes[0].toDataURL("image/png"),
        rectangle: Cesium.Rectangle.fromDegrees(coordniate[0],coordniate[1],coordniate[2],coordniate[3]),
      })
    );
    hainanHeatMapLyr.alpah = 0.3;
}
// 清除热力图
const removeHeatMap = () => {
    if(hainanHeatMapLyr){
        viewer.imageryLayers.remove(hainanHeatMapLyr);
    }
}
//生成随机坐标点
const getData = (len:number) => {
    //构建一些随机数据点
    let points:any = [];
    let max = 0;
    let width = 1000;
    let height = 1000;
    while(len--){
        let val = Math.floor(Math.random() * 100);
        max = Math.max(max,val);
        points.push({
            x: Math.floor(Math.random() * width),
            y: Math.floor(Math.random() * height),
            value: val
        })
    }
    return {max: max, data: points}
};
//添加热力图
const addHeatMap = (h337) => {
    //热力图显示矩形范围
    let coordinate = [105.58453747976795, 16.19456532505111, 113.4837779239999, 22.422961094121227];
    //创建热力图
    let heatMap = createHeatMap(getData(1000).max, getData(1000).data, h337);
    //绑定热力图 
    createRectangle(coordinate, heatMap);
};

4、实现效果

image.png

项目地址:github.com/DLFouge/vue…

欢迎指正与star