I'm using OpenLayers with JavaScript, and I'm calculating the rotation between two points (they represent arrows indicating the path taken by a vehicle). I have the following function:
function calculateAngleBetweenTwoPoints(point1, point2) { let lonLat1 = ol.proj.toLonLat(point1.getGeometry().getCoordinates()); let lonLat2 = ol.proj.toLonLat(point2.getGeometry().getCoordinates()); let angleRad = - Math.atan2(lonLat2[1] - lonLat1[1], lonLat2[0] - lonLat1[0]); let angleDeg = (angleRad * 180) / Math.PI; let vector_angle = Math.abs(angleDeg) % 360 ; vector_angle = (vector_angle * Math.PI) / 180; return vector_angle;}
Although the orientation is correct for some points, it fails with some points. All points are rendered, I call it here:
function createArrowVectorLayer(points, image) { const features = []; for (let i = 0; i < points.length; i++) { const point1 = points[i]; let point2 = ""; let rotation = 0; if (points[i + 1] === undefined) { rotation = 0; } else { point2 = points[i + 1]; rotation = calculateAngleBetweenTwoPoints(point1, point2); } const arrowStyle = new ol.style.Style({ image: new ol.style.Icon({ src: image, scale: 0.03, rotation: rotation, anchor: [0.5, 0.5], graphicXOffset: -18, graphicYOffset: -18, }), }); point1.setStyle(arrowStyle); features.push(point1);}
Does anyone know what is wrong?