JSFiddle - React, Tailwind, and code Playground
by ahocevar
HTML
<script src="https://openlayers.org/en/v3.19.1/build/ol.js"></script>
<link rel="stylesheet" href="https://openlayers.org/en/v3.19.1/css/ol.css">
<div id="map" class="map"></div>
<button id="start-animation">Start Animation</button>
JavaScript
var routeSource = new ol.source.Vector({
format: new ol.format.GPX(),
url: 'https://gist.githubusercontent.com/ahocevar/00f495c1d66149c27d1b1e5edbe1e597/raw/ba02324e022f1f1ac353c9db01219c5159792390/tet.gpx'
});
var routeLayer = new ol.layer.Vector({
source: routeSource
});
var dynamicSource = new ol.source.Vector({
spatialIndex: false
});
var dynamicLayer = new ol.layer.Vector({
updateWhileAnimating: true,
updateWhileInteracting: true,
source: dynamicSource
});
var geoMarker, startMarker, endMarker, routeCoords, routeLength;
var handle = routeSource.on('change', function() {
if (routeSource.getState() == 'ready') {
routeSource.unByKey(handle);
var route = routeSource.getFeatures()[0].getGeometry();
map.getView().fit(route, map.getSize());
routeCoords = route.getCoordinates()[0];
routeLength = routeCoords.length;
geoMarker = new ol.Feature({
geometry: new ol.geom.Point(routeCoords[0])
});
dynamicSource.addFeature(geoMarker);
startMarker = new ol.Feature({
type: 'icon',
geometry: new ol.geom.Point(routeCoords[0])
});
endMarker = new ol.Feature({
type: 'icon',
geometry: new ol.geom.Point(routeCoords[routeLength - 1])
});
routeSource.addFeatures([startMarker, endMarker]);
}
});
var styles = {
'Ride': new ol.style.Style({
stroke: new ol.style.Stroke({
width: 6,
color: [237, 212, 0, 0.8]
})
}),
'icon': new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 1],
src: 'https://openlayers.org/en/v3.19.1/examples/data/icon.png'
})
}),
'geoMarker': new ol.style.Style({
image: new ol.style.Circle({
radius: 7,
snapToPixel: false,
fill: new ol.style.Fill({
color: 'black'
}),
stroke: new ol.style.Stroke({
color: 'white',
width: 2
})
})
})
};
routeLayer.setStyle(function(feature) {
return...