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