]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/directions.js
Unify directions page handler and parallelize requests
[rails.git] / app / assets / javascripts / index / directions.js
1 //= require ./directions-endpoint
2 //= require ./directions-route-output
3 //= require_self
4 //= require_tree ./directions
5
6 OSM.Directions = function (map) {
7   let controller = null; // the AbortController for the current route request if a route request is in progress
8   let lastLocation = [];
9   let chosenEngine;
10
11   let sidebarReadyPromise = null;
12
13   const routeOutput = OSM.DirectionsRouteOutput(map);
14
15   const endpointDragCallback = function (dragging) {
16     if (!routeOutput.isVisible()) return;
17     if (dragging && !chosenEngine.draggable) return;
18     if (dragging && controller) return;
19
20     getRoute(false, !dragging);
21   };
22   const endpointChangeCallback = function () {
23     getRoute(true, true);
24   };
25
26   const endpoints = [
27     OSM.DirectionsEndpoint(map, $("input[name='route_from']"), { icon: "MARKER_GREEN" }, endpointDragCallback, endpointChangeCallback),
28     OSM.DirectionsEndpoint(map, $("input[name='route_to']"), { icon: "MARKER_RED" }, endpointDragCallback, endpointChangeCallback)
29   ];
30
31   const expiry = new Date();
32   expiry.setYear(expiry.getFullYear() + 10);
33
34   const modeGroup = $(".routing_modes");
35   const select = $("select.routing_engines");
36
37   $(".directions_form .reverse_directions").on("click", function () {
38     const coordFrom = endpoints[0].latlng,
39           coordTo = endpoints[1].latlng;
40     let routeFrom = "",
41         routeTo = "";
42     if (coordFrom) {
43       routeFrom = coordFrom.lat + "," + coordFrom.lng;
44     }
45     if (coordTo) {
46       routeTo = coordTo.lat + "," + coordTo.lng;
47     }
48     endpoints[0].swapCachedReverseGeocodes(endpoints[1]);
49
50     OSM.router.route("/directions?" + new URLSearchParams({
51       route: routeTo + ";" + routeFrom
52     }));
53   });
54
55   $(".directions_form .btn-close").on("click", function (e) {
56     e.preventDefault();
57     $(".describe_location").toggle(!endpoints[1].value);
58     $(".search_form input[name='query']").val(endpoints[1].value);
59     OSM.router.route("/" + OSM.formatHash(map));
60   });
61
62   function setEngine(id) {
63     const engines = OSM.Directions.engines;
64     const desired = engines.find(engine => engine.id === id);
65     if (!desired || (chosenEngine && chosenEngine.id === id)) return;
66     chosenEngine = desired;
67
68     const modes = engines
69       .filter(engine => engine.provider === chosenEngine.provider)
70       .map(engine => engine.mode);
71     modeGroup
72       .find("input[id]")
73       .prop("disabled", function () {
74         return !modes.includes(this.id);
75       })
76       .prop("checked", function () {
77         return this.id === chosenEngine.mode;
78       });
79
80     const providers = engines
81       .filter(engine => engine.mode === chosenEngine.mode)
82       .map(engine => engine.provider);
83     select
84       .find("option[value]")
85       .prop("disabled", function () {
86         return !providers.includes(this.value);
87       });
88     select.val(chosenEngine.provider);
89   }
90
91   function getRoute(fitRoute, reportErrors) {
92     // Cancel any route that is already in progress
93     if (controller) controller.abort();
94
95     const points = endpoints.map(p => p.latlng);
96
97     if (!points[0] || !points[1]) return;
98     $("header").addClass("closed");
99
100     OSM.router.replace("/directions?" + new URLSearchParams({
101       engine: chosenEngine.id,
102       route: points.map(p => `${p.lat},${p.lng}`).join(";")
103     }));
104
105     // copy loading item to sidebar and display it. we copy it, rather than
106     // just using it in-place and replacing it in case it has to be used
107     // again.
108     $("#directions_content").html($(".directions_form .loader_copy").html());
109     map.setSidebarOverlaid(false);
110     controller = new AbortController();
111     chosenEngine.getRoute(points, controller.signal).then(async function (route) {
112       await sidebarLoaded();
113       routeOutput.write($("#directions_content"), route);
114       if (fitRoute) {
115         routeOutput.fit();
116       }
117     }).catch(async function () {
118       await sidebarLoaded();
119       routeOutput.remove($("#directions_content"));
120       if (reportErrors) {
121         $("#directions_content").html("<div class=\"alert alert-danger\">" + OSM.i18n.t("javascripts.directions.errors.no_route") + "</div>");
122       }
123     }).finally(function () {
124       controller = null;
125     });
126   }
127
128   function closeButtonListener(e) {
129     e.stopPropagation();
130     routeOutput.remove($("#directions_content"));
131     sidebarReadyPromise = null;
132     map.setSidebarOverlaid(true);
133     // TODO: collapse width of sidebar back to previous
134   }
135
136   setEngine("fossgis_osrm_car");
137   setEngine(Cookies.get("_osm_directions_engine"));
138
139   modeGroup.on("change", "input[name='modes']", function (e) {
140     setEngine(chosenEngine.provider + "_" + e.target.id);
141     Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
142     getRoute(true, true);
143   });
144
145   select.on("change", function (e) {
146     setEngine(e.target.value + "_" + chosenEngine.mode);
147     Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
148     getRoute(true, true);
149   });
150
151   $(".directions_form").on("submit", function (e) {
152     e.preventDefault();
153     getRoute(true, true);
154   });
155
156   $(".routing_marker_column img").on("dragstart", function (e) {
157     const dt = e.originalEvent.dataTransfer;
158     dt.effectAllowed = "move";
159     const dragData = { type: $(this).data("type") };
160     dt.setData("text", JSON.stringify(dragData));
161     if (dt.setDragImage) {
162       const img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
163       dt.setDragImage(img.get(0), 12, 21);
164     }
165   });
166
167   function sendstartinglocation({ latlng: { lat, lng } }) {
168     map.fire("startinglocation", { latlng: [lat, lng] });
169   }
170
171   function startingLocationListener({ latlng }) {
172     if (endpoints[0].value) return;
173     endpoints[0].setValue(latlng.join(", "));
174   }
175
176   map.on("locationfound", ({ latlng: { lat, lng } }) =>
177     lastLocation = [lat, lng]
178   ).on("locateactivate", () => {
179     map.once("startinglocation", startingLocationListener);
180   });
181
182   function initializeFromParams() {
183     const params = new URLSearchParams(location.search),
184           route = (params.get("route") || "").split(";");
185
186     if (params.has("engine")) setEngine(params.get("engine"));
187
188     endpoints[0].setValue(params.get("from") || route[0] || lastLocation.join(", "));
189     endpoints[1].setValue(params.get("to") || route[1] || "");
190   }
191
192   function enableListeners() {
193     $("#sidebar .sidebar-close-controls button").on("click", closeButtonListener);
194
195     $("#map").on("dragend dragover", function (e) {
196       e.preventDefault();
197     });
198
199     $("#map").on("drop", function (e) {
200       e.preventDefault();
201       const oe = e.originalEvent;
202       const dragData = JSON.parse(oe.dataTransfer.getData("text"));
203       const type = dragData.type;
204       const pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
205       pt.y += 20;
206       const ll = map.containerPointToLatLng(pt);
207       const llWithPrecision = OSM.cropLocation(ll, map.getZoom());
208       endpoints[type === "from" ? 0 : 1].setValue(llWithPrecision.join(", "));
209     });
210
211     map.on("locationfound", sendstartinglocation);
212
213     endpoints[0].enableListeners();
214     endpoints[1].enableListeners();
215   }
216
217   const page = {};
218
219   function sidebarLoaded() {
220     if ($("#directions_content").length) {
221       sidebarReadyPromise = null;
222       return Promise.resolve();
223     }
224     if (sidebarReadyPromise) return sidebarReadyPromise;
225     sidebarReadyPromise = new Promise(resolve => OSM.loadSidebarContent("/directions", resolve));
226     return sidebarReadyPromise;
227   }
228
229   page.pushstate = page.popstate = page.load = function () {
230     initializeFromParams();
231
232     $(".search_form").hide();
233     $(".directions_form").show();
234
235     sidebarLoaded().then(enableListeners);
236
237     map.setSidebarOverlaid(!endpoints[0].latlng || !endpoints[1].latlng);
238   };
239
240   page.unload = function () {
241     $(".search_form").show();
242     $(".directions_form").hide();
243
244     $("#sidebar .sidebar-close-controls button").off("click", closeButtonListener);
245     $("#map").off("dragend dragover drop");
246     map.off("locationfound", sendstartinglocation);
247
248     endpoints[0].disableListeners();
249     endpoints[1].disableListeners();
250
251     endpoints[0].clearValue();
252     endpoints[1].clearValue();
253
254     routeOutput.remove($("#directions_content"));
255
256     sidebarReadyPromise = null;
257   };
258
259   return page;
260 };
261
262 OSM.Directions.engines = [];
263
264 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
265   if (location.protocol === "http:" || supportsHTTPS) {
266     engine.id = engine.provider + "_" + engine.mode;
267     OSM.Directions.engines.push(engine);
268   }
269 };