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 '/layers/chandler/pin.svg?url'; // TODO: remove `?url`? import { Collection, Feature } from 'ol'; import { Point } from 'ol/geom'; import { fromLonLat } from 'ol/proj'; let features = new Collection(); const vectorLayer = new VectorLayer({ source: new VectorSource({ features, }), style: new Style({ image: new Icon({ anchor: [0.5, 1], src: pinURL, }), }), }); async function refresh(){ const res = await fetch("https://whereis.chandlerswift.com/api/0/last"); const locs = await res.json(); const loc = locs[0]; // TODO: I could probably just `features[0] = …` but I'm not sure if that causes problems with re-rendering features if (features.getLength() == 0) { features.push(new Feature({ geometry: new Point(fromLonLat([loc.lon, loc.lat])), ...loc })); } else { features.item(0).setProperties(loc); // TODO: this won't remove a property if it was in a previous response but not this one features.item(0).getGeometry().setCoordinates(fromLonLat([loc.lon, loc.lat])); } } refresh(); setInterval(refresh, 10 * 1000); export default vectorLayer;