OpenLayers 6 实现仿Echarts风格的动态迁徙图/航班图

这是一个做完很久的demo,主要还是为了摆脱echarts那种“图层脱线”的问题,提升可视化渲染性能。

使用的数据还是来自echarts,模拟了全国各地到湖南重点景区的客流情况。
在这里插入图片描述

分析

要实现动态迁徙图的效果,主要需解决两个问题

曲线的绘制。因为给出的数据只有起点和终点两个点位,所以想要绘制曲线可以参考turf中的bezier曲线生成API。
点迹的动画播放。仍然要依靠render机制,这里我还是使用比较熟悉的postrender事件回调函数。

实现

首先利用turf做一个利用两个点就可以生成弧线要素的函数,其实这里面调用的是turf的bezierSpline,写死了一个定比例取到的点位,参数列表为要素的自定义属性留了位置。同时在函数里计算出曲线的长度待用。

function getTurfArcFeature(start, end, opt) {
  var line = turf.lineString([
    start,
    [start[0] + (end[0] - start[0]) * 0.5,
    start[1] + (end[1] - start[1]) * 0.65],
    end
  ]);
  var curved = turf.bezierSpline(line);
  let length = turf.length(curved, { units: 'meters' });
  var bF = turfFormat.readFeature(curved);
  bF.getGeometry().transform('EPSG:4326', 'EPSG:3857');
  bF.setProperties(opt);
  bF.set("length", length);
  return bF;
}

然后重点分析一下点位动画的实现:

先写出监听postrender事件回调函数的基本框架,并取得VectorContex对象的句柄:

tileLayer.on('postrender', (evt) => {
  let veContext = getVectorContext(evt);
 
 
})

再写出遍历所有曲线的forEach结构及回调函数,回调函数内先将本次迭代的曲线绘制到地图上:

tileLayer.on('postrender', (evt) => {
  let veContext = getVectorContext(evt);
 
  arcLinesFeature.forEach((item,index) => {
    veContext.drawFeature(item, arcStyle);
    
  })
 
 
})

然后通过frameState获取当前帧的时间戳,计算得到当前帧运动点位的位置百分比,如果百分比超过100%还要进行归零处理

tileLayer.on('postrender', (evt) => {
  let veContext = getVectorContext(evt);
  arcLinesFeature.forEach((item,index) => {
    veContext.drawFeature(item, arcStyle);
    
    let time = (evt.frameState.time - item.get('start')) / 1000;
    let frac = time / 5-index/arcLinesFeature.length;
    if (!item.get('start')) item.set('start', new Date().getTime());
    if (frac>=1) {
      item.set('start', new Date().getTime());
      frac=0;
    }
    
  })
 
})

最后根据位置百分比,使用getCoordinateAt求得点位的坐标,并且使用VectorContex对象绘制到canvas上,然后显示调用render()函数,请求渲染下一帧。

tileLayer.on('postrender', (evt) => {
  let veContext = getVectorContext(evt);
  arcLinesFeature.forEach((item,index) => {
    veContext.drawFeature(item, arcStyle);
    let time = (evt.frameState.time - item.get('start')) / 1000;
    let frac = time / 5-index/arcLinesFeature.length;
    if (!item.get('start')) item.set('start', new Date().getTime());
    if (frac>=1) {
      item.set('start', new Date().getTime());
      frac=0;
    }
    let along = item.getGeometry().getCoordinateAt(frac);
    let pF=new Feature(new Point(along));
    veContext.drawFeature(pF, dotStyle);
  })
  map.render()
})

完整代码

(删掉了我自己的Google开发者Key,黑色主题地图还请自己动手做一个)

import { Map, View } from 'ol';
import TileLayer from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ';
import Point from 'ol/geom/Point';
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import Feature from 'ol/Feature';
import * as turf from '@turf/turf'
import GeoJSON from 'ol/format/GeoJSON'
import { getVectorContext } from 'ol/render';
import Style from 'ol/style/Style';
import Stroke from 'ol/style/Stroke';
import Fill from 'ol/style/Fill';
import CircleStyle from 'ol/style/Circle';
import data from './data/t.json'
 
let tileLayer = new TileLayer({
  source: new XYZ({
    url: 'http://www.google.cn/maps/vt?pb=!1m5!1m4!1i{z}!2i{x}!3i{y}!4i256!2m3!1e0!2sm!3i451159038!3m14!2szh-CN!3sUS!5e18!12m1!1e68!12m3!1e37!2m1!1ssmartmaps!12m4!1e26!2m2!1sstyles!2zcC5oOiNmZjFhMDB8cC5pbDp0cnVlfHAuczotMTAwfHAubDozM3xwLmc6MC41LHMudDo2fHMuZTpnfHAuYzojZmYyRDMzM0M!4e0&key=<这里是我自己的google开发者key>&token=126219'
  })
})
let map = new Map({
  target: 'map',
  layers: [
    tileLayer
  ],
  view: new View({
    center: [11936406.337013, 3786384.633134],
    zoom: 5
  })
});
 
var flightSource = new VectorSource()
var flightLayer = new VectorLayer(
  {
    source: flightSource
  }
)
var turfFormat = new GeoJSON();
 
function getTurfArcFeature(start, end, opt) {
  var line = turf.lineString([
    start,
    [start[0] + (end[0] - start[0]) * 0.5,
    start[1] + (end[1] - start[1]) * 0.65],
    end
  ]);
  var curved = turf.bezierSpline(line);
  let length = turf.length(curved, { units: 'meters' });
  var bF = turfFormat.readFeature(curved);
  bF.getGeometry().transform('EPSG:4326', 'EPSG:3857');
  bF.setProperties(opt);
  bF.set("length", length);
  return bF;
}
 
map.addLayer(flightLayer)
 
var arcStyle = new Style({
  stroke: new Stroke({
    color: [0, 122, 122, 0.7],
    width: 1
  })
})
 
var dotStyle = new Style({
  image: new CircleStyle({
    fill: new Fill({
      color: [255, 255, 255,0.7]
    }),
    radius: 1
 
  })
})
 
var arcLinesFeature = [];
data.moveLines.forEach((item, index) => {
  let tempF = getTurfArcFeature(item.coords[0], item.coords[1], { 'from': item.fromName, 'to': item.toName });
  arcLinesFeature.push(tempF);
})
 
tileLayer.on('postrender', (evt) => {
  let veContext = getVectorContext(evt);
  arcLinesFeature.forEach((item,index) => {
    veContext.drawFeature(item, arcStyle);
    let time = (evt.frameState.time - item.get('start')) / 1000;
    let frac = time / 5-index/arcLinesFeature.length;
    if (!item.get('start')) item.set('start', new Date().getTime());
    if (frac>=1) {
      item.set('start', new Date().getTime());
      frac=0;
    }
    let along = item.getGeometry().getCoordinateAt(frac);
    let pF=new Feature(new Point(along));
    veContext.drawFeature(pF, dotStyle);
  })
  map.render()
})

我在企鹅家的课堂和CSDN学院都开通了《OpenLayers实例详解》课程,欢迎报名学习。搜索关键字OpenLayers就能看到。