官网demo地址:
这篇绘制了一个运动轨迹动画。
先请求了一个json文件。
fetch(
"https://openlayers.org/en/latest/examples/data/polyline/route.json"
).then(function (response) {
response.json().then(function (result) {
const polyline = result.routes[0].geometry;
const route = new Polyline({
factor: 1e6,
}).readGeometry(polyline, {
dataProjection: "EPSG:4326",
featureProjection: "EPSG:3857",
});
})
文件中的数据格式跟我们常见的不太一样,
这些字符串是一种被称为 Polyline 编码的格式。是一种用于在地图上高效存储和传输折线(路径)的坐标数据的编码方法。用于将一系列纬度和经度坐标压缩成一个字符串。它使用增量编码和 可变长度编码 技术,使得路径数据在传输时占用更少的空间。 所以需要使用Polyline先进行解析。
解析完之后,可以直接创建为feature,同时,创建起点和终点以及运动中的图标feature。
const routeFeature = new Feature({
type: "route",
geometry: route,
});
const startMarker = new Feature({
type: "icon",
geometry: new Point(route.getFirstCoordinate()),
});
const endMarker = new Feature({
type: "icon",
geometry: new Point(route.getLastCoordinate()),
});
const position = startMarker.getGeometry().clone();
const geoMarker = new Feature({
type: "geoMarker",
geometry: position,
});
给每个feature绑定相应的样式。
const styles = {
route: new Style({
stroke: new Stroke({
width: 6,
color: [237, 212, 0, 0.8],
}),
}),
icon: new Style({
image: new