71 lines
2.5 KiB
JavaScript
71 lines
2.5 KiB
JavaScript
class MarkerManager {
|
|
constructor(layer, styleFunction) {
|
|
this.layer = layer;
|
|
this.source = layer.getSource();
|
|
this.markers = {};
|
|
this.styleFunction = styleFunction;
|
|
}
|
|
|
|
addMarker(id, coordinates, properties = {}) {
|
|
const point = new ol.geom.Point(ol.proj.fromLonLat(coordinates));
|
|
const feature = new ol.Feature(point);
|
|
|
|
for (const prop in properties) {
|
|
feature.set(prop, properties[prop]);
|
|
}
|
|
|
|
if (this.styleFunction) {
|
|
feature.setStyle(this.styleFunction(feature));
|
|
}
|
|
|
|
this.source.addFeature(feature);
|
|
this.markers[id] = feature;
|
|
return feature;
|
|
}
|
|
|
|
updateMarker(id, coordinates, properties = {}) {
|
|
const marker = this.markers[id];
|
|
if (!marker) return this.addMarker(id, coordinates, properties);
|
|
|
|
const newCoords = ol.proj.fromLonLat(coordinates);
|
|
marker.getGeometry().setCoordinates(newCoords);
|
|
|
|
for (const prop in properties) {
|
|
marker.set(prop, properties[prop]);
|
|
}
|
|
|
|
return marker;
|
|
}
|
|
|
|
animateMarker(id, newCoordinates, duration = 2000) {
|
|
const marker = this.markers[id];
|
|
if (!marker) return;
|
|
|
|
const startCoordinates = marker.getGeometry().getCoordinates();
|
|
const endCoordinates = ol.proj.fromLonLat(newCoordinates);
|
|
const startTime = performance.now();
|
|
|
|
const animate = (currentTime) => {
|
|
const elapsed = currentTime - startTime;
|
|
const fraction = Math.min(elapsed / duration, 1);
|
|
|
|
const interpolated = [
|
|
startCoordinates[0] + fraction * (endCoordinates[0] - startCoordinates[0]),
|
|
startCoordinates[1] + fraction * (endCoordinates[1] - startCoordinates[1])
|
|
];
|
|
|
|
marker.getGeometry().setCoordinates(interpolated);
|
|
|
|
if (fraction < 1) {
|
|
requestAnimationFrame(animate);
|
|
}
|
|
};
|
|
|
|
requestAnimationFrame(animate);
|
|
}
|
|
|
|
clearMarkers() {
|
|
this.source.clear()
|
|
}
|
|
}
|