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