1 //= require ./directions-endpoint
 
   3 //= require_tree ./directions
 
   5 OSM.Directions = function (map) {
 
   6   let controller = null; // the AbortController for the current route request if a route request is in progress
 
  10   const popup = L.popup({ autoPanPadding: [100, 100] });
 
  12   const polyline = L.polyline([], {
 
  18   const highlight = L.polyline([], {
 
  24   const endpointDragCallback = function (dragging) {
 
  25     if (!map.hasLayer(polyline)) return;
 
  26     if (dragging && !chosenEngine.draggable) return;
 
  27     if (dragging && controller) return;
 
  29     getRoute(false, !dragging);
 
  31   const endpointChangeCallback = function () {
 
  36     OSM.DirectionsEndpoint(map, $("input[name='route_from']"), OSM.MARKER_GREEN, endpointDragCallback, endpointChangeCallback),
 
  37     OSM.DirectionsEndpoint(map, $("input[name='route_to']"), OSM.MARKER_RED, endpointDragCallback, endpointChangeCallback)
 
  40   let downloadURL = null;
 
  42   const expiry = new Date();
 
  43   expiry.setYear(expiry.getFullYear() + 10);
 
  45   const modeGroup = $(".routing_modes");
 
  46   const select = $("select.routing_engines");
 
  48   $(".directions_form .reverse_directions").on("click", function () {
 
  49     const coordFrom = endpoints[0].latlng,
 
  50           coordTo = endpoints[1].latlng;
 
  54       routeFrom = coordFrom.lat + "," + coordFrom.lng;
 
  57       routeTo = coordTo.lat + "," + coordTo.lng;
 
  59     endpoints[0].swapCachedReverseGeocodes(endpoints[1]);
 
  61     OSM.router.route("/directions?" + new URLSearchParams({
 
  62       route: routeTo + ";" + routeFrom
 
  66   $(".directions_form .btn-close").on("click", function (e) {
 
  68     $(".describe_location").toggle(!endpoints[1].value);
 
  69     $(".search_form input[name='query']").val(endpoints[1].value);
 
  70     OSM.router.route("/" + OSM.formatHash(map));
 
  73   function formatTotalDistance(m) {
 
  75       return OSM.i18n.t("javascripts.directions.distance_m", { distance: Math.round(m) });
 
  76     } else if (m < 10000) {
 
  77       return OSM.i18n.t("javascripts.directions.distance_km", { distance: (m / 1000.0).toFixed(1) });
 
  79       return OSM.i18n.t("javascripts.directions.distance_km", { distance: Math.round(m / 1000) });
 
  83   function formatStepDistance(m) {
 
  87       return OSM.i18n.t("javascripts.directions.distance_m", { distance: String(Math.round(m / 10) * 10) });
 
  88     } else if (m < 1500) {
 
  89       return OSM.i18n.t("javascripts.directions.distance_m", { distance: String(Math.round(m / 100) * 100) });
 
  90     } else if (m < 5000) {
 
  91       return OSM.i18n.t("javascripts.directions.distance_km", { distance: String(Math.round(m / 100) / 10) });
 
  93       return OSM.i18n.t("javascripts.directions.distance_km", { distance: String(Math.round(m / 1000)) });
 
  97   function formatHeight(m) {
 
  98     return OSM.i18n.t("javascripts.directions.distance_m", { distance: Math.round(m) });
 
 101   function formatTime(s) {
 
 102     let m = Math.round(s / 60);
 
 103     const h = Math.floor(m / 60);
 
 105     return h + ":" + (m < 10 ? "0" : "") + m;
 
 108   function setEngine(id) {
 
 109     const engines = OSM.Directions.engines;
 
 110     const desired = engines.find(engine => engine.id === id);
 
 111     if (!desired || (chosenEngine && chosenEngine.id === id)) return;
 
 112     chosenEngine = desired;
 
 114     const modes = engines
 
 115       .filter(engine => engine.provider === chosenEngine.provider)
 
 116       .map(engine => engine.mode);
 
 119       .prop("disabled", function () {
 
 120         return !modes.includes(this.id);
 
 122       .prop("checked", function () {
 
 123         return this.id === chosenEngine.mode;
 
 126     const providers = engines
 
 127       .filter(engine => engine.mode === chosenEngine.mode)
 
 128       .map(engine => engine.provider);
 
 130       .find("option[value]")
 
 131       .prop("disabled", function () {
 
 132         return !providers.includes(this.value);
 
 134     select.val(chosenEngine.provider);
 
 137   function getRoute(fitRoute, reportErrors) {
 
 138     // Cancel any route that is already in progress
 
 139     if (controller) controller.abort();
 
 141     const points = endpoints.map(p => p.latlng);
 
 143     if (!points[0] || !points[1]) return;
 
 144     $("header").addClass("closed");
 
 146     OSM.router.replace("/directions?" + new URLSearchParams({
 
 147       engine: chosenEngine.id,
 
 148       route: points.map(p => `${p.lat},${p.lng}`).join(";")
 
 151     // copy loading item to sidebar and display it. we copy it, rather than
 
 152     // just using it in-place and replacing it in case it has to be used
 
 154     $("#directions_content").html($(".directions_form .loader_copy").html());
 
 155     map.setSidebarOverlaid(false);
 
 156     controller = new AbortController();
 
 157     chosenEngine.getRoute(points, controller.signal).then(function (route) {
 
 159         .setLatLngs(route.line)
 
 163         map.fitBounds(polyline.getBounds().pad(0.05));
 
 166       const distanceText = $("<p>").append(
 
 167         OSM.i18n.t("javascripts.directions.distance") + ": " + formatTotalDistance(route.distance) + ". " +
 
 168         OSM.i18n.t("javascripts.directions.time") + ": " + formatTime(route.time) + ".");
 
 169       if (typeof route.ascend !== "undefined" && typeof route.descend !== "undefined") {
 
 172           OSM.i18n.t("javascripts.directions.ascend") + ": " + formatHeight(route.ascend) + ". " +
 
 173           OSM.i18n.t("javascripts.directions.descend") + ": " + formatHeight(route.descend) + ".");
 
 176       const turnByTurnTable = $("<table class='table table-hover table-sm mb-3'>")
 
 177         .append($("<tbody>"));
 
 179       $("#directions_content")
 
 187       route.steps.forEach(function (step) {
 
 188         const [ll, direction, instruction, dist, lineseg] = step;
 
 190         const row = $("<tr class='turn'/>");
 
 192           row.append("<td class='border-0'><svg width='20' height='20' class='d-block'><use href='#routing-sprite-" + direction + "' /></svg></td>");
 
 194           row.append("<td class='border-0'>");
 
 196         row.append("<td>" + instruction);
 
 197         row.append("<td class='distance text-body-secondary text-end'>" + formatStepDistance(dist));
 
 199         row.on("click", function () {
 
 202             .setContent("<p>" + instruction + "</p>")
 
 206         row.hover(function () {
 
 211           map.removeLayer(highlight);
 
 214         turnByTurnTable.append(row);
 
 217       const blob = new Blob([JSON.stringify(polyline.toGeoJSON())], { type: "application/json" });
 
 218       URL.revokeObjectURL(downloadURL);
 
 219       downloadURL = URL.createObjectURL(blob);
 
 221       $("#directions_content").append(`<p class="text-center"><a href="${downloadURL}" download="${
 
 222         OSM.i18n.t("javascripts.directions.filename")
 
 224         OSM.i18n.t("javascripts.directions.download")
 
 227       $("#directions_content").append("<p class=\"text-center\">" +
 
 228         OSM.i18n.t("javascripts.directions.instructions.courtesy", { link: chosenEngine.creditline }) +
 
 230     }).catch(function () {
 
 231       map.removeLayer(polyline);
 
 233         $("#directions_content").html("<div class=\"alert alert-danger\">" + OSM.i18n.t("javascripts.directions.errors.no_route") + "</div>");
 
 235     }).finally(function () {
 
 240   function hideRoute(e) {
 
 242     map.removeLayer(polyline);
 
 243     $("#directions_content").html("");
 
 245     map.setSidebarOverlaid(true);
 
 246     // TODO: collapse width of sidebar back to previous
 
 249   setEngine("fossgis_osrm_car");
 
 250   setEngine(Cookies.get("_osm_directions_engine"));
 
 252   modeGroup.on("change", "input[name='modes']", function (e) {
 
 253     setEngine(chosenEngine.provider + "_" + e.target.id);
 
 254     Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
 
 255     getRoute(true, true);
 
 258   select.on("change", function (e) {
 
 259     setEngine(e.target.value + "_" + chosenEngine.mode);
 
 260     Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
 
 261     getRoute(true, true);
 
 264   $(".directions_form").on("submit", function (e) {
 
 266     getRoute(true, true);
 
 269   $(".routing_marker_column img").on("dragstart", function (e) {
 
 270     const dt = e.originalEvent.dataTransfer;
 
 271     dt.effectAllowed = "move";
 
 272     const dragData = { type: $(this).data("type") };
 
 273     dt.setData("text", JSON.stringify(dragData));
 
 274     if (dt.setDragImage) {
 
 275       const img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
 
 276       dt.setDragImage(img.get(0), 12, 21);
 
 280   function sendstartinglocation({ latlng: { lat, lng } }) {
 
 281     map.fire("startinglocation", { latlng: [lat, lng] });
 
 284   function startingLocationListener({ latlng }) {
 
 285     if (endpoints[0].value) return;
 
 286     endpoints[0].setValue(latlng.join(", "));
 
 289   map.on("locationfound", ({ latlng: { lat, lng } }) =>
 
 290     lastLocation = [lat, lng]
 
 291   ).on("locateactivate", () => {
 
 292     map.once("startinglocation", startingLocationListener);
 
 295   function initializeFromParams() {
 
 296     const params = new URLSearchParams(location.search),
 
 297           route = (params.get("route") || "").split(";");
 
 299     if (params.has("engine")) setEngine(params.get("engine"));
 
 301     endpoints[0].setValue(params.get("from") || route[0] || lastLocation.join(", "));
 
 302     endpoints[1].setValue(params.get("to") || route[1] || "");
 
 305   function enableListeners() {
 
 306     $("#sidebar .sidebar-close-controls button").on("click", hideRoute);
 
 308     $("#map").on("dragend dragover", function (e) {
 
 312     $("#map").on("drop", function (e) {
 
 314       const oe = e.originalEvent;
 
 315       const dragData = JSON.parse(oe.dataTransfer.getData("text"));
 
 316       const type = dragData.type;
 
 317       const pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
 
 319       const ll = map.containerPointToLatLng(pt);
 
 320       const llWithPrecision = OSM.cropLocation(ll, map.getZoom());
 
 321       endpoints[type === "from" ? 0 : 1].setValue(llWithPrecision.join(", "));
 
 324     map.on("locationfound", sendstartinglocation);
 
 326     endpoints[0].enableListeners();
 
 327     endpoints[1].enableListeners();
 
 332   page.pushstate = page.popstate = function () {
 
 333     if ($("#directions_content").length) {
 
 336       initializeFromParams();
 
 338       $(".search_form").hide();
 
 339       $(".directions_form").show();
 
 341       OSM.loadSidebarContent("/directions", enableListeners);
 
 343       map.setSidebarOverlaid(!endpoints[0].latlng || !endpoints[1].latlng);
 
 347   page.load = function () {
 
 348     initializeFromParams();
 
 350     $(".search_form").hide();
 
 351     $(".directions_form").show();
 
 355     map.setSidebarOverlaid(!endpoints[0].latlng || !endpoints[1].latlng);
 
 358   page.unload = function () {
 
 359     $(".search_form").show();
 
 360     $(".directions_form").hide();
 
 362     $("#sidebar .sidebar-close-controls button").off("click", hideRoute);
 
 363     $("#map").off("dragend dragover drop");
 
 364     map.off("locationfound", sendstartinglocation);
 
 366     endpoints[0].disableListeners();
 
 367     endpoints[1].disableListeners();
 
 369     endpoints[0].clearValue();
 
 370     endpoints[1].clearValue();
 
 374       .removeLayer(polyline);
 
 380 OSM.Directions.engines = [];
 
 382 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
 
 383   if (location.protocol === "http:" || supportsHTTPS) {
 
 384     engine.id = engine.provider + "_" + engine.mode;
 
 385     OSM.Directions.engines.push(engine);