]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/directions.js
Replace qs with URLSearchParams
[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   var routeRequest = null; // jqXHR object of an ongoing route request or null
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 && routeRequest) 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     if (m < 1000) {
83       return I18n.t("javascripts.directions.distance_m", { distance: Math.round(m) });
84     } else if (m < 10000) {
85       return I18n.t("javascripts.directions.distance_km", { distance: (m / 1000.0).toFixed(1) });
86     } else {
87       return I18n.t("javascripts.directions.distance_km", { distance: Math.round(m / 1000) });
88     }
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     var m = Math.round(s / 60);
97     var 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 (routeRequest) routeRequest.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
133     routeRequest = chosenEngine.getRoute(points, function (err, route) {
134       routeRequest = null;
135
136       if (err) {
137         map.removeLayer(polyline);
138
139         if (reportErrors) {
140           $("#sidebar_content").html("<div class=\"alert alert-danger\">" + I18n.t("javascripts.directions.errors.no_route") + "</div>");
141         }
142
143         return;
144       }
145
146       polyline
147         .setLatLngs(route.line)
148         .addTo(map);
149
150       if (fitRoute) {
151         map.fitBounds(polyline.getBounds().pad(0.05));
152       }
153
154       var distanceText = $("<p>").append(
155         I18n.t("javascripts.directions.distance") + ": " + formatDistance(route.distance) + ". " +
156         I18n.t("javascripts.directions.time") + ": " + formatTime(route.time) + ".");
157       if (typeof route.ascend !== "undefined" && typeof route.descend !== "undefined") {
158         distanceText.append(
159           $("<br>"),
160           I18n.t("javascripts.directions.ascend") + ": " + formatHeight(route.ascend) + ". " +
161           I18n.t("javascripts.directions.descend") + ": " + formatHeight(route.descend) + ".");
162       }
163
164       var turnByTurnTable = $("<table class='table table-hover table-sm mb-3'>")
165         .append($("<tbody>"));
166       var directionsCloseButton = $("<button type='button' class='btn-close'>")
167         .attr("aria-label", I18n.t("javascripts.close"));
168
169       $("#sidebar_content")
170         .empty()
171         .append(
172           $("<div class='d-flex'>").append(
173             $("<h2 class='flex-grow-1 text-break'>")
174               .text(I18n.t("javascripts.directions.directions")),
175             $("<div>").append(directionsCloseButton)),
176           distanceText,
177           turnByTurnTable
178         );
179
180       // Add each row
181       route.steps.forEach(function (step) {
182         var ll = step[0],
183             direction = step[1],
184             instruction = step[2],
185             dist = step[3],
186             lineseg = step[4];
187
188         if (dist < 5) {
189           dist = "";
190         } else if (dist < 200) {
191           dist = String(Math.round(dist / 10) * 10) + "m";
192         } else if (dist < 1500) {
193           dist = String(Math.round(dist / 100) * 100) + "m";
194         } else if (dist < 5000) {
195           dist = String(Math.round(dist / 100) / 10) + "km";
196         } else {
197           dist = String(Math.round(dist / 1000)) + "km";
198         }
199
200         var row = $("<tr class='turn'/>");
201         row.append("<td class='border-0'><div class='direction i" + direction + "'/></td> ");
202         row.append("<td>" + instruction);
203         row.append("<td class='distance text-body-secondary text-end'>" + dist);
204
205         row.on("click", function () {
206           popup
207             .setLatLng(ll)
208             .setContent("<p>" + instruction + "</p>")
209             .openOn(map);
210         });
211
212         row.hover(function () {
213           highlight
214             .setLatLngs(lineseg)
215             .addTo(map);
216         }, function () {
217           map.removeLayer(highlight);
218         });
219
220         turnByTurnTable.append(row);
221       });
222
223       $("#sidebar_content").append("<p class=\"text-center\">" +
224         I18n.t("javascripts.directions.instructions.courtesy", { link: chosenEngine.creditline }) +
225         "</p>");
226
227       directionsCloseButton.on("click", function () {
228         map.removeLayer(polyline);
229         $("#sidebar_content").html("");
230         map.setSidebarOverlaid(true);
231         // TODO: collapse width of sidebar back to previous
232       });
233     });
234   }
235
236   var chosenEngineIndex = findEngine("fossgis_osrm_car");
237   if (Cookies.get("_osm_directions_engine")) {
238     chosenEngineIndex = findEngine(Cookies.get("_osm_directions_engine"));
239   }
240   setEngine(chosenEngineIndex);
241
242   select.on("change", function (e) {
243     chosenEngine = engines[e.target.selectedIndex];
244     Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
245     getRoute(true, true);
246   });
247
248   $(".directions_form").on("submit", function (e) {
249     e.preventDefault();
250     getRoute(true, true);
251   });
252
253   $(".routing_marker_column img").on("dragstart", function (e) {
254     var dt = e.originalEvent.dataTransfer;
255     dt.effectAllowed = "move";
256     var dragData = { type: $(this).data("type") };
257     dt.setData("text", JSON.stringify(dragData));
258     if (dt.setDragImage) {
259       var img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
260       dt.setDragImage(img.get(0), 12, 21);
261     }
262   });
263
264   var page = {};
265
266   page.pushstate = page.popstate = function () {
267     $(".search_form").hide();
268     $(".directions_form").show();
269
270     $("#map").on("dragend dragover", function (e) {
271       e.preventDefault();
272     });
273
274     $("#map").on("drop", function (e) {
275       e.preventDefault();
276       var oe = e.originalEvent;
277       var dragData = JSON.parse(oe.dataTransfer.getData("text"));
278       var type = dragData.type;
279       var pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
280       pt.y += 20;
281       var ll = map.containerPointToLatLng(pt);
282       const llWithPrecision = OSM.cropLocation(ll, map.getZoom());
283       endpoints[type === "from" ? 0 : 1].setValue(llWithPrecision.join(", "));
284     });
285
286     endpoints[0].enable();
287     endpoints[1].enable();
288
289     const params = new URLSearchParams(location.search),
290           route = (params.get("route") || "").split(";");
291
292     if (params.has("engine")) {
293       var engineIndex = findEngine(params.get("engine"));
294
295       if (engineIndex >= 0) {
296         setEngine(engineIndex);
297       }
298     }
299
300     endpoints[0].setValue(params.get("from") || route[0] || "");
301     endpoints[1].setValue(params.get("to") || route[1] || "");
302
303     map.setSidebarOverlaid(!endpoints[0].latlng || !endpoints[1].latlng);
304   };
305
306   page.load = function () {
307     page.pushstate();
308   };
309
310   page.unload = function () {
311     $(".search_form").show();
312     $(".directions_form").hide();
313     $("#map").off("dragend dragover drop");
314
315     endpoints[0].disable();
316     endpoints[1].disable();
317
318     map
319       .removeLayer(popup)
320       .removeLayer(polyline);
321   };
322
323   return page;
324 };
325
326 OSM.Directions.engines = [];
327
328 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
329   if (document.location.protocol === "http:" || supportsHTTPS) {
330     OSM.Directions.engines.push(engine);
331   }
332 };