]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/directions.js
Merge branch 'pull/5594'
[rails.git] / app / assets / javascripts / index / directions.js
1 //= require ./directions-endpoint
2 //= require_self
3 //= require_tree ./directions
4 //= require qs/dist/qs
5
6 OSM.Directions = function (map) {
7   var routeRequest = null; // jqXHR object of an ongoing route request or null
8   var chosenEngine;
9
10   var popup = L.popup({ autoPanPadding: [100, 100] });
11
12   var polyline = L.polyline([], {
13     color: "#03f",
14     opacity: 0.3,
15     weight: 10
16   });
17
18   var highlight = L.polyline([], {
19     color: "#ff0",
20     opacity: 0.5,
21     weight: 12
22   });
23
24   var endpointDragCallback = function (dragging) {
25     if (!map.hasLayer(polyline)) return;
26     if (dragging && !chosenEngine.draggable) return;
27     if (dragging && routeRequest) return;
28
29     getRoute(false, !dragging);
30   };
31   var endpointChangeCallback = function () {
32     getRoute(true, true);
33   };
34
35   var 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   var expiry = new Date();
41   expiry.setYear(expiry.getFullYear() + 10);
42
43   var engines = OSM.Directions.engines;
44
45   engines.sort(function (a, b) {
46     var localised_a = I18n.t("javascripts.directions.engines." + a.id),
47         localised_b = I18n.t("javascripts.directions.engines." + b.id);
48     return localised_a.localeCompare(localised_b);
49   });
50
51   var select = $("select.routing_engines");
52
53   engines.forEach(function (engine, i) {
54     select.append("<option value='" + i + "'>" + I18n.t("javascripts.directions.engines." + engine.id) + "</option>");
55   });
56
57   $(".directions_form .reverse_directions").on("click", function () {
58     var coordFrom = endpoints[0].latlng,
59         coordTo = endpoints[1].latlng,
60         routeFrom = "",
61         routeTo = "";
62     if (coordFrom) {
63       routeFrom = coordFrom.lat + "," + coordFrom.lng;
64     }
65     if (coordTo) {
66       routeTo = coordTo.lat + "," + coordTo.lng;
67     }
68     endpoints[0].swapCachedReverseGeocodes(endpoints[1]);
69
70     OSM.router.route("/directions?" + Qs.stringify({
71       route: routeTo + ";" + routeFrom
72     }));
73   });
74
75   $(".directions_form .btn-close").on("click", function (e) {
76     e.preventDefault();
77     $(".describe_location").toggle(!endpoints[0].value);
78     $(".search_form input[name='query']").val(endpoints[0].value);
79     OSM.router.route("/" + OSM.formatHash(map));
80   });
81
82   function formatDistance(m) {
83     if (m < 1000) {
84       return I18n.t("javascripts.directions.distance_m", { distance: Math.round(m) });
85     } else if (m < 10000) {
86       return I18n.t("javascripts.directions.distance_km", { distance: (m / 1000.0).toFixed(1) });
87     } else {
88       return I18n.t("javascripts.directions.distance_km", { distance: Math.round(m / 1000) });
89     }
90   }
91
92   function formatHeight(m) {
93     return I18n.t("javascripts.directions.distance_m", { distance: Math.round(m) });
94   }
95
96   function formatTime(s) {
97     var m = Math.round(s / 60);
98     var h = Math.floor(m / 60);
99     m -= h * 60;
100     return h + ":" + (m < 10 ? "0" : "") + m;
101   }
102
103   function findEngine(id) {
104     return engines.findIndex(function (engine) {
105       return engine.id === id;
106     });
107   }
108
109   function setEngine(index) {
110     chosenEngine = engines[index];
111     select.val(index);
112   }
113
114   function getRoute(fitRoute, reportErrors) {
115     // Cancel any route that is already in progress
116     if (routeRequest) routeRequest.abort();
117
118     const points = endpoints.map(p => p.latlng);
119
120     if (!points[0] || !points[1]) return;
121     $("header").addClass("closed");
122
123     OSM.router.replace("/directions?" + Qs.stringify({
124       engine: chosenEngine.id,
125       route: points.map(p => OSM.cropLocation(p, map.getZoom()).join()).join(";")
126     }));
127
128     // copy loading item to sidebar and display it. we copy it, rather than
129     // just using it in-place and replacing it in case it has to be used
130     // again.
131     $("#sidebar_content").html($(".directions_form .loader_copy").html());
132     map.setSidebarOverlaid(false);
133
134     routeRequest = chosenEngine.getRoute(points, function (err, route) {
135       routeRequest = null;
136
137       if (err) {
138         map.removeLayer(polyline);
139
140         if (reportErrors) {
141           $("#sidebar_content").html("<div class=\"alert alert-danger\">" + I18n.t("javascripts.directions.errors.no_route") + "</div>");
142         }
143
144         return;
145       }
146
147       polyline
148         .setLatLngs(route.line)
149         .addTo(map);
150
151       if (fitRoute) {
152         map.fitBounds(polyline.getBounds().pad(0.05));
153       }
154
155       var distanceText = $("<p>").append(
156         I18n.t("javascripts.directions.distance") + ": " + formatDistance(route.distance) + ". " +
157         I18n.t("javascripts.directions.time") + ": " + formatTime(route.time) + ".");
158       if (typeof route.ascend !== "undefined" && typeof route.descend !== "undefined") {
159         distanceText.append(
160           $("<br>"),
161           I18n.t("javascripts.directions.ascend") + ": " + formatHeight(route.ascend) + ". " +
162           I18n.t("javascripts.directions.descend") + ": " + formatHeight(route.descend) + ".");
163       }
164
165       var turnByTurnTable = $("<table class='table table-hover table-sm mb-3'>")
166         .append($("<tbody>"));
167       var directionsCloseButton = $("<button type='button' class='btn-close'>")
168         .attr("aria-label", I18n.t("javascripts.close"));
169
170       $("#sidebar_content")
171         .empty()
172         .append(
173           $("<div class='d-flex'>").append(
174             $("<h2 class='flex-grow-1 text-break'>")
175               .text(I18n.t("javascripts.directions.directions")),
176             $("<div>").append(directionsCloseButton)),
177           distanceText,
178           turnByTurnTable
179         );
180
181       // Add each row
182       route.steps.forEach(function (step) {
183         var ll = step[0],
184             direction = step[1],
185             instruction = step[2],
186             dist = step[3],
187             lineseg = step[4];
188
189         if (dist < 5) {
190           dist = "";
191         } else if (dist < 200) {
192           dist = String(Math.round(dist / 10) * 10) + "m";
193         } else if (dist < 1500) {
194           dist = String(Math.round(dist / 100) * 100) + "m";
195         } else if (dist < 5000) {
196           dist = String(Math.round(dist / 100) / 10) + "km";
197         } else {
198           dist = String(Math.round(dist / 1000)) + "km";
199         }
200
201         var row = $("<tr class='turn'/>");
202         row.append("<td class='border-0'><div class='direction i" + direction + "'/></td> ");
203         row.append("<td>" + instruction);
204         row.append("<td class='distance text-body-secondary text-end'>" + dist);
205
206         row.on("click", function () {
207           popup
208             .setLatLng(ll)
209             .setContent("<p>" + instruction + "</p>")
210             .openOn(map);
211         });
212
213         row.hover(function () {
214           highlight
215             .setLatLngs(lineseg)
216             .addTo(map);
217         }, function () {
218           map.removeLayer(highlight);
219         });
220
221         turnByTurnTable.append(row);
222       });
223
224       $("#sidebar_content").append("<p class=\"text-center\">" +
225         I18n.t("javascripts.directions.instructions.courtesy", { link: chosenEngine.creditline }) +
226         "</p>");
227
228       directionsCloseButton.on("click", function () {
229         map.removeLayer(polyline);
230         $("#sidebar_content").html("");
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     var params = Qs.parse(location.search.substring(1)),
291         route = (params.route || "").split(";");
292
293     if (params.engine) {
294       var engineIndex = findEngine(params.engine);
295
296       if (engineIndex >= 0) {
297         setEngine(engineIndex);
298       }
299     }
300
301     endpoints[0].setValue(params.from || route[0] || "");
302     endpoints[1].setValue(params.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 };