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