OpenLayers 导航之运动轨迹
注:当前使用的是 ol 5.3.0 版本,天地图使用的
key
请到天地图官网申请,并替换为自己的key
地图导航除了单点定位导航,还可以根据动态模拟运动轨迹,并标绘导航路线。本文基于JSON格式模拟运动轨迹数据,实现动态定位导航功能。本节主要介绍加载地图运动轨迹。
1. 创建轨迹
通过ol.geom.LineString
创建线几何对象,然后创建线图层并添加到地图中。
// 用LineString存储轨迹点的地理信息(XYZM,Z维度用来存储角度/M则为时间维度)
const lineGeometry = new ol.geom.LineString([], ('XYZM'));
const lineLayer = new ol.layer.Vector({source: new ol.source.Vector({features: [new ol.Feature({geometry: lineGeometry})]}),style: new ol.style.Style({fill: new ol.style.Fill({color: 'red'}),stroke: new ol.style.Stroke({color: 'blue',width: 2.5})})
})
map.addLayer(lineLayer)
lineLayer.setProperties({ layerName: 'lineLayer' })
2. 创建导航定位标注
通过Overlay
创建标注图层。
// 创建导航定位标注
const markerImage = document.getElementById("geolocation_marker")
const markerOverlay = new ol.Overlay({positioning: 'center-center',element: markerImage,stopEvent: false
})
map.addOverlay(markerOverlay)
3. 生成轨迹
设置一个定时器,每隔2s
钟改变一个标注点,并更新线几何对象坐标,然后将标注点移至地图中心点,调用render
函数重新渲染地图。
function startFoot() {if (!footData.length) {console.warn("轨迹数据未加载!")return}const coordinates = footData // 运动轨迹数组const firstFoot = coordinates.shift()// 生成运动轨迹线,添加下一个点,在定时器中const lineCoords = []let timeInterval = setInterval(() => {if (!coordinates.length) {clearInterval(timeInterval)timeInterval = nullreturn}const firstFoot = coordinates.shift()firstCoords = [firstFoot.coords.longitude, firstFoot.coords.latitude]lineCoords.push(firstCoords)lineGeometry.setCoordinates(lineCoords)map.getView().animate({ center: firstCoords, zoom: 20 })markerOverlay.setPosition(firstCoords)map.render()}, 2000)
}
4. 完整代码
其中libs
文件夹下的包需要更换为自己下载的本地包或者引用在线资源。
<!DOCTYPE html>
<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>运动轨迹</title><meta charset="utf-8" /><script src="../libs/js/ol-5.3.3.js"></script><script src="../libs/js/jquery-2.1.1.min.js"></script><link rel="stylesheet" href="../libs/css//ol.css"><style>* {padding: 0;margin: 0;font-size: 14px;font-family: '微软雅黑';}html,body {width: 100%;height: 100%;}#map {position: absolute;top: 50px;bottom: 0;width: 100%;}#foot-location {position: absolute;width: 100%;height: 50px;background: linear-gradient(135deg, #ff00cc, #ffcc00, #00ffcc, #ff0066);color: #fff;}.view-center {position: absolute;line-height: 50px;width: 100%;text-align: center;}.view-center span {border-radius: 5px;border: 1px solid #50505040;padding: 5px 20px;color: #fff;margin: 0 10px;background: #377d466e;}.view-center span:hover {cursor: pointer;filter: brightness(120%);background: linear-gradient(135deg, #c850c0, #4158d0);transition-delay: .25s;}</style>
</head><body><div id="map" title="地图显示"></div><div id="foot-location"><div class="view-center"><span class="start-foot">开启运动轨迹</span></div></div><img id="geolocation_marker" src="./geolocation_marker_heading.png" />
</body></html><script>//地图投影坐标系const projection = ol.proj.get('EPSG:3857');//==============================================================================////============================天地图服务参数简单介绍==============================////================================vec:矢量图层==================================////================================img:影像图层==================================////================================cva:注记图层==================================////======================其中:_c表示经纬度投影,_w表示球面墨卡托投影================////==============================================================================//const TDTImgLayer = new ol.layer.Tile({title: "天地图影像图层",source: new ol.source.XYZ({url: "http://t0.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=2a890fe711a79cafebca446a5447cfb2",attibutions: "天地图注记描述",crossOrigin: "anoymous",wrapX: false})})const TDTImgCvaLayer = new ol.layer.Tile({title: "天地图影像注记图层",source: new ol.source.XYZ({url: "http://t0.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=2a890fe711a79cafebca446a5447cfb2",attibutions: "天地图注记描述",crossOrigin: "anoymous",wrapX: false})})const map = new ol.Map({target: "map",loadTilesWhileInteracting: true,view: new ol.View({// center: [11421771, 4288300],// center: [102.6914059817791, 25.10595662891865],center: [104.0635986160487, 30.660919181071225],zoom: 10,worldsWrap: true,minZoom: 1,maxZoom: 20,projection: "EPSG:4326"}),layers: [TDTImgLayer, TDTImgCvaLayer],// 鼠标控件:鼠标在地图上移动时显示坐标信息。controls: ol.control.defaults().extend([// 加载鼠标控件// new ol.control.MousePosition()])})map.on('click', evt => {console.log(evt.coordinate)})// 用LineString存储轨迹点的地理信息(XYZM,Z维度用来存储角度/M则为时间维度)const lineGeometry = new ol.geom.LineString([], ('XYZM'));const lineLayer = new ol.layer.Vector({source: new ol.source.Vector({features: [new ol.Feature({geometry: lineGeometry})]}),style: new ol.style.Style({fill: new ol.style.Fill({color: 'red'}),stroke: new ol.style.Stroke({color: 'blue',width: 2.5})})})map.addLayer(lineLayer)lineLayer.setProperties({ layerName: 'lineLayer' })// 创建定位导航对象const geolocation = new ol.Geolocation({projection: map.getView().getProjection(),tracking: true, // 开启定位追踪trackingOptions: {maximumAge: 10000,enableHighAccuracy: true, // 是否开启高精度timeout: 60000 // 最大等待时间,毫秒}})// 创建导航定位标注const markerImage = document.getElementById("geolocation_marker")const markerOverlay = new ol.Overlay({positioning: 'center-center',element: markerImage,stopEvent: false})map.addOverlay(markerOverlay)// 请求模拟运动的轨迹数据let footData = []fetch("./foot-location.json").then(response => {console.log(response)if (response.status == 200) {response.json().then(res => {footData = res.datadocument.querySelector(".start-foot").addEventListener('click', startFoot())})}})function startFoot() {if (!footData.length) {console.warn("轨迹数据未加载!")return}const coordinates = footData // 运动轨迹数组const firstFoot = coordinates.shift()// 生成运动轨迹线,添加下一个点,在定时器中const lineCoords = []let timeInterval = setInterval(() => {if (!coordinates.length) {clearInterval(timeInterval)timeInterval = nullreturn}const firstFoot = coordinates.shift()firstCoords = [firstFoot.coords.longitude, firstFoot.coords.latitude]lineCoords.push(firstCoords)lineGeometry.setCoordinates(lineCoords)map.getView().animate({ center: firstCoords, zoom: 20 })markerOverlay.setPosition(firstCoords)map.render()}, 2000)}
</script>
OpenLayers示例数据下载,请回复关键字:ol数据
全国信息化工程师-GIS 应用水平考试资料,请回复关键字:GIS考试
【GIS之路】 已经接入了智能助手,欢迎关注,欢迎提问。
欢迎访问我的博客网站-长谈GIS:
http://shanhaitalk.com
都看到这了,不要忘记点赞、收藏 + 关注 哦 !
本号不定时更新有关 GIS开发 相关内容,欢迎关注 !