Openlayers3实现车辆轨迹回放功能

记录基于geoserver地图服务,Openlayers3在web前端实现车辆轨迹回放功能,并记录和解决过程中出现的linestring只描绘部分经纬度坐标问题。

参考Openlayers3 官网例子

html

<!DOCTYPE html>
<html lang="en">
<head>
 <title>车辆轨迹回放</title>
 <meta charset="UTF-8"/>
 <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
 <link rel="stylesheet" href="../css/bootstrap.min.css"/>
 <link rel="stylesheet" href="../ol/ol.css"/>
 <style>
 #map {
 position: relative;
 }
 .popover{
 min-width: 60px;
 }
 html{height:100%}
 body{height:100%;margin:0px;padding:0px}
 </style>
</head>
<body style="margin: 0px 0px 0px 0px;line-height:0px;">
<div id="content">
 <!--<div id="map" style="height: 100%;width:100%"></div>-->
 <div class="row-fluid">
 <div>
 <div id="map" class="map"></div>
 </div>
 </div>

 <div class="row-fluid">
 <div class="span3" style="position:absolute;top:0px;right:0px;">
 <div class="accordion-group widget-box">
 <div class="accordion-heading">
  <div class="widget-title"><a data-parent="#collapse-group" href="#collapseGOne"
    data-toggle="collapse"><span class="icon"><i
  class="icon-map-marker"></i></span>
  <h5>轨迹查询</h5>
  </a>
  </div>
 </div>
 <div class="accordion-body in collapse" id="collapseGOne">
  <div class="form-actions">
  <div class="control-group" style="margin-bottom: 0px">
  <label class="control-label"><i class="icon-truck"></i>设备</label>

  <div class="controls">
  <select id="busSelect" class="span10">
   <option value="*">请选择设备</option>
  </select>
  </div>
  </div>
  </div>

  <div class="form-actions">
  <div class="control-group" style="margin-bottom: 0px">
  <label class="control-label"><i class="icon-table"></i>日期</label>

  <div class="controls">
  <div data-date="" class="input-append date datepicker">
   <input id="traceday" type="text" data-date-format="yyyy-mm-dd" class="span10"
   disabled>
   <span class="add-on"><i class="icon-time"></i></span></div>
  </div>
  </div>
  </div>
  <div style="padding: 19px 20px 20px; margin-top: 20px; margin-bottom: 20px;">
  <div class="control-group" style="margin-bottom: 0px">
  <button id="queryBtn" class="btn btn-primary"><i class="icon-search"></i>&nbsp;轨迹查询</button>
  <span class="remind"></span>
 </div>
  <div class="control-group" style="margin-top: 10px">
  <button id="animateBtn" class="btn btn-info"><i class="icon-eye-open"></i>&nbsp;轨迹回放</button>
  <input id="speed" type="range" min="1" max="100" step="10" value="10">&nbsp;<span><i class="icon-cog">速度</i></span>
 </div>
 </div>
 </div>
 </div>
</div>
</div>
</div>
</div>
<script src="../js/lib/jquery.min.js"></script>
<script src="../js/lib/bootstrap.min.js"></script>
<script src="../ol/ol-debug.js"></script>
<script src="../ol/ol.js"></script>
<script src="../js/globalVariable.js"></script>
<script src="../js/gpsQueryAndroid.js"></script>
</body>
</html>

map初始化

$(document).ready(function () {
 map = new ol.Map({
 logo: false,
 target: document.getElementById('map'),
 layers: layers,
 view: view
 });
 initSelect();//设备下拉框列表初始化
 //时间控件初始化
 $('#s-traceday').val(transfromTime(new Date(),false)+" 00:00:00");
 $('#e-traceday').val(transfromTime(new Date(),true));
 $('.datepicker').datetimepicker({
 minView:0,
 format: 'yyyy-MM-dd hh:mm:ss',
 todayBtn : "linked",
 autoclose : true,
 todayHighlight : true,
 startDate: daylimit,
 endDate:'+1d'//结束时间,在这时间之后都不可选
 });
});

//轨迹line layer
var vsource = new ol.source.Vector({
 type: 'LineString',
 features: []
});
var linelayers = new ol.layer.Vector({
 source: vsource,
 style: new ol.style.Style({
 fill: new ol.style.Fill({
 color: '#0044CC'
 }),
 stroke: new ol.style.Stroke({
 color: '#0044CC',
 width: 4
 })
 })
});
//地图基础参数
var map;
var center = [121.6606763113213, 31.14611063632111];
var lng, lat;
var source = new ol.source.Vector({
 wrapX: false
});;
var projection = new ol.proj.Projection({
 code: 'EPSG:4326',
 units: 'degrees',
 axisOrientation: 'neu'
});
var view = new ol.View({
 projection: projection,
 center: center,
 zoom: 16
});

