1 //= require ./directions-endpoint
3 //= require_tree ./directions
5 OSM.Directions = function (map) {
6 let controller = null; // the AbortController for the current route request if a route request is in progress
9 const popup = L.popup({ autoPanPadding: [100, 100] });
11 const polyline = L.polyline([], {
17 const highlight = L.polyline([], {
23 const endpointDragCallback = function (dragging) {
24 if (!map.hasLayer(polyline)) return;
25 if (dragging && !chosenEngine.draggable) return;
26 if (dragging && controller) return;
28 getRoute(false, !dragging);
30 const endpointChangeCallback = function () {
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)
39 let downloadURL = null;
41 const expiry = new Date();
42 expiry.setYear(expiry.getFullYear() + 10);
44 const engines = OSM.Directions.engines;
46 engines.sort(function (a, b) {
47 const localised_a = I18n.t("javascripts.directions.engines." + a.id),
48 localised_b = I18n.t("javascripts.directions.engines." + b.id);
49 return localised_a.localeCompare(localised_b);
52 const select = $("select.routing_engines");
54 engines.forEach(function (engine, i) {
55 select.append("<option value='" + i + "'>" + I18n.t("javascripts.directions.engines." + engine.id) + "</option>");
58 $(".directions_form .reverse_directions").on("click", function () {
59 const coordFrom = endpoints[0].latlng,
60 coordTo = endpoints[1].latlng;
64 routeFrom = coordFrom.lat + "," + coordFrom.lng;
67 routeTo = coordTo.lat + "," + coordTo.lng;
69 endpoints[0].swapCachedReverseGeocodes(endpoints[1]);
71 OSM.router.route("/directions?" + new URLSearchParams({
72 route: routeTo + ";" + routeFrom
76 $(".directions_form .btn-close").on("click", function (e) {
78 $(".describe_location").toggle(!endpoints[1].value);
79 $(".search_form input[name='query']").val(endpoints[1].value);
80 OSM.router.route("/" + OSM.formatHash(map));
83 function formatDistance(m) {
84 const unitTemplate = "javascripts.directions.distance_";
85 if (m < 1000) return I18n.t(unitTemplate + "m", { distance: Math.round(m) });
86 if (m < 10000) return I18n.t(unitTemplate + "km", { distance: (m / 1000.0).toFixed(1) });
87 return I18n.t(unitTemplate + "km", { distance: Math.round(m / 1000) });
90 function formatHeight(m) {
91 return I18n.t("javascripts.directions.distance_m", { distance: Math.round(m) });
94 function formatTime(s) {
95 let m = Math.round(s / 60);
96 const h = Math.floor(m / 60);
98 return h + ":" + (m < 10 ? "0" : "") + m;
101 function findEngine(id) {
102 return engines.findIndex(function (engine) {
103 return engine.id === id;
107 function setEngine(index) {
108 chosenEngine = engines[index];
112 function getRoute(fitRoute, reportErrors) {
113 // Cancel any route that is already in progress
114 if (controller) controller.abort();
116 const points = endpoints.map(p => p.latlng);
118 if (!points[0] || !points[1]) return;
119 $("header").addClass("closed");
121 OSM.router.replace("/directions?" + new URLSearchParams({
122 engine: chosenEngine.id,
123 route: points.map(p => OSM.cropLocation(p, map.getZoom()).join()).join(";")
126 // copy loading item to sidebar and display it. we copy it, rather than
127 // just using it in-place and replacing it in case it has to be used
129 $("#sidebar_content").html($(".directions_form .loader_copy").html());
130 map.setSidebarOverlaid(false);
131 controller = new AbortController();
132 chosenEngine.getRoute(points, controller.signal).then(function (route) {
134 .setLatLngs(route.line)
138 map.fitBounds(polyline.getBounds().pad(0.05));
141 const distanceText = $("<p>").append(
142 I18n.t("javascripts.directions.distance") + ": " + formatDistance(route.distance) + ". " +
143 I18n.t("javascripts.directions.time") + ": " + formatTime(route.time) + ".");
144 if (typeof route.ascend !== "undefined" && typeof route.descend !== "undefined") {
147 I18n.t("javascripts.directions.ascend") + ": " + formatHeight(route.ascend) + ". " +
148 I18n.t("javascripts.directions.descend") + ": " + formatHeight(route.descend) + ".");
151 const turnByTurnTable = $("<table class='table table-hover table-sm mb-3'>")
152 .append($("<tbody>"));
153 const directionsCloseButton = $("<button type='button' class='btn-close'>")
154 .attr("aria-label", I18n.t("javascripts.close"));
156 $("#sidebar_content")
159 $("<div class='d-flex'>").append(
160 $("<h2 class='flex-grow-1 text-break'>")
161 .text(I18n.t("javascripts.directions.directions")),
162 $("<div>").append(directionsCloseButton)),
168 route.steps.forEach(function (step) {
169 const [ll, direction, instruction, dist, lineseg] = step;
171 const row = $("<tr class='turn'/>");
172 row.append("<td class='border-0'><div class='direction i" + direction + "'/></td> ");
173 row.append("<td>" + instruction);
174 row.append("<td class='distance text-body-secondary text-end'>" + getDistText(dist));
176 row.on("click", function () {
179 .setContent("<p>" + instruction + "</p>")
183 row.hover(function () {
188 map.removeLayer(highlight);
191 turnByTurnTable.append(row);
194 const blob = new Blob([JSON.stringify(polyline.toGeoJSON())], { type: "application/json" });
195 URL.revokeObjectURL(downloadURL);
196 downloadURL = URL.createObjectURL(blob);
198 $("#sidebar_content").append(`<p class="text-center"><a href="${downloadURL}" download="${
199 I18n.t("javascripts.directions.filename")
201 I18n.t("javascripts.directions.download")
204 $("#sidebar_content").append("<p class=\"text-center\">" +
205 I18n.t("javascripts.directions.instructions.courtesy", { link: chosenEngine.creditline }) +
208 directionsCloseButton.on("click", function () {
209 map.removeLayer(polyline);
210 $("#sidebar_content").html("");
212 map.setSidebarOverlaid(true);
213 // TODO: collapse width of sidebar back to previous
215 }).catch(function () {
216 map.removeLayer(polyline);
218 $("#sidebar_content").html("<div class=\"alert alert-danger\">" + I18n.t("javascripts.directions.errors.no_route") + "</div>");
220 }).finally(function () {
224 function getDistText(dist) {
225 if (dist < 5) return "";
226 if (dist < 200) return String(Math.round(dist / 10) * 10) + "m";
227 if (dist < 1500) return String(Math.round(dist / 100) * 100) + "m";
228 if (dist < 5000) return String(Math.round(dist / 100) / 10) + "km";
229 return String(Math.round(dist / 1000)) + "km";
233 let chosenEngineIndex = findEngine("fossgis_osrm_car");
234 if (Cookies.get("_osm_directions_engine")) {
235 chosenEngineIndex = findEngine(Cookies.get("_osm_directions_engine"));
237 setEngine(chosenEngineIndex);
239 select.on("change", function (e) {
240 chosenEngine = engines[e.target.selectedIndex];
241 Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
242 getRoute(true, true);
245 $(".directions_form").on("submit", function (e) {
247 getRoute(true, true);
250 $(".routing_marker_column img").on("dragstart", function (e) {
251 const dt = e.originalEvent.dataTransfer;
252 dt.effectAllowed = "move";
253 const dragData = { type: $(this).data("type") };
254 dt.setData("text", JSON.stringify(dragData));
255 if (dt.setDragImage) {
256 const img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
257 dt.setDragImage(img.get(0), 12, 21);
263 page.pushstate = page.popstate = function () {
264 $(".search_form").hide();
265 $(".directions_form").show();
267 $("#map").on("dragend dragover", function (e) {
271 $("#map").on("drop", function (e) {
273 const oe = e.originalEvent;
274 const dragData = JSON.parse(oe.dataTransfer.getData("text"));
275 const type = dragData.type;
276 const pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
278 const ll = map.containerPointToLatLng(pt);
279 const llWithPrecision = OSM.cropLocation(ll, map.getZoom());
280 endpoints[type === "from" ? 0 : 1].setValue(llWithPrecision.join(", "));
283 endpoints[0].enable();
284 endpoints[1].enable();
286 const params = new URLSearchParams(location.search),
287 route = (params.get("route") || "").split(";");
289 if (params.has("engine")) {
290 const engineIndex = findEngine(params.get("engine"));
292 if (engineIndex >= 0) {
293 setEngine(engineIndex);
297 endpoints[0].setValue(params.get("from") || route[0] || "");
298 endpoints[1].setValue(params.get("to") || route[1] || "");
300 map.setSidebarOverlaid(!endpoints[0].latlng || !endpoints[1].latlng);
303 page.load = function () {
307 page.unload = function () {
308 $(".search_form").show();
309 $(".directions_form").hide();
310 $("#map").off("dragend dragover drop");
312 endpoints[0].disable();
313 endpoints[1].disable();
317 .removeLayer(polyline);
323 OSM.Directions.engines = [];
325 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
326 if (document.location.protocol === "http:" || supportsHTTPS) {
327 OSM.Directions.engines.push(engine);