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