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