var layers = [new ol.layer.Tile({
 title: '、地图',
 visible: true,
 preload: Infinity,
 source: new ol.source.TileWMS({
 url: gisUrl,
 params: {
 'VERSION': '1.1.0',
 tiled: true,
 STYLES: '',
 LAYERS: 'shanghai:maptest',
 }
 })
 }),linelayers];

ajax获取坐标数据

//轨迹查询按钮点击
var positions=[];
$("#queryBtn").click(function(){
 //清除之前的图层
 if (centerSource.getFeatures != null) {
 centerSource.clear(); }
 linelayers.getSource().clear(true);
 positions=[];//清空
 //取值
 var busnum=$("#busSelect").val();
 var traceday=$("#traceday").val();
 if(busnum=="*"){
 $(".remind").html('<i class="icon-info-sign">请先选择车辆</i>');
 return;
 }else{
 $(".remind").html('');
 busnum=busnum.slice(2);
 }
 if(transfromTime(new Date(),false)==traceday){//当天
 traceday="*";
 }else{
 traceday=traceday.replace(/(-)/g,"");
 }
 $(".remind").html('<i class="icon-cogs"> 正在查询...</i>');

 //请求
 $.getJSON(baseUrl+"trace/query/"+busnum+"/"+traceday,"",function(data){
 if(data.length==0){
 $(".remind").html('<i class="icon-info-sign">未查到gps数据</i>');return;
 }
 var position = [];
 for(var i = 0;i<data.length;i++){
 if(i!=0&&data[i].lon==data[i-1].lon&&data[i].lon==data[i-1].lon){//去除重复数据
  continue;
 }
 position = [parseFloat(data[i].lon),parseFloat(data[i].lat)];
 positions.push(position);
 }
 console.log(positions);
 if(positions.length==1){
 $(".remind").html('<i class="icon-info-sign">该车辆当天停在该位置未启动</i>');
 centerAt(positions[0]);
 return;
 }
 AddLayer(positions);
 });
});

显示轨迹

//轨迹描绘
function AddLayer() {
 var lineFeature = new ol.Feature({//路线
 geometry: new ol.geom.LineString(positions,'XY'),
 });
 linelayers.getSource().addFeature(lineFeature);

 var startFeature = new ol.Feature({//起点
 geometry: new ol.geom.Point(positions[0]),
 population: 4000,
 rainfall: 500
 });
 startFeature.setStyle(startStyle);
 linelayers.getSource().addFeature(startFeature);
 var endFeature = new ol.Feature({//终点
 geometry: new ol.geom.Point(positions[positions.length-1]),
 population: 4000,
 rainfall: 500
 });
 endFeature.setStyle(endStyle);
 linelayers.getSource().addFeature(endFeature);

 carFeature = new ol.Feature({//车子
 geometry: new ol.geom.Point(positions[0]),
 population: 4000,
 rainfall: 500
 });
 carFeature.setStyle(carStyle);
 linelayers.getSource().addFeature(carFeature);
 var extent = linelayers.getSource().getExtent();//合适比例缩放居中
 view.fit(extent, map.getSize());
 }

显示单点

//居中 车辆不运动时居中显示图标处理
var centerLayer = null;
var centerSource = new ol.source.Vector({
 features: null
});
//居中在一个位置
function centerAt(position) {
 var pan = ol.animation.pan({
 duration: 2000,
 source: (view.getCenter())
 });
 view.setCenter(position);

 var iconFeature = new ol.Feature({
 geometry: new ol.geom.Point(position),
 name: 'Null Island',
 population: 4000,
 rainfall: 500
 });
 iconFeature.setStyle(iconStyle);
 centerSource.addFeature(iconFeature);
 centerLayer = new ol.layer.Vector({
 source: centerSource
 });
 map.addLayer(centerLayer);
 centerLayer.setVisible(true);
}

点在线上运动,轨迹回放

//轨迹回放start 参考官网
var carFeature = null;
var speed, now;
var animating = false;
$("#animateBtn").click(function(){
 if(positions.length==0){
 $(".remind").html('<i class="icon-info-sign">请先查询轨迹</i>');
 return;
 }
 if (animating) {
 stopAnimation(false);
 } else {
 animating = true;
 now = new Date().getTime();
 speed = $("#speed").val();//速度
 $("#animateBtn").html('<i class="icon-eye-close"></i>&nbsp;取消回放');
 carFeature.setStyle(null);
 // map.getView().setCenter(center);
 map.on('postcompose', moveFeature);
 map.render();
 }
});

