transport-accessibility/transport_accessibility/pt_map/templates/osrm_drawing.js

110 lines
3.1 KiB
JavaScript

// This script is not imported in the main script at all
// Function that takes a shape of a route and draws an OSRM path along it
function shapeToOSRM (polyline) {
if (!polyline) {
console.error('Invalid polyline');
return;
}
// Get the latlngs array from the polyline
const latlngs = polyline.getLatLngs();
if (latlngs.length < 2) {
console.error('Polyline should have at least two points');
return;
}
// Define start and end points
const startPoint = latlngs[0];
const endPoint = latlngs[latlngs.length - 1];
const initialWaypoints = [
L.latLng(startPoint.lat, startPoint.lng),
L.latLng(endPoint.lat, endPoint.lng)
];
console.log('initialWaypoints', initialWaypoints[0]);
const routingControl = L.Routing.control({
waypoints: initialWaypoints,
routeWhileDragging: false,
createMarker: () => null // Don't create markers for initial route
}).addTo(map);
console.log('Added routingControl.');
routingControl.on('routesfound', function (e) {
const routes = e.routes;
const routePolyline = routes[0].coordinates;
console.log('routePolyline[0]: ', routePolyline[0]);
// Find the furthest point from the original polyline to the generated polyline
const furthestPoint = findFurthestPoint(latlngs, routePolyline);
console.log('furthestPoint: ', furthestPoint);
// Create new waypoints with the furthest point added
const newWaypoints = [
L.latLng(startPoint.lat, startPoint.lng),
L.latLng(furthestPoint.lat, furthestPoint.lng),
L.latLng(endPoint.lat, endPoint.lng)
];
// Generate the new route with the updated waypoints
generateNewRoute(newWaypoints);
});
}
function generateNewRoute(waypoints) {
if (window.finalRoutingControl) {
map.removeControl(window.finalRoutingControl);
}
window.finalRoutingControl = L.Routing.control({
waypoints: waypoints,
routeWhileDragging: false
}).addTo(map);
}
function findFurthestPoint(originalPolyline, generatedPolyline) {
let maxDistance = -1;
let furthestPoint = null;
originalPolyline.forEach(point => {
const latlngPoint = L.latLng(point.lat, point.lng);
const distance = findDistanceToPolyline(latlngPoint, generatedPolyline);
if (distance > maxDistance) {
maxDistance = distance;
furthestPoint = point;
}
});
return furthestPoint;
}
function findDistanceToPolyline(point, polyline) {
let minDistance = Infinity;
polyline.forEach((segmentPoint, index) => {
if (index === 0) return;
const prevPoint = polyline[index - 1];
console.log('Current shapefile point: ', point);
console.log('Current generated polyline point: ', segment);
const segmentDistance = L.GeometryUtil.distanceSegment(map, point, prevPoint, segmentPoint);
minDistance = Math.min(minDistance, segmentDistance);
});
return minDistance;
}