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