有一阵子没动笔了,时间过得好快。这阵子因为工作的原因,间隔了很久跟大家分享,希望后面稳定下来会有更多的时间来做一些记录。这次分享一个比较有意思的leaflet插件,可以在二维场景下用来对风场、洋流等信息进行动态展示,同时可以展示实时风速和流速。
本次内容用到的例子以及数据可以在以下开源地址找到:
https://github.com/onaci/leaflet-velocity,包含演示的数据。
打开clone下来的代码,可以看到:
实例文件在demo文件夹中。
第一步、打开demo.html
<!doctype html>
<html>
<head>
<title>LeafletVelocity Demo</title>
<meta charset="utf-8">
</head>
<body>
<div id="map"></div>
<!--vendor-->
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<link rel="stylesheet" href="https://npmcdn.com/leaflet@1.1.0/dist/leaflet.css" />
<script src="https://npmcdn.com/leaflet@1.1.0/dist/leaflet.js"></script>
<!--leaflet-velocity-->
<link rel="stylesheet" href="../dist/leaflet-velocity.css" />
<script src="../dist/leaflet-velocity.js"></script>
<!--demo-->
<link rel="stylesheet" href="demo.css" />
<script src="demo.js"></script>
</body>
</html>
上面的关键代码主要引入了leaflet、jquery和leaflet-velocity插件,以及用来控制核心逻辑的demo.js
第二步、编辑demo.js
function initDemoMap(){
var Esri_WorldImagery = L.tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}', {
attribution: 'Tiles © Esri — Source: Esri, i-cubed, USDA, USGS, ' +
'AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
});
var Esri_DarkGreyCanvas = L.tileLayer(
"http://{s}.sm.mapstack.stamen.com/" +
"(toner-lite,$fff[difference],$fff[@23],$fff[hsl-saturation@20])/" +
"{z}/{x}/{y}.png",
{
attribution: 'Tiles © Esri — Esri, DeLorme, NAVTEQ, TomTom, Intermap, iPC, USGS, FAO, ' +
'NPS, NRCAN, GeoBase, Kadaster NL, Ordnance Survey, Esri Japan, METI, Esri China (Hong Kong), and the GIS User Community'
}
);
var baseLayers = {
"Satellite": Esri_WorldImagery,
"Grey Canvas": Esri_DarkGreyCanvas
};
var map = L.map('map', {
layers: [ Esri_WorldImagery ]
});
var layerControl = L.control.layers(baseLayers);
layerControl.addTo(map);
map.setView([-22, 150], 5);
return {
map: map,
layerControl: layerControl
};
}
照例是做底图的初始化配置和引用资源的定义等等初始化工作。
第三步、引入动态数据
$.getJSON('http://localhost:8086/2d/leaflet-velocity-master/demo/wind-gbr.json', function (data) {
var velocityLayer = L.velocityLayer({
displayValues: true,
displayOptions: {
velocityType: 'GBR Wind',
displayPosition: 'bottomleft',
displayEmptyString: 'No wind data'
},
data: data,
maxVelocity: 10
});
layerControl.addOverlay(velocityLayer, 'Wind - Great Barrier Reef');
});
如果只是对接数据进行数据可视化的话,到这一步基本已经达到预期。我们来看下实现的效果:
静态展示图
动态展示图
这里,使用的底图是墨卡托的,如果要换成经纬度或者其他投影方式的话,兼容性不太好,需要调整源码。调整leaflet-velocity.js中的矢量元素变化的动态计算算法。如果有已经调整好的小伙伴,可以分享一下github链接。