]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/directions.js
Replace jquery's getJSON with fetch
[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     $("#sidebar_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       const directionsCloseButton = $("<button type='button' class='btn-close'>")
162         .attr("aria-label", I18n.t("javascripts.close"));
163
164       $("#sidebar_content")
165         .empty()
166         .append(
167           $("<div class='d-flex'>").append(
168             $("<h2 class='flex-grow-1 text-break'>")
169               .text(I18n.t("javascripts.directions.directions")),
170             $("<div>").append(directionsCloseButton)),
171           distanceText,
172           turnByTurnTable
173         );
174
175       // Add each row
176       route.steps.forEach(function (step) {
177         const [ll, direction, instruction, dist, lineseg] = step;
178
179         const row = $("<tr class='turn'/>");
180         row.append("<td class='border-0'><div class='direction i" + direction + "'/></td> ");
181         row.append("<td>" + instruction);
182         row.append("<td class='distance text-body-secondary text-end'>" + getDistText(dist));
183
184         row.on("click", function () {
185           popup
186             .setLatLng(ll)
187             .setContent("<p>" + instruction + "</p>")
188             .openOn(map);
189         });
190
191         row.hover(function () {
192           highlight
193             .setLatLngs(lineseg)
194             .addTo(map);
195         }, function () {
196           map.removeLayer(highlight);
197         });
198
199         turnByTurnTable.append(row);
200       });
201
202       const blob = new Blob([JSON.stringify(polyline.toGeoJSON())], { type: "application/json" });
203       URL.revokeObjectURL(downloadURL);
204       downloadURL = URL.createObjectURL(blob);
205
206       $("#sidebar_content").append(`<p class="text-center"><a href="${downloadURL}" download="${
207         I18n.t("javascripts.directions.filename")
208       }">${
209         I18n.t("javascripts.directions.download")
210       }</a></p>`);
211
212       $("#sidebar_content").append("<p class=\"text-center\">" +
213         I18n.t("javascripts.directions.instructions.courtesy", { link: chosenEngine.creditline }) +
214         "</p>");
215
216       directionsCloseButton.on("click", function () {
217         map.removeLayer(polyline);
218         $("#sidebar_content").html("");
219         popup.close();
220         map.setSidebarOverlaid(true);
221         // TODO: collapse width of sidebar back to previous
222       });
223     }).catch(function () {
224       map.removeLayer(polyline);
225       if (reportErrors) {
226         $("#sidebar_content").html("<div class=\"alert alert-danger\">" + I18n.t("javascripts.directions.errors.no_route") + "</div>");
227       }
228     }).finally(function () {
229       controller = null;
230     });
231
232     function getDistText(dist) {
233       if (dist < 5) return "";
234       if (dist < 200) return String(Math.round(dist / 10) * 10) + "m";
235       if (dist < 1500) return String(Math.round(dist / 100) * 100) + "m";
236       if (dist < 5000) return String(Math.round(dist / 100) / 10) + "km";
237       return String(Math.round(dist / 1000)) + "km";
238     }
239   }
240
241   setEngine("fossgis_osrm_car");
242   setEngine(Cookies.get("_osm_directions_engine"));
243
244   modeGroup.on("change", "input[name='modes']", function (e) {
245     setEngine(chosenEngine.provider + "_" + e.target.id);
246     Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
247     getRoute(true, true);
248   });
249
250   select.on("change", function (e) {
251     setEngine(e.target.selectedOptions[0].value + "_" + chosenEngine.mode);
252     Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
253     getRoute(true, true);
254   });
255
256   $(".directions_form").on("submit", function (e) {
257     e.preventDefault();
258     getRoute(true, true);
259   });
260
261   $(".routing_marker_column img").on("dragstart", function (e) {
262     const dt = e.originalEvent.dataTransfer;
263     dt.effectAllowed = "move";
264     const dragData = { type: $(this).data("type") };
265     dt.setData("text", JSON.stringify(dragData));
266     if (dt.setDragImage) {
267       const img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
268       dt.setDragImage(img.get(0), 12, 21);
269     }
270   });
271
272   function sendstartinglocation({ latlng: { lat, lng } }) {
273     map.fire("startinglocation", { latlng: [lat, lng] });
274   }
275
276   map.on("locationfound", ({ latlng: { lat, lng } }) =>
277     lastLocation = [lat, lng]
278   ).on("locateactivate", () => {
279     map.once("startinglocation", ({ latlng }) => {
280       if (endpoints[0].value) return;
281       endpoints[0].setValue(latlng.join(", "));
282     });
283   });
284
285   const page = {};
286
287   page.pushstate = page.popstate = function () {
288     $(".search_form").hide();
289     $(".directions_form").show();
290
291     $("#map").on("dragend dragover", function (e) {
292       e.preventDefault();
293     });
294
295     $("#map").on("drop", function (e) {
296       e.preventDefault();
297       const oe = e.originalEvent;
298       const dragData = JSON.parse(oe.dataTransfer.getData("text"));
299       const type = dragData.type;
300       const pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
301       pt.y += 20;
302       const ll = map.containerPointToLatLng(pt);
303       const llWithPrecision = OSM.cropLocation(ll, map.getZoom());
304       endpoints[type === "from" ? 0 : 1].setValue(llWithPrecision.join(", "));
305     });
306
307     map.on("locationfound", sendstartinglocation);
308
309     endpoints[0].enable();
310     endpoints[1].enable();
311
312     const params = new URLSearchParams(location.search),
313           route = (params.get("route") || "").split(";");
314
315     if (params.has("engine")) setEngine(params.get("engine"));
316
317     endpoints[0].setValue(params.get("from") || route[0] || lastLocation.join(", "));
318     endpoints[1].setValue(params.get("to") || route[1] || "");
319
320     map.setSidebarOverlaid(!endpoints[0].latlng || !endpoints[1].latlng);
321   };
322
323   page.load = function () {
324     page.pushstate();
325   };
326
327   page.unload = function () {
328     $(".search_form").show();
329     $(".directions_form").hide();
330     $("#map").off("dragend dragover drop");
331     map.off("locationfound", sendstartinglocation);
332
333     endpoints[0].disable();
334     endpoints[1].disable();
335
336     map
337       .removeLayer(popup)
338       .removeLayer(polyline);
339   };
340
341   return page;
342 };
343
344 OSM.Directions.engines = [];
345
346 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
347   if (document.location.protocol === "http:" || supportsHTTPS) {
348     engine.id = engine.provider + "_" + engine.mode;
349     OSM.Directions.engines.push(engine);
350   }
351 };