Refactor direction engines and unify structure

This commit is contained in:
Marwin Hochfelsner 2025-02-04 14:42:06 +01:00 committed by Marwin Hochfelsner
parent e206dd527e
commit 957ae192b6
3 changed files with 223 additions and 240 deletions

View file

@ -3,42 +3,37 @@
(function () { (function () {
function FOSSGISOSRMEngine(id, vehicleType) { function FOSSGISOSRMEngine(id, vehicleType) {
var cachedHints = []; let cachedHints = [];
return { function _processDirections(route) {
id: id, const INSTRUCTION_TEMPLATE = {
creditline: "<a href=\"https://routing.openstreetmap.de/about.html\" target=\"_blank\">OSRM (FOSSGIS)</a>", "continue": "continue",
draggable: true, "merge right": "merge_right",
"merge left": "merge_left",
_transformSteps: function (input_steps, line) { "off ramp right": "offramp_right",
var INSTRUCTION_TEMPLATE = { "off ramp left": "offramp_left",
"continue": "javascripts.directions.instructions.continue", "on ramp right": "onramp_right",
"merge right": "javascripts.directions.instructions.merge_right", "on ramp left": "onramp_left",
"merge left": "javascripts.directions.instructions.merge_left", "fork right": "fork_right",
"off ramp right": "javascripts.directions.instructions.offramp_right", "fork left": "fork_left",
"off ramp left": "javascripts.directions.instructions.offramp_left", "end of road right": "endofroad_right",
"on ramp right": "javascripts.directions.instructions.onramp_right", "end of road left": "endofroad_left",
"on ramp left": "javascripts.directions.instructions.onramp_left", "turn straight": "continue",
"fork right": "javascripts.directions.instructions.fork_right", "turn slight right": "slight_right",
"fork left": "javascripts.directions.instructions.fork_left", "turn right": "turn_right",
"end of road right": "javascripts.directions.instructions.endofroad_right", "turn sharp right": "sharp_right",
"end of road left": "javascripts.directions.instructions.endofroad_left", "turn uturn": "uturn",
"turn straight": "javascripts.directions.instructions.continue", "turn sharp left": "sharp_left",
"turn slight right": "javascripts.directions.instructions.slight_right", "turn left": "turn_left",
"turn right": "javascripts.directions.instructions.turn_right", "turn slight left": "slight_left",
"turn sharp right": "javascripts.directions.instructions.sharp_right", "roundabout": "roundabout",
"turn uturn": "javascripts.directions.instructions.uturn", "rotary": "roundabout",
"turn sharp left": "javascripts.directions.instructions.sharp_left", "exit roundabout": "exit_roundabout",
"turn left": "javascripts.directions.instructions.turn_left", "exit rotary": "exit_roundabout",
"turn slight left": "javascripts.directions.instructions.slight_left", "depart": "start",
"roundabout": "javascripts.directions.instructions.roundabout", "arrive": "destination"
"rotary": "javascripts.directions.instructions.roundabout",
"exit roundabout": "javascripts.directions.instructions.exit_roundabout",
"exit rotary": "javascripts.directions.instructions.exit_roundabout",
"depart": "javascripts.directions.instructions.start",
"arrive": "javascripts.directions.instructions.destination"
}; };
var ICON_MAP = { const ICON_MAP = {
"continue": 0, "continue": 0,
"merge right": 21, "merge right": 21,
"merge left": 20, "merge left": 20,
@ -65,49 +60,47 @@
"depart": 8, "depart": 8,
"arrive": 14 "arrive": 14
}; };
var numToWord = function (num) { function numToWord(num) {
return ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth"][num - 1]; return ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth"][num - 1];
}; }
var transformed_steps = input_steps.map(function (step, idx) { function getManeuverId(maneuver) {
var maneuver_id;
// special case handling // special case handling
switch (step.maneuver.type) { switch (maneuver.type) {
case "on ramp": case "on ramp":
case "off ramp": case "off ramp":
case "merge": case "merge":
case "end of road": case "end of road":
case "fork": case "fork":
maneuver_id = step.maneuver.type + " " + (step.maneuver.modifier.indexOf("left") >= 0 ? "left" : "right"); return maneuver.type + " " + (maneuver.modifier.indexOf("left") >= 0 ? "left" : "right");
break;
case "depart": case "depart":
case "arrive": case "arrive":
case "roundabout": case "roundabout":
case "rotary": case "rotary":
case "exit roundabout": case "exit roundabout":
case "exit rotary": case "exit rotary":
maneuver_id = step.maneuver.type; return maneuver.type;
break;
case "roundabout turn": case "roundabout turn":
case "turn": case "turn":
maneuver_id = "turn " + step.maneuver.modifier; return "turn " + maneuver.modifier;
break;
// for unknown types the fallback is turn // for unknown types the fallback is turn
default: default:
maneuver_id = "turn " + step.maneuver.modifier; return "turn " + maneuver.modifier;
break; }
} }
var template = INSTRUCTION_TEMPLATE[maneuver_id];
// convert lat,lng pairs to LatLng objects const steps = route.legs.flatMap(
var step_geometry = L.PolylineUtil.decode(step.geometry, { precision: 5 }).map(function (a) { return L.latLng(a); }); leg => leg.steps.map(function (step, idx) {
// append step_geometry on line const maneuver_id = getManeuverId(step.maneuver);
Array.prototype.push.apply(line, step_geometry);
var instText = "<b>" + (idx + 1) + ".</b> "; const instrPrefix = "javascripts.directions.instructions.";
var destinations = "<b>" + step.destinations + "</b>"; let template = instrPrefix + INSTRUCTION_TEMPLATE[maneuver_id];
var namedRoad = true;
var name; const step_geometry = L.PolylineUtil.decode(step.geometry, { precision: 5 }).map(L.latLng);
let instText = "<b>" + (idx + 1) + ".</b> ";
const destinations = "<b>" + step.destinations + "</b>";
let namedRoad = true;
let name;
if (step.name && step.ref) { if (step.name && step.ref) {
name = "<b>" + step.name + " (" + step.ref + ")</b>"; name = "<b>" + step.name + " (" + step.ref + ")</b>";
@ -116,7 +109,7 @@
} else if (step.ref) { } else if (step.ref) {
name = "<b>" + step.ref + "</b>"; name = "<b>" + step.ref + "</b>";
} else { } else {
name = I18n.t("javascripts.directions.instructions.unnamed"); name = I18n.t(instrPrefix + "unnamed");
namedRoad = false; namedRoad = false;
} }
@ -125,7 +118,7 @@
} else if (step.maneuver.type.match(/^(rotary|roundabout)$/)) { } else if (step.maneuver.type.match(/^(rotary|roundabout)$/)) {
if (step.maneuver.exit) { if (step.maneuver.exit) {
if (step.maneuver.exit <= 10) { if (step.maneuver.exit <= 10) {
instText += I18n.t(template + "_with_exit_ordinal", { exit: I18n.t("javascripts.directions.instructions.exit_counts." + numToWord(step.maneuver.exit)), name: name }); instText += I18n.t(template + "_with_exit_ordinal", { exit: I18n.t(instrPrefix + "exit_counts." + numToWord(step.maneuver.exit)), name: name });
} else { } else {
instText += I18n.t(template + "_with_exit", { exit: step.maneuver.exit, name: name }); instText += I18n.t(template + "_with_exit", { exit: step.maneuver.exit, name: name });
} }
@ -133,7 +126,7 @@
instText += I18n.t(template + "_without_exit", { name: name }); instText += I18n.t(template + "_without_exit", { name: name });
} }
} else if (step.maneuver.type.match(/^(on ramp|off ramp)$/)) { } else if (step.maneuver.type.match(/^(on ramp|off ramp)$/)) {
var params = {}; const params = {};
if (step.exits && step.maneuver.type.match(/^(off ramp)$/)) params.exit = step.exits; if (step.exits && step.maneuver.type.match(/^(off ramp)$/)) params.exit = step.exits;
if (step.destinations) params.directions = destinations; if (step.destinations) params.directions = destinations;
if (namedRoad) params.directions = name; if (namedRoad) params.directions = name;
@ -145,61 +138,50 @@
instText += I18n.t(template + "_without_exit", { name: name }); instText += I18n.t(template + "_without_exit", { name: name });
} }
return [[step.maneuver.location[1], step.maneuver.location[0]], ICON_MAP[maneuver_id], instText, step.distance, step_geometry]; return [[step.maneuver.location[1], step.maneuver.location[0]], ICON_MAP[maneuver_id], instText, step.distance, step_geometry];
}); })
);
return transformed_steps; return {
}, line: steps.flatMap(step => step[4]),
steps,
distance: route.distance,
time: route.duration
};
}
return {
id: id,
creditline: "<a href=\"https://routing.openstreetmap.de/about.html\" target=\"_blank\">OSRM (FOSSGIS)</a>",
draggable: true,
getRoute: function (points, callback) { getRoute: function (points, callback) {
var params = [ const data = [
{ name: "overview", value: "false" }, { name: "overview", value: "false" },
{ name: "geometries", value: "polyline" }, { name: "geometries", value: "polyline" },
{ name: "steps", value: true } { name: "steps", value: true }
]; ];
if (cachedHints.length === points.length) { if (cachedHints.length === points.length) {
params.push({ name: "hints", value: cachedHints.join(";") }); data.push({ name: "hints", value: cachedHints.join(";") });
} else { } else {
// invalidate cache // invalidate cache
cachedHints = []; cachedHints = [];
} }
var encoded_coords = points.map(function (p) { const req_path = "routed-" + vehicleType + "/route/v1/driving/" + points.map(p => p.lng + "," + p.lat).join(";");
return p.lng + "," + p.lat;
}).join(";");
var req_url = OSM.FOSSGIS_OSRM_URL + "routed-" + vehicleType + "/route/v1/driving/" + encoded_coords; return $.ajax({
url: OSM.FOSSGIS_OSRM_URL + req_path,
var onResponse = function (data) { data,
if (data.code !== "Ok") { dataType: "json",
success: function (response) {
if (response.code !== "Ok") {
return callback(true); return callback(true);
} }
cachedHints = data.waypoints.map(function (wp) { cachedHints = response.waypoints.map(wp => wp.hint);
return wp.hint; callback(false, _processDirections(response.routes[0]));
}); },
var line = [];
var transformLeg = function (leg) {
return this._transformSteps(leg.steps, line);
};
var steps = [].concat.apply([], data.routes[0].legs.map(transformLeg.bind(this)));
callback(false, {
line: line,
steps: steps,
distance: data.routes[0].distance,
time: data.routes[0].duration
});
};
return $.ajax({
url: req_url,
data: params,
dataType: "json",
success: onResponse.bind(this),
error: function () { error: function () {
callback(true); callback(true);
} }

View file

@ -1,6 +1,6 @@
(function () { (function () {
function FOSSGISValhallaEngine(id, costing) { function FOSSGISValhallaEngine(id, costing) {
var INSTR_MAP = [ const INSTR_MAP = [
0, // kNone = 0; 0, // kNone = 0;
8, // kStart = 1; 8, // kStart = 1;
8, // kStartRight = 2; 8, // kStartRight = 2;
@ -42,6 +42,45 @@
20 // kMergeLeft = 38; 20 // kMergeLeft = 38;
]; ];
function _processDirections(tripLegs) {
let line = [];
let steps = [];
let distance = 0;
let time = 0;
for (const leg of tripLegs) {
const legLine = L.PolylineUtil.decode(leg.shape, {
precision: 6
});
const legSteps = leg.maneuvers.map(function (manoeuvre, idx) {
const num = `<b>${idx + 1}.</b> `;
const lineseg = legLine
.slice(manoeuvre.begin_shape_index, manoeuvre.end_shape_index + 1)
.map(([lat, lng]) => ({ lat, lng }));
return [
lineseg[0],
INSTR_MAP[manoeuvre.type],
num + manoeuvre.instruction,
manoeuvre.length * 1000,
lineseg
];
});
line = line.concat(legLine);
steps = steps.concat(legSteps);
distance += leg.summary.length;
time += leg.summary.time;
}
return {
line: line,
steps: steps,
distance: distance * 1000,
time: time
};
}
return { return {
id: id, id: id,
creditline: creditline:
@ -49,9 +88,7 @@
draggable: false, draggable: false,
getRoute: function (points, callback) { getRoute: function (points, callback) {
return $.ajax({ const data = {
url: OSM.FOSSGIS_VALHALLA_URL,
data: {
json: JSON.stringify({ json: JSON.stringify({
locations: points.map(function (p) { locations: points.map(function (p) {
return { lat: p.lat, lon: p.lng, radius: 5 }; return { lat: p.lat, lon: p.lng, radius: 5 };
@ -62,46 +99,14 @@
language: I18n.currentLocale() language: I18n.currentLocale()
} }
}) })
}, };
return $.ajax({
url: OSM.FOSSGIS_VALHALLA_URL,
data,
dataType: "json", dataType: "json",
success: function (data) { success: function ({ trip }) {
var trip = data.trip;
if (trip.status === 0) { if (trip.status === 0) {
var line = []; callback(false, _processDirections(trip.legs));
var steps = [];
var distance = 0;
var time = 0;
trip.legs.forEach(function (leg) {
var legLine = L.PolylineUtil.decode(leg.shape, {
precision: 6
});
line = line.concat(legLine);
leg.maneuvers.forEach(function (manoeuvre, idx) {
var point = legLine[manoeuvre.begin_shape_index];
steps.push([
{ lat: point[0], lng: point[1] },
INSTR_MAP[manoeuvre.type],
"<b>" + (idx + 1) + ".</b> " + manoeuvre.instruction,
manoeuvre.length * 1000,
[]
]);
});
distance = distance + leg.summary.length;
time = time + leg.summary.time;
});
callback(false, {
line: line,
steps: steps,
distance: distance * 1000,
time: time
});
} else { } else {
callback(true); callback(true);
} }

View file

@ -1,6 +1,6 @@
(function () { (function () {
function GraphHopperEngine(id, vehicleType) { function GraphHopperEngine(id, vehicleType) {
var GH_INSTR_MAP = { const GH_INSTR_MAP = {
"-3": 7, // sharp left "-3": 7, // sharp left
"-2": 6, // left "-2": 6, // left
"-1": 5, // slight left "-1": 5, // slight left
@ -18,6 +18,34 @@
"8": 4 // right u-turn "8": 4 // right u-turn
}; };
function _processDirections(path) {
const line = L.PolylineUtil.decode(path.points);
const steps = path.instructions.map(function (instr, i) {
const num = `<b>${i + 1}.</b> `;
const lineseg = line
.slice(instr.interval[0], instr.interval[1] + 1)
.map(([lat, lng]) => ({ lat, lng }));
return [
lineseg[0],
GH_INSTR_MAP[instr.sign],
num + instr.text,
instr.distance,
lineseg
]; // TODO does graphhopper map instructions onto line indices?
});
steps.at(-1)[1] = 14;
return {
line: line,
steps: steps,
distance: path.distance,
time: path.time / 1000,
ascend: path.ascend,
descend: path.descend
};
}
return { return {
id: id, id: id,
creditline: "<a href=\"https://www.graphhopper.com/\" target=\"_blank\">GraphHopper</a>", creditline: "<a href=\"https://www.graphhopper.com/\" target=\"_blank\">GraphHopper</a>",
@ -26,57 +54,25 @@
getRoute: function (points, callback) { getRoute: function (points, callback) {
// GraphHopper Directions API documentation // GraphHopper Directions API documentation
// https://graphhopper.com/api/1/docs/routing/ // https://graphhopper.com/api/1/docs/routing/
return $.ajax({ const data = {
url: OSM.GRAPHHOPPER_URL,
data: {
vehicle: vehicleType, vehicle: vehicleType,
locale: I18n.currentLocale(), locale: I18n.currentLocale(),
key: "LijBPDQGfu7Iiq80w3HzwB4RUDJbMbhs6BU0dEnn", key: "LijBPDQGfu7Iiq80w3HzwB4RUDJbMbhs6BU0dEnn",
elevation: false, elevation: false,
instructions: true, instructions: true,
turn_costs: vehicleType === "car", turn_costs: vehicleType === "car",
point: points.map(function (p) { return p.lat + "," + p.lng; }) point: points.map(p => p.lat + "," + p.lng)
}, };
return $.ajax({
url: OSM.GRAPHHOPPER_URL,
data,
traditional: true, traditional: true,
dataType: "json", dataType: "json",
success: function (data) { success: function ({ paths }) {
if (!data.paths || data.paths.length === 0) { if (!paths || paths.length === 0) {
return callback(true); return callback(true);
} }
callback(false, _processDirections(paths[0]));
var path = data.paths[0];
var line = L.PolylineUtil.decode(path.points);
var steps = [];
var len = path.instructions.length;
for (var i = 0; i < len; i++) {
var instr = path.instructions[i];
var instrCode = (i === len - 1) ? 14 : GH_INSTR_MAP[instr.sign];
var instrText = "<b>" + (i + 1) + ".</b> ";
instrText += instr.text;
var latLng = line[instr.interval[0]];
var distInMeter = instr.distance;
var lineseg = [];
for (var j = instr.interval[0]; j <= instr.interval[1]; j++) {
lineseg.push({ lat: line[j][0], lng: line[j][1] });
}
steps.push([
{ lat: latLng[0], lng: latLng[1] },
instrCode,
instrText,
distInMeter,
lineseg
]); // TODO does graphhopper map instructions onto line indices?
}
callback(false, {
line: line,
steps: steps,
distance: path.distance,
time: path.time / 1000,
ascend: path.ascend,
descend: path.descend
});
}, },
error: function () { error: function () {
callback(true); callback(true);