reactjs - 如何通过几何图形更新标记位置并平滑过渡?
问题描述
我目前正在使用 ReactJS+Nodejs 应用程序,尝试集成 OpenLayers。我需要的是实时更改标记的 GPS 位置(通过 socket.io)。
到目前为止,我已经想出了这个代码:
this.map = new Map({
target: "map",
layers: [
new TileLayer({
source: new XYZ({
attributions: 'Tiles © <a href="https://services.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer">ArcGIS</a>',
url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}'
})
}),
],
view: new View({
center: fromLonLat([-8.455826, 40.168307]),
rotation: 1.1344640138,
easing: 0.5
})
});
var vectorSource = new VectorSource({});
var markersLayer = new VectorLayer({
source: vectorSource,
});
this.map.addLayer(markersLayer);
var point1 = new Point(
fromLonLat([-8.455826, 40.168307])
);
var point2 = new Point(
fromLonLat([-8.456819, 40.166388])
);
var marker = new Feature({
geometry: point1,
name: "My point",
});
vectorSource.addFeature(marker);
var style = new Style({
image: new CircleStyle({
radius: 7,
fill: new Fill({color: 'black'}),
stroke: new Stroke({
color: 'white', width: 2
})
})
});
marker.setStyle(style);
setTimeout(function () {
marker.setGeometry(point2);
marker.getGeometry().translate(40, -40);
}, 3500);
标记移动,但转换发生在瞬间。有没有办法让它像“CSS 线性过渡”一样移动,让它看起来更逼真?
解决方案
使用计时器,您可以沿着新旧位置之间的线将移动分成多个步骤,例如 100 个 10ms 步骤
var line = new LineString([oldCoordinates, newCoordinates])];
var step = 0;
var key = setInterval( function() {
if (step < 100) {
step++;
marker.setGeometry(new Point(line.getCoordinateAt(step/100)));
} else {
clearInterval(key);
}
}, 10);
您可能还可以基于飞行动画示例https://openlayers.org/en/latest/examples/flight-animation.html
推荐阅读
- javascript - Onclick 使用 jQuery 从 textarea 添加/删除特定字符串
- visual-studio - 当我在代码中时,是否有任何 vs 代码快捷方式可以按 Enter 并转到下一行?
- javascript - Github Actions 上的 Mocha 并行作业
- c# - 如何为 MemoryStream 中编写的内容提供 *.csv 扩展名?
- json - 如何在本机反应中以json格式获取excel文件数据
- javascript - 反应平滑滚动但不在初始化时
- c# - 将连接的套接字保存在字典中
- python - 根据条件将行更改为0
- java - 如何使用 RCaller 将预测数据从 R 返回到 Java?
- laravel - 通过 axios 更新时出现网络错误