1 //= require ./directions-endpoint
 
   2 //= require ./directions-route-output
 
   4 //= require_tree ./directions
 
   6 OSM.Directions = function (map) {
 
   7   let controller = null; // the AbortController for the current route request if a route request is in progress
 
  11   let sidebarReadyPromise = null;
 
  13   const routeOutput = OSM.DirectionsRouteOutput(map);
 
  15   const endpointDragCallback = function (dragging) {
 
  16     if (!routeOutput.isVisible()) return;
 
  17     if (dragging && !chosenEngine.draggable) return;
 
  18     if (dragging && controller) return;
 
  20     getRoute(false, !dragging);
 
  22   const endpointChangeCallback = function () {
 
  27     OSM.DirectionsEndpoint(map, $("input[name='route_from']"), { icon: "play", color: "var(--marker-green)" }, endpointDragCallback, endpointChangeCallback),
 
  28     OSM.DirectionsEndpoint(map, $("input[name='route_to']"), { icon: "stop", color: "var(--marker-red)" }, endpointDragCallback, endpointChangeCallback)
 
  31   const expiry = new Date();
 
  32   expiry.setYear(expiry.getFullYear() + 10);
 
  34   const modeGroup = $(".routing_modes");
 
  35   const select = $("select#routing_engines");
 
  37   $(".directions_form .reverse_directions").on("click", function () {
 
  38     const coordFrom = endpoints[0].latlng,
 
  39           coordTo = endpoints[1].latlng;
 
  43       routeFrom = coordFrom.lat + "," + coordFrom.lng;
 
  46       routeTo = coordTo.lat + "," + coordTo.lng;
 
  48     endpoints[0].swapCachedReverseGeocodes(endpoints[1]);
 
  50     OSM.router.route("/directions?" + new URLSearchParams({
 
  51       route: routeTo + ";" + routeFrom
 
  55   $(".directions_form .btn-close").on("click", function (e) {
 
  57     $(".search_form input[name='query']").val(endpoints[1].value);
 
  58     OSM.router.route("/" + OSM.formatHash(map));
 
  61   function setEngine(id) {
 
  62     const engines = OSM.Directions.engines;
 
  63     const desired = engines.find(engine => engine.id === id);
 
  64     if (!desired || (chosenEngine && chosenEngine.id === id)) return;
 
  65     chosenEngine = desired;
 
  68       .filter(engine => engine.provider === chosenEngine.provider)
 
  69       .map(engine => engine.mode);
 
  72       .prop("disabled", function () {
 
  73         return !modes.includes(this.value);
 
  75       .prop("checked", function () {
 
  76         return this.value === chosenEngine.mode;
 
  79     const providers = engines
 
  80       .filter(engine => engine.mode === chosenEngine.mode)
 
  81       .map(engine => engine.provider);
 
  83       .find("option[value]")
 
  84       .prop("disabled", function () {
 
  85         return !providers.includes(this.value);
 
  87     select.val(chosenEngine.provider);
 
  90   function getRoute(fitRoute, reportErrors) {
 
  91     // Cancel any route that is already in progress
 
  92     if (controller) controller.abort();
 
  94     const points = endpoints.map(p => p.latlng);
 
  96     if (!points[0] || !points[1]) return;
 
  97     $("header").addClass("closed");
 
  99     OSM.router.replace("/directions?" + new URLSearchParams({
 
 100       engine: chosenEngine.id,
 
 101       route: points.map(p => `${p.lat},${p.lng}`).join(";")
 
 104     $("#directions_loader").prop("hidden", false);
 
 105     $("#directions_error").prop("hidden", true).empty();
 
 106     $("#directions_route").prop("hidden", true);
 
 107     map.setSidebarOverlaid(false);
 
 108     controller = new AbortController();
 
 109     chosenEngine.getRoute(points, controller.signal).then(async function (route) {
 
 110       await sidebarLoaded();
 
 111       $("#directions_route").prop("hidden", false);
 
 112       routeOutput.write(route);
 
 116     }).catch(async function (error) {
 
 117       if (error.name === "AbortError") return;
 
 118       await sidebarLoaded();
 
 119       routeOutput.remove();
 
 121         $("#directions_error")
 
 122           .prop("hidden", false)
 
 123           .html("<div class=\"alert alert-danger\">" + OSM.i18n.t("javascripts.directions.errors.no_route") + "</div>");
 
 125     }).finally(function () {
 
 126       $("#directions_loader").prop("hidden", true);
 
 131   function closeButtonListener(e) {
 
 133     routeOutput.remove();
 
 134     sidebarReadyPromise = null;
 
 135     map.setSidebarOverlaid(true);
 
 138   setEngine("fossgis_osrm_car");
 
 139   setEngine(OSM.cookies.get("_osm_directions_engine"));
 
 141   modeGroup.on("change", "input[name='modes']", function (e) {
 
 142     setEngine(chosenEngine.provider + "_" + e.target.value);
 
 143     OSM.cookies.set("_osm_directions_engine", chosenEngine.id, { expires: expiry });
 
 144     getRoute(true, true);
 
 147   select.on("change", function (e) {
 
 148     setEngine(e.target.value + "_" + chosenEngine.mode);
 
 149     OSM.cookies.set("_osm_directions_engine", chosenEngine.id, { expires: expiry });
 
 150     getRoute(true, true);
 
 153   $(".directions_form").on("submit", function (e) {
 
 155     getRoute(true, true);
 
 158   $(".routing_marker_column span").on("dragstart", function (e) {
 
 159     const dt = e.originalEvent.dataTransfer;
 
 160     dt.effectAllowed = "move";
 
 161     const jqthis = $(this);
 
 162     dt.setData("text", JSON.stringify(jqthis.data()));
 
 163     if (dt.setDragImage) {
 
 164       const img = jqthis.clone()
 
 165         .appendTo(document.body);
 
 167         .toggleClass("position-absolute bottom-100 end-100")
 
 168         .attr({ width: "25", height: "40" });
 
 169       dt.setDragImage(img.get(0), 12, 21);
 
 170       setTimeout(() => img.remove(), 0);
 
 174   function sendstartinglocation({ latlng: { lat, lng } }) {
 
 175     map.fire("startinglocation", { latlng: [lat, lng] });
 
 178   function startingLocationListener({ latlng }) {
 
 179     if (endpoints[0].value) return;
 
 180     endpoints[0].setValue(latlng.join(", "));
 
 183   map.on("locationfound", ({ latlng: { lat, lng } }) =>
 
 184     lastLocation = [lat, lng]
 
 185   ).on("locateactivate", () => {
 
 186     map.once("startinglocation", startingLocationListener);
 
 189   function initializeFromParams() {
 
 190     const params = new URLSearchParams(location.search),
 
 191           route = (params.get("route") || "").split(";");
 
 193     if (params.has("engine")) setEngine(params.get("engine"));
 
 195     endpoints[0].setValue(params.get("from") || route[0] || lastLocation.join(", "));
 
 196     endpoints[1].setValue(params.get("to") || route[1] || "");
 
 199   function enableListeners() {
 
 200     $("#sidebar .sidebar-close-controls button").on("click", closeButtonListener);
 
 202     $("#map").on("dragend dragover", function (e) {
 
 206     $("#map").on("drop", function (e) {
 
 208       const oe = e.originalEvent;
 
 209       const dragData = JSON.parse(oe.dataTransfer.getData("text"));
 
 210       const type = dragData.type;
 
 211       const pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
 
 213       const ll = map.containerPointToLatLng(pt);
 
 214       const llWithPrecision = OSM.cropLocation(ll, map.getZoom());
 
 215       endpoints[type === "from" ? 0 : 1].setValue(llWithPrecision.join(", "));
 
 218     map.on("locationfound", sendstartinglocation);
 
 220     endpoints[0].enableListeners();
 
 221     endpoints[1].enableListeners();
 
 226   function sidebarLoaded() {
 
 227     if ($("#directions_route").length) {
 
 228       sidebarReadyPromise = null;
 
 229       return Promise.resolve();
 
 231     if (sidebarReadyPromise) return sidebarReadyPromise;
 
 232     sidebarReadyPromise = new Promise(resolve => OSM.loadSidebarContent("/directions", resolve));
 
 233     return sidebarReadyPromise;
 
 236   page.pushstate = page.popstate = page.load = function () {
 
 237     initializeFromParams();
 
 239     $(".search_form").hide();
 
 240     $(".directions_form").show();
 
 242     sidebarLoaded().then(enableListeners);
 
 244     map.setSidebarOverlaid(!endpoints[0].latlng || !endpoints[1].latlng);
 
 247   page.unload = function () {
 
 248     $(".search_form").show();
 
 249     $(".directions_form").hide();
 
 251     $("#sidebar .sidebar-close-controls button").off("click", closeButtonListener);
 
 252     $("#map").off("dragend dragover drop");
 
 253     map.off("locationfound", sendstartinglocation);
 
 255     endpoints[0].disableListeners();
 
 256     endpoints[1].disableListeners();
 
 258     endpoints[0].clearValue();
 
 259     endpoints[1].clearValue();
 
 261     routeOutput.remove();
 
 263     sidebarReadyPromise = null;
 
 269 OSM.Directions.engines = [];
 
 271 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
 
 272   if (location.protocol === "http:" || supportsHTTPS) {
 
 273     engine.id = engine.provider + "_" + engine.mode;
 
 274     OSM.Directions.engines.push(engine);