Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get directions using fetch #5642

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 14 additions & 17 deletions app/assets/javascripts/index/directions.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
//= require_tree ./directions

OSM.Directions = function (map) {
var routeRequest = null; // jqXHR object of an ongoing route request or null
let awaitingRoute = false; // true if a route request is in progress
let controller = null; // the AbortController for the current route request
var chosenEngine;

var popup = L.popup({ autoPanPadding: [100, 100] });
Expand All @@ -23,7 +24,7 @@ OSM.Directions = function (map) {
var endpointDragCallback = function (dragging) {
if (!map.hasLayer(polyline)) return;
if (dragging && !chosenEngine.draggable) return;
if (dragging && routeRequest) return;
if (dragging && awaitingRoute) return;

getRoute(false, !dragging);
};
Expand Down Expand Up @@ -109,7 +110,7 @@ OSM.Directions = function (map) {

function getRoute(fitRoute, reportErrors) {
// Cancel any route that is already in progress
if (routeRequest) routeRequest.abort();
if (controller) controller.abort();

const points = endpoints.map(p => p.latlng);

Expand All @@ -126,20 +127,9 @@ OSM.Directions = function (map) {
// again.
$("#sidebar_content").html($(".directions_form .loader_copy").html());
map.setSidebarOverlaid(false);

routeRequest = chosenEngine.getRoute(points, function (err, route) {
routeRequest = null;

if (err) {
map.removeLayer(polyline);

if (reportErrors) {
$("#sidebar_content").html("<div class=\"alert alert-danger\">" + I18n.t("javascripts.directions.errors.no_route") + "</div>");
}

return;
}

controller = new AbortController();
awaitingRoute = true;
chosenEngine.getRoute(points, controller.signal).then(function (route) {
polyline
.setLatLngs(route.line)
.addTo(map);
Expand Down Expand Up @@ -212,6 +202,13 @@ OSM.Directions = function (map) {
map.setSidebarOverlaid(true);
// TODO: collapse width of sidebar back to previous
});
}).catch(function () {
map.removeLayer(polyline);
if (reportErrors) {
$("#sidebar_content").html("<div class=\"alert alert-danger\">" + I18n.t("javascripts.directions.errors.no_route") + "</div>");
}
}).finally(function () {
awaitingRoute = false;
});

function getDistText(dist) {
Expand Down
33 changes: 13 additions & 20 deletions app/assets/javascripts/index/directions/fossgis_osrm.js
Original file line number Diff line number Diff line change
Expand Up @@ -154,38 +154,31 @@
creditline: "<a href=\"https://routing.openstreetmap.de/about.html\" target=\"_blank\">OSRM (FOSSGIS)</a>",
draggable: true,

getRoute: function (points, callback) {
const data = [
{ name: "overview", value: "false" },
{ name: "geometries", value: "polyline" },
{ name: "steps", value: true }
];
getRoute: function (points, signal) {
const query = new URLSearchParams({
overview: "false",
geometries: "polyline",
steps: true
});

if (cachedHints.length === points.length) {
data.push({ name: "hints", value: cachedHints.join(";") });
query.set("hints", cachedHints.join(";"));
} else {
// invalidate cache
cachedHints = [];
}

const req_path = "routed-" + vehicleType + "/route/v1/driving/" + points.map(p => p.lng + "," + p.lat).join(";");

return $.ajax({
url: OSM.FOSSGIS_OSRM_URL + req_path,
data,
dataType: "json",
success: function (response) {
return fetch(OSM.FOSSGIS_OSRM_URL + req_path + "?" + query, { signal })
.then(response => response.json())
.then(response => {
if (response.code !== "Ok") {
return callback(true);
throw new TypeError("Response " + response.code);
}

cachedHints = response.waypoints.map(wp => wp.hint);
callback(false, _processDirections(response.routes[0]));
},
error: function () {
callback(true);
}
});
return _processDirections(response.routes[0]);
});
}
};
}
Expand Down
27 changes: 10 additions & 17 deletions app/assets/javascripts/index/directions/fossgis_valhalla.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,8 @@
"<a href='https://gis-ops.com/global-open-valhalla-server-online/' target='_blank'>Valhalla (FOSSGIS)</a>",
draggable: false,

getRoute: function (points, callback) {
const data = {
getRoute: function (points, signal) {
const query = new URLSearchParams({
json: JSON.stringify({
locations: points.map(function (p) {
return { lat: p.lat, lon: p.lng, radius: 5 };
Expand All @@ -99,22 +99,15 @@
language: I18n.currentLocale()
}
})
};
return $.ajax({
url: OSM.FOSSGIS_VALHALLA_URL,
data,
dataType: "json",
success: function ({ trip }) {
if (trip.status === 0) {
callback(false, _processDirections(trip.legs));
} else {
callback(true);
}
},
error: function () {
callback(true);
}
});
return fetch(OSM.FOSSGIS_VALHALLA_URL + "?" + query, { signal })
.then(response => response.json())
.then(({ trip }) => {
if (trip.status !== 0) {
hlfan marked this conversation as resolved.
Show resolved Hide resolved
throw new TypeError("Response status " + trip.status);
}
return _processDirections(trip.legs);
});
}
};
}
Expand Down
25 changes: 9 additions & 16 deletions app/assets/javascripts/index/directions/graphhopper.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,33 +51,26 @@
creditline: "<a href=\"https://www.graphhopper.com/\" target=\"_blank\">GraphHopper</a>",
draggable: false,

getRoute: function (points, callback) {
getRoute: function (points, signal) {
// GraphHopper Directions API documentation
// https://graphhopper.com/api/1/docs/routing/
const data = {
const query = new URLSearchParams({
vehicle: vehicleType,
locale: I18n.currentLocale(),
key: "LijBPDQGfu7Iiq80w3HzwB4RUDJbMbhs6BU0dEnn",
elevation: false,
instructions: true,
turn_costs: vehicleType === "car",
point: points.map(p => p.lat + "," + p.lng)
};
return $.ajax({
url: OSM.GRAPHHOPPER_URL,
data,
traditional: true,
dataType: "json",
success: function ({ paths }) {
});
return fetch(OSM.GRAPHHOPPER_URL + "?" + query, { signal })
.then(response => response.json())
.then(({ paths }) => {
if (!paths || paths.length === 0) {
return callback(true);
throw new TypeError("Response empty");
}
callback(false, _processDirections(paths[0]));
},
error: function () {
callback(true);
}
});
return _processDirections(paths[0]);
});
}
};
}
Expand Down
Loading