var moveFeature = function(event) {
 var vectorContext = event.vectorContext;
 var frameState = event.frameState;

 if (animating) {
 var elapsedTime = frameState.time - now;
 // here the trick to increase speed is to jump some indexes
 // on lineString coordinates
 var index = Math.round(speed * elapsedTime / 1000);

 if (index >= positions.length) {
 stopAnimation(true);
 return;
 }

 var currentPoint = new ol.geom.Point(positions[index]);
 var feature = new ol.Feature(currentPoint);
 vectorContext.drawFeature(feature, carStyle);
 }
 // tell OL3 to continue the postcompose animation
 map.render();
 };

 function startAnimation() {
 if (animating) {
 stopAnimation(false);
 } else {
 animating = true;
 now = new Date().getTime();
 speed = speedInput.value;
 $("#animateBtn").html('<i class="icon-eye-close"></i>&nbsp;取消回放');
 // hide geoMarker
 geoMarker.setStyle(null);
 // just in case you pan somewhere else
 map.getView().setCenter(center);
 map.on('postcompose', moveFeature);
 map.render();
 }
 }

 function stopAnimation(ended) {
 animating = false;
 $("#animateBtn").html('<i class="icon-eye-open"></i>&nbsp;轨迹回放');

 // if animation cancelled set the marker at the beginning
 var coord = ended ? positions[positions.length - 1] : positions[0];
 /** @type {ol.geom.Point} */ (carFeature.getGeometry())
 .setCoordinates(coord);
 //remove listener
 map.un('postcompose', moveFeature);
 }
//轨迹回放end

解决linestring坐标显示不全

期间碰到一个问题

var lineFeature = new ol.Feature({//路线
 geometry: new ol.geom.LineString(positions,'XY'),
 });
 linelayers.getSource().addFeature(lineFeature);

调用这段代码显示轨迹时,从数据库取到20个坐标,就可能只显示4个坐标,本来是弯曲的轨迹,但是实际上就是折线,很尴尬。
误打误撞,和同学 交流过程中发现问题所在,特此感谢。
在ajax获取坐标数据中发现问题所在:
原先错误代码

position = [data[i].lon,data[i].lat];
 positions.push(position);

正确代码

position = [parseFloat(data[i].lon),parseFloat(data[i].lat)];
 positions.push(position);

原因就是没有把float类型的坐标利用parseFloat强转,导致默认的泛数据类型精确度不够,经纬度小数点后末尾几位就会被忽略,于是造成数据失效,描出的线就会有问题。

附上icon、起点、终点、车辆等地图样式

