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 modeGroup = $(".routing_modes");
45 const select = $("select.routing_engines");
47 $(".directions_form .reverse_directions").on("click", function () {
48 const coordFrom = endpoints[0].latlng,
49 coordTo = endpoints[1].latlng;
53 routeFrom = coordFrom.lat + "," + coordFrom.lng;
56 routeTo = coordTo.lat + "," + coordTo.lng;
58 endpoints[0].swapCachedReverseGeocodes(endpoints[1]);
60 OSM.router.route("/directions?" + new URLSearchParams({
61 route: routeTo + ";" + routeFrom
65 $(".directions_form .btn-close").on("click", function (e) {
67 $(".describe_location").toggle(!endpoints[1].value);
68 $(".search_form input[name='query']").val(endpoints[1].value);
69 OSM.router.route("/" + OSM.formatHash(map));
72 function formatDistance(m) {
73 const unitTemplate = "javascripts.directions.distance_";
74 if (m < 1000) return I18n.t(unitTemplate + "m", { distance: Math.round(m) });
75 if (m < 10000) return I18n.t(unitTemplate + "km", { distance: (m / 1000.0).toFixed(1) });
76 return I18n.t(unitTemplate + "km", { distance: Math.round(m / 1000) });
79 function formatHeight(m) {
80 return I18n.t("javascripts.directions.distance_m", { distance: Math.round(m) });
83 function formatTime(s) {
84 let m = Math.round(s / 60);
85 const h = Math.floor(m / 60);
87 return h + ":" + (m < 10 ? "0" : "") + m;
90 function setEngine(id) {
91 const engines = OSM.Directions.engines;
92 const desired = engines.find(engine => engine.id === id);
93 if (!desired || (chosenEngine && chosenEngine.id === id)) return;
94 chosenEngine = desired;
97 .filter(engine => engine.provider === chosenEngine.provider)
98 .map(engine => engine.mode);
101 .prop("disabled", function () {
102 return !modes.includes(this.id);
104 .prop("checked", function () {
105 return this.id === chosenEngine.mode;
108 const providers = engines
109 .filter(engine => engine.mode === chosenEngine.mode)
110 .map(engine => engine.provider);
112 .find("option[value]")
113 .prop("disabled", function () {
114 return !providers.includes(this.value);
116 select.val(chosenEngine.provider);
119 function getRoute(fitRoute, reportErrors) {
120 // Cancel any route that is already in progress
121 if (controller) controller.abort();
123 const points = endpoints.map(p => p.latlng);
125 if (!points[0] || !points[1]) return;
126 $("header").addClass("closed");
128 OSM.router.replace("/directions?" + new URLSearchParams({
129 engine: chosenEngine.id,
130 route: points.map(p => OSM.cropLocation(p, map.getZoom()).join()).join(";")
133 // copy loading item to sidebar and display it. we copy it, rather than
134 // just using it in-place and replacing it in case it has to be used
136 $("#sidebar_content").html($(".directions_form .loader_copy").html());
137 map.setSidebarOverlaid(false);
138 controller = new AbortController();
139 chosenEngine.getRoute(points, controller.signal).then(function (route) {
141 .setLatLngs(route.line)
145 map.fitBounds(polyline.getBounds().pad(0.05));
148 const distanceText = $("<p>").append(
149 I18n.t("javascripts.directions.distance") + ": " + formatDistance(route.distance) + ". " +
150 I18n.t("javascripts.directions.time") + ": " + formatTime(route.time) + ".");
151 if (typeof route.ascend !== "undefined" && typeof route.descend !== "undefined") {
154 I18n.t("javascripts.directions.ascend") + ": " + formatHeight(route.ascend) + ". " +
155 I18n.t("javascripts.directions.descend") + ": " + formatHeight(route.descend) + ".");
158 const turnByTurnTable = $("<table class='table table-hover table-sm mb-3'>")
159 .append($("<tbody>"));
160 const directionsCloseButton = $("<button type='button' class='btn-close'>")
161 .attr("aria-label", I18n.t("javascripts.close"));
163 $("#sidebar_content")
166 $("<div class='d-flex'>").append(
167 $("<h2 class='flex-grow-1 text-break'>")
168 .text(I18n.t("javascripts.directions.directions")),
169 $("<div>").append(directionsCloseButton)),
175 route.steps.forEach(function (step) {
176 const [ll, direction, instruction, dist, lineseg] = step;
178 const row = $("<tr class='turn'/>");
179 row.append("<td class='border-0'><div class='direction i" + direction + "'/></td> ");
180 row.append("<td>" + instruction);
181 row.append("<td class='distance text-body-secondary text-end'>" + getDistText(dist));
183 row.on("click", function () {
186 .setContent("<p>" + instruction + "</p>")
190 row.hover(function () {
195 map.removeLayer(highlight);
198 turnByTurnTable.append(row);
201 const blob = new Blob([JSON.stringify(polyline.toGeoJSON())], { type: "application/json" });
202 URL.revokeObjectURL(downloadURL);
203 downloadURL = URL.createObjectURL(blob);
205 $("#sidebar_content").append(`<p class="text-center"><a href="${downloadURL}" download="${
206 I18n.t("javascripts.directions.filename")
208 I18n.t("javascripts.directions.download")
211 $("#sidebar_content").append("<p class=\"text-center\">" +
212 I18n.t("javascripts.directions.instructions.courtesy", { link: chosenEngine.creditline }) +
215 directionsCloseButton.on("click", function () {
216 map.removeLayer(polyline);
217 $("#sidebar_content").html("");
219 map.setSidebarOverlaid(true);
220 // TODO: collapse width of sidebar back to previous
222 }).catch(function () {
223 map.removeLayer(polyline);
225 $("#sidebar_content").html("<div class=\"alert alert-danger\">" + I18n.t("javascripts.directions.errors.no_route") + "</div>");
227 }).finally(function () {
231 function getDistText(dist) {
232 if (dist < 5) return "";
233 if (dist < 200) return String(Math.round(dist / 10) * 10) + "m";
234 if (dist < 1500) return String(Math.round(dist / 100) * 100) + "m";
235 if (dist < 5000) return String(Math.round(dist / 100) / 10) + "km";
236 return String(Math.round(dist / 1000)) + "km";
240 setEngine("fossgis_osrm_car");
241 setEngine(Cookies.get("_osm_directions_engine"));
243 modeGroup.on("change", "input[name='modes']", function (e) {
244 setEngine(chosenEngine.provider + "_" + e.target.id);
245 Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
246 getRoute(true, true);
249 select.on("change", function (e) {
250 setEngine(e.target.selectedOptions[0].value + "_" + chosenEngine.mode);
251 Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
252 getRoute(true, true);
255 $(".directions_form").on("submit", function (e) {
257 getRoute(true, true);
260 $(".routing_marker_column img").on("dragstart", function (e) {
261 const dt = e.originalEvent.dataTransfer;
262 dt.effectAllowed = "move";
263 const dragData = { type: $(this).data("type") };
264 dt.setData("text", JSON.stringify(dragData));
265 if (dt.setDragImage) {
266 const img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
267 dt.setDragImage(img.get(0), 12, 21);
273 page.pushstate = page.popstate = function () {
274 $(".search_form").hide();
275 $(".directions_form").show();
277 $("#map").on("dragend dragover", function (e) {
281 $("#map").on("drop", function (e) {
283 const oe = e.originalEvent;
284 const dragData = JSON.parse(oe.dataTransfer.getData("text"));
285 const type = dragData.type;
286 const pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
288 const ll = map.containerPointToLatLng(pt);
289 const llWithPrecision = OSM.cropLocation(ll, map.getZoom());
290 endpoints[type === "from" ? 0 : 1].setValue(llWithPrecision.join(", "));
293 endpoints[0].enable();
294 endpoints[1].enable();
296 const params = new URLSearchParams(location.search),
297 route = (params.get("route") || "").split(";");
299 if (params.has("engine")) setEngine(params.get("engine"));
301 endpoints[0].setValue(params.get("from") || route[0] || "");
302 endpoints[1].setValue(params.get("to") || route[1] || "");
304 map.setSidebarOverlaid(!endpoints[0].latlng || !endpoints[1].latlng);
307 page.load = function () {
311 page.unload = function () {
312 $(".search_form").show();
313 $(".directions_form").hide();
314 $("#map").off("dragend dragover drop");
316 endpoints[0].disable();
317 endpoints[1].disable();
321 .removeLayer(polyline);
327 OSM.Directions.engines = [];
329 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
330 if (document.location.protocol === "http:" || supportsHTTPS) {
331 engine.id = engine.provider + "_" + engine.mode;
332 OSM.Directions.engines.push(engine);