]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/directions.js
Merge branch 'pull/5627'
[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         popup.close();
231         map.setSidebarOverlaid(true);
232         // TODO: collapse width of sidebar back to previous
233       });
234     });
235   }
236
237   var chosenEngineIndex = findEngine("fossgis_osrm_car");
238   if (Cookies.get("_osm_directions_engine")) {
239     chosenEngineIndex = findEngine(Cookies.get("_osm_directions_engine"));
240   }
241   setEngine(chosenEngineIndex);
242
243   select.on("change", function (e) {
244     chosenEngine = engines[e.target.selectedIndex];
245     Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
246     getRoute(true, true);
247   });
248
249   $(".directions_form").on("submit", function (e) {
250     e.preventDefault();
251     getRoute(true, true);
252   });
253
254   $(".routing_marker_column img").on("dragstart", function (e) {
255     var dt = e.originalEvent.dataTransfer;
256     dt.effectAllowed = "move";
257     var dragData = { type: $(this).data("type") };
258     dt.setData("text", JSON.stringify(dragData));
259     if (dt.setDragImage) {
260       var img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
261       dt.setDragImage(img.get(0), 12, 21);
262     }
263   });
264
265   var page = {};
266
267   page.pushstate = page.popstate = function () {
268     $(".search_form").hide();
269     $(".directions_form").show();
270
271     $("#map").on("dragend dragover", function (e) {
272       e.preventDefault();
273     });
274
275     $("#map").on("drop", function (e) {
276       e.preventDefault();
277       var oe = e.originalEvent;
278       var dragData = JSON.parse(oe.dataTransfer.getData("text"));
279       var type = dragData.type;
280       var pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
281       pt.y += 20;
282       var ll = map.containerPointToLatLng(pt);
283       const llWithPrecision = OSM.cropLocation(ll, map.getZoom());
284       endpoints[type === "from" ? 0 : 1].setValue(llWithPrecision.join(", "));
285     });
286
287     endpoints[0].enable();
288     endpoints[1].enable();
289
290     const params = new URLSearchParams(location.search),
291           route = (params.get("route") || "").split(";");
292
293     if (params.has("engine")) {
294       var engineIndex = findEngine(params.get("engine"));
295
296       if (engineIndex >= 0) {
297         setEngine(engineIndex);
298       }
299     }
300
301     endpoints[0].setValue(params.get("from") || route[0] || "");
302     endpoints[1].setValue(params.get("to") || route[1] || "");
303
304     map.setSidebarOverlaid(!endpoints[0].latlng || !endpoints[1].latlng);
305   };
306
307   page.load = function () {
308     page.pushstate();
309   };
310
311   page.unload = function () {
312     $(".search_form").show();
313     $(".directions_form").hide();
314     $("#map").off("dragend dragover drop");
315
316     endpoints[0].disable();
317     endpoints[1].disable();
318
319     map
320       .removeLayer(popup)
321       .removeLayer(polyline);
322   };
323
324   return page;
325 };
326
327 OSM.Directions.engines = [];
328
329 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
330   if (document.location.protocol === "http:" || supportsHTTPS) {
331     OSM.Directions.engines.push(engine);
332   }
333 };