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