GPX数据在mapboxGL中轨迹动画

概述

喜欢跑步的人都会选择一款APP来自己跑步的,常用的有keep、悦跑圈、华为健康等等,每次跑完步,会根据跑步的轨迹绘制轨迹动画。今天咱们讲讲技术,不扯淡,讲一下在mapboxGL中如何实现类似的效果。

效果

GPX数据在mapboxGL中轨迹动画_第1张图片

数据

本文中的数据是我跑步的实测数据,数据导出于Garmin运动手表,格式为GPX。

实现

1.解析处理数据

gpx数据解析用到了gpxparse.js,具体请移步GPXParser.js。

loadPgxData() {
  $.get('../data/route.gpx', function (res) {
    res = res.firstChild;
    var dom = $('
'); dom.html(res); var gpx = new gpxParser(); gpx.parse(dom.html()); that.points = gpx.tracks[0].points; var geojson = { 'type': 'FeatureCollection', 'features': [] }; var points = [[that.points[0].lon, that.points[0].lat]]; for(var i = 1;i<that.points.length;i++) { var p = [that.points[i].lon, that.points[i].lat]; var _points = points.concat([p]); geojson.features.push({ type: 'Feature', geometry: { type: 'LineString', coordinates: _points }, properties: { index: i } }); points.push(p); } // var geojson = gpx.toGeoJSON(); map.addSource('track-line', { type: 'geojson', data: geojson }); map.addLayer({ id: 'track-line', type: 'line', source: 'track-line', paint: { 'line-color': '#ff0000', 'line-width': 6 } }); that.play(); that.playFlag = setInterval(function () { that.index++; if(that.index === that.points.length) { window.clearInterval(that.playFlag); } else { that.play(); } }, 30); }) }

2.轨迹动画

play() {
  if(that.marker) that.marker.remove();
  switch (that.index) {
    case 0: {
      var img = $('').attr('src', '../css/start.png');
      var dom = $('
').append(img); const option = { element: dom[0], anchor: 'bottom', offset: [0, 10] }; new mapboxgl.Marker(option) .setLngLat([that.points[0].lon, that.points[0].lat]) .addTo(map); break; } case that.points.length -1: { var img = $('').attr('src', '../css/end.png'); var dom = $('
').append(img); const option = { element: dom[0], anchor: 'bottom', offset: [0, 10] }; new mapboxgl.Marker(option) .setLngLat([that.points[that.points.length - 1].lon, that.points[that.points.length - 1].lat]) .addTo(map); break; } default: { var img = $('').attr('src', '../css/loc.png'); var dom = $('
').append(img); const option = { element: dom[0], anchor: 'bottom', offset: [0, 10] }; that.marker = new mapboxgl.Marker(option) .setLngLat([that.points[that.index].lon, that.points[that.index].lat]) .addTo(map); break; } } map.setFilter('track-line', ['==', 'index', that.index]); if(that.index === that.points.length - 2) { var pt0 = [that.points[that.index].lon, that.points[that.index].lat]; var pt1 = [that.points[that.index + 1].lon, that.points[that.index + 1].lat]; map.flyTo({ center: pt0, zoom: 17.7 }); map.setPitch(60); var angle = that.getAngle(pt0, pt1); map.setBearing(angle); } }

你可能感兴趣的:(mapboxGL,GIS加油站)