maps.chandlerswift.com/layers/amtrak-live/layer.js

55 lines
1.7 KiB
JavaScript
Raw Permalink Normal View History

2024-02-03 00:28:31 -06:00
import VectorLayer from 'ol/layer/Vector';
import {Vector as VectorSource} from 'ol/source.js';
import {Style} from 'ol/style.js';
import Icon from 'ol/style/Icon.js';
import pinURL from './pin.svg?url';
import { Feature } from 'ol';
import { Point } from 'ol/geom';
import { fromLonLat } from 'ol/proj';
const vectorLayer = new VectorLayer({
source: new VectorSource({
loader: async function() {
const res = await fetch("https://api-v3.amtraker.com/v3/trains");
const trainsByRoute = await res.json();
for (let [_route, trains] of Object.entries(trainsByRoute)) {
for (let train of trains) {
const {stations: _, ...trainWithoutStations} = train;
this.addFeature(new Feature({
geometry: new Point(fromLonLat([train.lon, train.lat])),
...trainWithoutStations,
}))
}
}
},
}),
2024-09-02 14:42:51 -05:00
style: function(feature){
let scale = [1, 1];
let rotation = ['E', 'SE', 'S', 'SW', 'W', 'NW', 'N', 'NE'].indexOf(feature.get('heading'));
if (rotation < 0) { // heading not found in array
console.warn(`Could not find ${feature.get('heading')} in rotation array`);
}
if (2 < rotation && rotation <= 6 ) {
rotation -= 4; // half turn
scale = [-1, 1];
}
rotation = Math.PI / 4 * rotation;
return new Style({
2024-02-03 00:28:31 -06:00
image: new Icon({
anchor: [0.5, .9],
src: pinURL,
2024-09-02 14:42:51 -05:00
rotateWithView: true,
rotation: rotation,
scale: scale,
2024-02-03 00:28:31 -06:00
}),
2024-09-02 14:42:51 -05:00
});
}
2024-02-03 00:28:31 -06:00
});
setInterval(() => vectorLayer.getSource().refresh(), 30000);
export default vectorLayer;