]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/directions.js
Split directions engine select into modes and providers
[rails.git] / app / assets / javascripts / index / directions.js
1 //= require ./directions-endpoint
2 //= require_self
3 //= require_tree ./directions
4
5 OSM.Directions = function (map) {
6   let controller = null; // the AbortController for the current route request if a route request is in progress
7   let chosenEngine;
8
9   const popup = L.popup({ autoPanPadding: [100, 100] });
10
11   const polyline = L.polyline([], {
12     color: "#03f",
13     opacity: 0.3,
14     weight: 10
15   });
16
17   const highlight = L.polyline([], {
18     color: "#ff0",
19     opacity: 0.5,
20     weight: 12
21   });
22
23   const endpointDragCallback = function (dragging) {
24     if (!map.hasLayer(polyline)) return;
25     if (dragging && !chosenEngine.draggable) return;
26     if (dragging && controller) return;
27
28     getRoute(false, !dragging);
29   };
30   const endpointChangeCallback = function () {
31     getRoute(true, true);
32   };
33
34   const endpoints = [
35     OSM.DirectionsEndpoint(map, $("input[name='route_from']"), OSM.MARKER_GREEN, endpointDragCallback, endpointChangeCallback),
36     OSM.DirectionsEndpoint(map, $("input[name='route_to']"), OSM.MARKER_RED, endpointDragCallback, endpointChangeCallback)
37   ];
38
39   let downloadURL = null;
40
41   const expiry = new Date();
42   expiry.setYear(expiry.getFullYear() + 10);
43
44   const modeGroup = $(".routing_modes");
45   const select = $("select.routing_engines");
46
47   $(".directions_form .reverse_directions").on("click", function () {
48     const coordFrom = endpoints[0].latlng,
49           coordTo = endpoints[1].latlng;
50     let routeFrom = "",
51         routeTo = "";
52     if (coordFrom) {
53       routeFrom = coordFrom.lat + "," + coordFrom.lng;
54     }
55     if (coordTo) {
56       routeTo = coordTo.lat + "," + coordTo.lng;
57     }
58     endpoints[0].swapCachedReverseGeocodes(endpoints[1]);
59
60     OSM.router.route("/directions?" + new URLSearchParams({
61       route: routeTo + ";" + routeFrom
62     }));
63   });
64
65   $(".directions_form .btn-close").on("click", function (e) {
66     e.preventDefault();
67     $(".describe_location").toggle(!endpoints[1].value);
68     $(".search_form input[name='query']").val(endpoints[1].value);
69     OSM.router.route("/" + OSM.formatHash(map));
70   });
71
72   function formatDistance(m) {
73     const unitTemplate = "javascripts.directions.distance_";
74     if (m < 1000) return I18n.t(unitTemplate + "m", { distance: Math.round(m) });
75     if (m < 10000) return I18n.t(unitTemplate + "km", { distance: (m / 1000.0).toFixed(1) });
76     return I18n.t(unitTemplate + "km", { distance: Math.round(m / 1000) });
77   }
78
79   function formatHeight(m) {
80     return I18n.t("javascripts.directions.distance_m", { distance: Math.round(m) });
81   }
82
83   function formatTime(s) {
84     let m = Math.round(s / 60);
85     const h = Math.floor(m / 60);
86     m -= h * 60;
87     return h + ":" + (m < 10 ? "0" : "") + m;
88   }
89
90   function setEngine(id) {
91     const engines = OSM.Directions.engines;
92     const desired = engines.find(engine => engine.id === id);
93     if (!desired || (chosenEngine && chosenEngine.id === id)) return;
94     chosenEngine = desired;
95
96     const modes = engines
97       .filter(engine => engine.provider === chosenEngine.provider)
98       .map(engine => engine.mode);
99     modeGroup
100       .find("input[id]")
101       .prop("disabled", function () {
102         return !modes.includes(this.id);
103       })
104       .prop("checked", function () {
105         return this.id === chosenEngine.mode;
106       });
107
108     const providers = engines
109       .filter(engine => engine.mode === chosenEngine.mode)
110       .map(engine => engine.provider);
111     select
112       .find("option[value]")
113       .prop("disabled", function () {
114         return !providers.includes(this.value);
115       });
116     select.val(chosenEngine.provider);
117   }
118
119   function getRoute(fitRoute, reportErrors) {
120     // Cancel any route that is already in progress
121     if (controller) controller.abort();
122
123     const points = endpoints.map(p => p.latlng);
124
125     if (!points[0] || !points[1]) return;
126     $("header").addClass("closed");
127
128     OSM.router.replace("/directions?" + new URLSearchParams({
129       engine: chosenEngine.id,
130       route: points.map(p => OSM.cropLocation(p, map.getZoom()).join()).join(";")
131     }));
132
133     // copy loading item to sidebar and display it. we copy it, rather than
134     // just using it in-place and replacing it in case it has to be used
135     // again.
136     $("#sidebar_content").html($(".directions_form .loader_copy").html());
137     map.setSidebarOverlaid(false);
138     controller = new AbortController();
139     chosenEngine.getRoute(points, controller.signal).then(function (route) {
140       polyline
141         .setLatLngs(route.line)
142         .addTo(map);
143
144       if (fitRoute) {
145         map.fitBounds(polyline.getBounds().pad(0.05));
146       }
147
148       const distanceText = $("<p>").append(
149         I18n.t("javascripts.directions.distance") + ": " + formatDistance(route.distance) + ". " +
150         I18n.t("javascripts.directions.time") + ": " + formatTime(route.time) + ".");
151       if (typeof route.ascend !== "undefined" && typeof route.descend !== "undefined") {
152         distanceText.append(
153           $("<br>"),
154           I18n.t("javascripts.directions.ascend") + ": " + formatHeight(route.ascend) + ". " +
155           I18n.t("javascripts.directions.descend") + ": " + formatHeight(route.descend) + ".");
156       }
157
158       const turnByTurnTable = $("<table class='table table-hover table-sm mb-3'>")
159         .append($("<tbody>"));
160       const directionsCloseButton = $("<button type='button' class='btn-close'>")
161         .attr("aria-label", I18n.t("javascripts.close"));
162
163       $("#sidebar_content")
164         .empty()
165         .append(
166           $("<div class='d-flex'>").append(
167             $("<h2 class='flex-grow-1 text-break'>")
168               .text(I18n.t("javascripts.directions.directions")),
169             $("<div>").append(directionsCloseButton)),
170           distanceText,
171           turnByTurnTable
172         );
173
174       // Add each row
175       route.steps.forEach(function (step) {
176         const [ll, direction, instruction, dist, lineseg] = step;
177
178         const row = $("<tr class='turn'/>");
179         row.append("<td class='border-0'><div class='direction i" + direction + "'/></td> ");
180         row.append("<td>" + instruction);
181         row.append("<td class='distance text-body-secondary text-end'>" + getDistText(dist));
182
183         row.on("click", function () {
184           popup
185             .setLatLng(ll)
186             .setContent("<p>" + instruction + "</p>")
187             .openOn(map);
188         });
189
190         row.hover(function () {
191           highlight
192             .setLatLngs(lineseg)
193             .addTo(map);
194         }, function () {
195           map.removeLayer(highlight);
196         });
197
198         turnByTurnTable.append(row);
199       });
200
201       const blob = new Blob([JSON.stringify(polyline.toGeoJSON())], { type: "application/json" });
202       URL.revokeObjectURL(downloadURL);
203       downloadURL = URL.createObjectURL(blob);
204
205       $("#sidebar_content").append(`<p class="text-center"><a href="${downloadURL}" download="${
206         I18n.t("javascripts.directions.filename")
207       }">${
208         I18n.t("javascripts.directions.download")
209       }</a></p>`);
210
211       $("#sidebar_content").append("<p class=\"text-center\">" +
212         I18n.t("javascripts.directions.instructions.courtesy", { link: chosenEngine.creditline }) +
213         "</p>");
214
215       directionsCloseButton.on("click", function () {
216         map.removeLayer(polyline);
217         $("#sidebar_content").html("");
218         popup.close();
219         map.setSidebarOverlaid(true);
220         // TODO: collapse width of sidebar back to previous
221       });
222     }).catch(function () {
223       map.removeLayer(polyline);
224       if (reportErrors) {
225         $("#sidebar_content").html("<div class=\"alert alert-danger\">" + I18n.t("javascripts.directions.errors.no_route") + "</div>");
226       }
227     }).finally(function () {
228       controller = null;
229     });
230
231     function getDistText(dist) {
232       if (dist < 5) return "";
233       if (dist < 200) return String(Math.round(dist / 10) * 10) + "m";
234       if (dist < 1500) return String(Math.round(dist / 100) * 100) + "m";
235       if (dist < 5000) return String(Math.round(dist / 100) / 10) + "km";
236       return String(Math.round(dist / 1000)) + "km";
237     }
238   }
239
240   setEngine("fossgis_osrm_car");
241   setEngine(Cookies.get("_osm_directions_engine"));
242
243   modeGroup.on("change", "input[name='modes']", function (e) {
244     setEngine(chosenEngine.provider + "_" + e.target.id);
245     Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
246     getRoute(true, true);
247   });
248
249   select.on("change", function (e) {
250     setEngine(e.target.selectedOptions[0].value + "_" + chosenEngine.mode);
251     Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
252     getRoute(true, true);
253   });
254
255   $(".directions_form").on("submit", function (e) {
256     e.preventDefault();
257     getRoute(true, true);
258   });
259
260   $(".routing_marker_column img").on("dragstart", function (e) {
261     const dt = e.originalEvent.dataTransfer;
262     dt.effectAllowed = "move";
263     const dragData = { type: $(this).data("type") };
264     dt.setData("text", JSON.stringify(dragData));
265     if (dt.setDragImage) {
266       const img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
267       dt.setDragImage(img.get(0), 12, 21);
268     }
269   });
270
271   const page = {};
272
273   page.pushstate = page.popstate = function () {
274     $(".search_form").hide();
275     $(".directions_form").show();
276
277     $("#map").on("dragend dragover", function (e) {
278       e.preventDefault();
279     });
280
281     $("#map").on("drop", function (e) {
282       e.preventDefault();
283       const oe = e.originalEvent;
284       const dragData = JSON.parse(oe.dataTransfer.getData("text"));
285       const type = dragData.type;
286       const pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
287       pt.y += 20;
288       const ll = map.containerPointToLatLng(pt);
289       const llWithPrecision = OSM.cropLocation(ll, map.getZoom());
290       endpoints[type === "from" ? 0 : 1].setValue(llWithPrecision.join(", "));
291     });
292
293     endpoints[0].enable();
294     endpoints[1].enable();
295
296     const params = new URLSearchParams(location.search),
297           route = (params.get("route") || "").split(";");
298
299     if (params.has("engine")) setEngine(params.get("engine"));
300
301     endpoints[0].setValue(params.get("from") || route[0] || "");
302     endpoints[1].setValue(params.get("to") || route[1] || "");
303
304     map.setSidebarOverlaid(!endpoints[0].latlng || !endpoints[1].latlng);
305   };
306
307   page.load = function () {
308     page.pushstate();
309   };
310
311   page.unload = function () {
312     $(".search_form").show();
313     $(".directions_form").hide();
314     $("#map").off("dragend dragover drop");
315
316     endpoints[0].disable();
317     endpoints[1].disable();
318
319     map
320       .removeLayer(popup)
321       .removeLayer(polyline);
322   };
323
324   return page;
325 };
326
327 OSM.Directions.engines = [];
328
329 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
330   if (document.location.protocol === "http:" || supportsHTTPS) {
331     engine.id = engine.provider + "_" + engine.mode;
332     OSM.Directions.engines.push(engine);
333   }
334 };