//样式,供上述代码调用
var iconStyle = new ol.style.Style({
 image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
 anchor: [0.5, 0.8],
 anchorXUnits: 'fraction',
 anchorYUnits: 'pixels',
 opacity: 0.75,
 src: 'img/iconfont-weizhi-red.png'
 }))
});
var startStyle = new ol.style.Style({
 image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
 anchor: [0.5, 0.8],
 opacity: 0.8,
 src: 'img/start.png'
 /*anchorXUnits: 'fraction',
 anchorYUnits: 'pixels',
 opacity: 0.75,*/

 }))
});
var endStyle = new ol.style.Style({
 image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
 src: 'img/end.png',
 anchor: [0.5, 0.8],
 }))
});
var carStyle = new ol.style.Style({
 image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
 src: 'img/car.png',
 anchor: [0.5, 0.8],
 }))
});

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • openlayers 3实现车辆轨迹回放

    本文实例为大家分享了openlayers 3实现车辆轨迹回放的具体代码,供大家参考,具体内容如下 先上效果: 利用 openlayers 3地图的 postcompose 事件监听地图的重绘 注意:此代码是我在Vue 的methods 里面写的测试方法,并不能直接运行,请在理解的基础上测试. vm 为vue的this对象 注释已经很丰富了,先做个备份,后期会编辑加入一点详解. 实现代码: html: <div id="menu"> <label for="s

  • Vue+Openlayers自定义轨迹动画

    本文实例为大家分享了Vue+Openlayers实现轨迹动画的具体代码,供大家参考,具体内容如下 <template> <div class="map-warp"> <h3> <a href="https://openlayers.org/en/latest/examples/feature-move-animation.html?q=polyline" target="_bank" >Openla

  • Openlayers3实现车辆轨迹回放功能

    记录基于geoserver地图服务,Openlayers3在web前端实现车辆轨迹回放功能,并记录和解决过程中出现的linestring只描绘部分经纬度坐标问题. 参考Openlayers3 官网例子 html <!DOCTYPE html> <html lang="en"> <head> <title>车辆轨迹回放</title> <meta charset="UTF-8"/> <met

  • canvas轨迹回放功能实现

    本文通过json机构,HTML代码以及JS代码详细给大家分析了canvas轨迹回放功能实现的过程,以下是全部内容. json结构 [ { "path": [ { "x": 82, "y": 43 }, { "x": 83, "y": 43 }, { "x": 84, "y": 45 }, { "x": 86, "y": 47 }

  • silverlight线程与基于事件驱动javascript引擎(实现轨迹回放功能)

    案例背景: 整个功能其实就是从数据库取出数据,然后在界面上播放,简单地说就是类似网上在线看视频,听音乐,只不过我取的是字符串数据,而他们取的是流文件数据.把整体数据分成十份,十个线程同时向数据库取数据(并发提高速度)放在十个队列中,另外一个线程从队列中取数据拿出来到界面上播放,可以拖动播放进度,停止,暂停,重新播放,控制播放速度.恩,功能听起来似乎很简单,做起来也不是很难.但是后面发现的一些问题,以及顺着这些问题往下挖掘,挖掘了一些我认为值得记住的东西. 关键东西: 1. siliverligh

  • 详解微信小程序轨迹回放实现及遇到的坑

    微信小程序轨迹回放主要使用到polyline进行划线操作,以及使用marker去进行小车移动操作.效果图如下: 具体实现代码: trackplay.wxml文件 <!--pages/tracker/tracker.wxml--> <map id="mymap" longitude="{{mapCenter.longitude}}" latitude="{{mapCenter.latitude}}" scale="{{s

  • c# wpf使用GMap.NET类库,实现地图轨迹回放

    前言 实现轨迹回放,GMap.NET有对应的类GMapRoute.这个类函数很少,功能有限,只能实现简单的轨迹回放.要实现更复杂的轨迹回放,就需要自己动手了. 本文介绍一种方法,可以实现复杂的轨迹回放.有句话"功夫在诗外",GMap.NET给你提供了基本地图处理功能:但是不要让CMap.NET束缚了手脚.你需要有深刻理解地图实现原理,深入理解WPF动画的原理,才能到达随心所欲.最终的效果如下: GMap.NET 显示原理 地图就是由许多方格"瓦片"组合而来.当你移动

  • 微信小程序实现轨迹回放的示例代码

    在微信小程序实现轨迹回放的效果 1.wxml <map id="map" longitude="{{longitude}}" latitude="{{latitude}}" scale="16" bindcontroltap="controltap" bindmarkertap="markertap" markers="{{markers}}" polyline

  • vue+flv.js+SpringBoot+websocket实现视频监控与回放功能

    目录 需求: 思路: 准备工作: 实现: 最后: 需求: vue+springboot的项目,需要在页面展示出海康的硬盘录像机连接的摄像头的实时监控画面以及回放功能. 之前项目里是纯前端实现视频监控和回放功能.但是有局限性.就是ip地址必须固定.新的需求里设备ip不固定.所以必须换一种思路. 通过设备的主动注册,让设备去主动连接服务器后端通过socket推流给前端实现实时监控和回放功能: 思路: 1:初始化设备.后端项目启动时就调用初始化方法.2:开启socket连接.前端页面加载时尝试连接so

  • OpenLayers3实现图层控件功能

    本文实例为大家分享了OpenLayers3实现图层控件的具体代码,供大家参考,具体内容如下 1. 前言 在实际应用中,我们将加载到地图容器中的图层通过图层显示的控件功能,来显示加载的图层,便于用户查看与操作,OpenLayers 3 中并没有提供类似的图层控件,但是他的 API 却提供了该功能的相关接口,我们可以通过调用相关的接口,实现该功能. 2. 实现思路 (1)新建一个网页,参考前面的文章加载OSM瓦片图层的方法,加载OSM瓦片.MapQuest 影像.JSON 与KML 格式的矢量图.

  • Shell脚本制作的终端会话回放功能脚本分享

    不久前在书上看到两个很有趣的命令--script和srciptreplay,它可以把终端会话记录到一个文件中,即是说我们可以通过终端会话来来制作命令行技巧视频教程,也可以与他人分享会话文件,而且生成的文件还只是一般的文本文件,文件的大小非常小,真是非常有意思.下面是本人写的两个shell程序,来方便进行这个有趣并有意义的操作. 一.实现代码 文件:Record.sh 复制代码 代码如下: #! /bin/bash  # Filename:Record.sh    read -p "Please

随机推荐