在地图上添加热力图
热力图(heatmap)是一种通过颜色值把原本抽象、独立的数据展示在地图上的地图表达。热力图可以更直观地展示不同区域(位置)的热度,如景点热度(百度热力图)、海洋盐度、区域影响力等。
SupeMap的JavaScript API提供了热力图图层HeatMapLayer,使用该类可以快速制作热力图。
Step1 初始化地图
制作热力图的第一步,需要初始化地图,并检查浏览器的兼容性。本例使用World地图为底图。
var map, layer, heatMapLayer,
url = "http://www.supermapol.com/iserver/services/vm3sbiax/rest/maps/World",
value = "VZ88xbrMEMpGv4yiisTojgVq",
name = "key";
SuperMap.Credential.CREDENTIAL = new SuperMap.Credential(value, "key");
function init(){
//检查浏览器兼容性
if(!document.createElement('canvas').getContext) {
alert('您的浏览器不支持 canvas,请升级');
return;
}
//初始化地图,添加基本控件
map = new SuperMap.Map("map",{controls: [
new SuperMap.Control.ScaleLine(),
new SuperMap.Control.Zoom(),
new SuperMap.Control.Navigation({
dragPanOptions: {
enableKinetic: true
}
})]
});
map.addControl(new SuperMap.Control.MousePosition());
……
}
分别初始化地图底图和热力图图层:
//初始化地图底图
layer = new SuperMap.Layer.TiledDynamicRESTLayer("World", url, {transparent: true, cacheEnabled: true}, {maxResolution:"auto"});
//初始化热力图图层HeatMapLayer
heatMapLayer = new SuperMap.Layer.HeatMapLayer(
"heatMap",
{
"radius":45,
"featureWeight":"value",
"featureRadius":"geoRadius"
}
);
layer.events.on({"layerInitialized": addLayer});
Step2 制作热力图
本例根据传入的热点半径heatradius和根据热点数量heatNums随机生成的热力点heatPoints制作热点图。
如果想要根据固定点制作热点图,则直接将点的坐标位置赋值给heatPoints数组即可。
//生成热力图上的热点
function createHeatPoints(){
clearHeatPoints();
var heatPoints = [];
var num = parseInt(document.getElementById('heatNums').value);
var radius = parseInt(document.getElementById('heatradius').value);
var unit = document.getElementById("radiusUnit").value,
useGeoRadius = false;
if("degree" == unit){
useGeoRadius = true;
}
heatMapLayer.radius = radius;
//根据设置的点的数量,随机生成热力点
for(var i=0; i < num; i++){
heatPoints[i] = new SuperMap.Feature.Vector(
new SuperMap.Geometry.Point(
Math.random()*360 - 180,
Math.random()*180 - 90
),
{
"value":Math.random()*9,
"geoRadius":useGeoRadius?radius:null
}
);
}
heatMapLayer.addFeatures(heatPoints);
}
Step3 把底图、热力图图层添加到地图上
//把底图、热力图图层添加到地图上,并设置地图默认的中心点坐标和比例尺级别
function addLayer() {
map.addLayers([layer,heatMapLayer]);
map.setCenter(new SuperMap.LonLat(0, 0), 0);
}
Step4 删除已有的热力图
function clearHeatPoints(){
heatMapLayer.removeAllFeatures();
}
在线演示与源码编辑
您可以在线访问完整代码、体验演示效果,也可以直接在线编辑源码并实时查看效果。