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