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