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 return a.localeId.localeCompare(b.localeId);
50 const select = $("select.routing_engines");
52 engines.forEach(function (engine, i) {
53 select.append("<option value='" + i + "'>" + engine.localeId + "</option>");
56 $(".directions_form .reverse_directions").on("click", function () {
57 const coordFrom = endpoints[0].latlng,
58 coordTo = endpoints[1].latlng;
62 routeFrom = coordFrom.lat + "," + coordFrom.lng;
65 routeTo = coordTo.lat + "," + coordTo.lng;
67 endpoints[0].swapCachedReverseGeocodes(endpoints[1]);
69 OSM.router.route("/directions?" + new URLSearchParams({
70 route: routeTo + ";" + routeFrom
74 $(".directions_form .btn-close").on("click", function (e) {
76 $(".describe_location").toggle(!endpoints[1].value);
77 $(".search_form input[name='query']").val(endpoints[1].value);
78 OSM.router.route("/" + OSM.formatHash(map));
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) });
88 function formatHeight(m) {
89 return I18n.t("javascripts.directions.distance_m", { distance: Math.round(m) });
92 function formatTime(s) {
93 let m = Math.round(s / 60);
94 const h = Math.floor(m / 60);
96 return h + ":" + (m < 10 ? "0" : "") + m;
99 function setEngine(id) {
100 const index = engines.findIndex(engine => engine.id === id);
101 if (index < 0) return;
102 chosenEngine = engines[index];
106 function getRoute(fitRoute, reportErrors) {
107 // Cancel any route that is already in progress
108 if (controller) controller.abort();
110 const points = endpoints.map(p => p.latlng);
112 if (!points[0] || !points[1]) return;
113 $("header").addClass("closed");
115 OSM.router.replace("/directions?" + new URLSearchParams({
116 engine: chosenEngine.id,
117 route: points.map(p => OSM.cropLocation(p, map.getZoom()).join()).join(";")
120 // copy loading item to sidebar and display it. we copy it, rather than
121 // just using it in-place and replacing it in case it has to be used
123 $("#sidebar_content").html($(".directions_form .loader_copy").html());
124 map.setSidebarOverlaid(false);
125 controller = new AbortController();
126 chosenEngine.getRoute(points, controller.signal).then(function (route) {
128 .setLatLngs(route.line)
132 map.fitBounds(polyline.getBounds().pad(0.05));
135 const distanceText = $("<p>").append(
136 I18n.t("javascripts.directions.distance") + ": " + formatDistance(route.distance) + ". " +
137 I18n.t("javascripts.directions.time") + ": " + formatTime(route.time) + ".");
138 if (typeof route.ascend !== "undefined" && typeof route.descend !== "undefined") {
141 I18n.t("javascripts.directions.ascend") + ": " + formatHeight(route.ascend) + ". " +
142 I18n.t("javascripts.directions.descend") + ": " + formatHeight(route.descend) + ".");
145 const turnByTurnTable = $("<table class='table table-hover table-sm mb-3'>")
146 .append($("<tbody>"));
147 const directionsCloseButton = $("<button type='button' class='btn-close'>")
148 .attr("aria-label", I18n.t("javascripts.close"));
150 $("#sidebar_content")
153 $("<div class='d-flex'>").append(
154 $("<h2 class='flex-grow-1 text-break'>")
155 .text(I18n.t("javascripts.directions.directions")),
156 $("<div>").append(directionsCloseButton)),
162 route.steps.forEach(function (step) {
163 const [ll, direction, instruction, dist, lineseg] = step;
165 const row = $("<tr class='turn'/>");
166 row.append("<td class='border-0'><div class='direction i" + direction + "'/></td> ");
167 row.append("<td>" + instruction);
168 row.append("<td class='distance text-body-secondary text-end'>" + getDistText(dist));
170 row.on("click", function () {
173 .setContent("<p>" + instruction + "</p>")
177 row.hover(function () {
182 map.removeLayer(highlight);
185 turnByTurnTable.append(row);
188 const blob = new Blob([JSON.stringify(polyline.toGeoJSON())], { type: "application/json" });
189 URL.revokeObjectURL(downloadURL);
190 downloadURL = URL.createObjectURL(blob);
192 $("#sidebar_content").append(`<p class="text-center"><a href="${downloadURL}" download="${
193 I18n.t("javascripts.directions.filename")
195 I18n.t("javascripts.directions.download")
198 $("#sidebar_content").append("<p class=\"text-center\">" +
199 I18n.t("javascripts.directions.instructions.courtesy", { link: chosenEngine.creditline }) +
202 directionsCloseButton.on("click", function () {
203 map.removeLayer(polyline);
204 $("#sidebar_content").html("");
206 map.setSidebarOverlaid(true);
207 // TODO: collapse width of sidebar back to previous
209 }).catch(function () {
210 map.removeLayer(polyline);
212 $("#sidebar_content").html("<div class=\"alert alert-danger\">" + I18n.t("javascripts.directions.errors.no_route") + "</div>");
214 }).finally(function () {
218 function getDistText(dist) {
219 if (dist < 5) return "";
220 if (dist < 200) return String(Math.round(dist / 10) * 10) + "m";
221 if (dist < 1500) return String(Math.round(dist / 100) * 100) + "m";
222 if (dist < 5000) return String(Math.round(dist / 100) / 10) + "km";
223 return String(Math.round(dist / 1000)) + "km";
227 setEngine("fossgis_osrm_car");
228 setEngine(Cookies.get("_osm_directions_engine"));
230 select.on("change", function (e) {
231 chosenEngine = engines[e.target.selectedIndex];
232 Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
233 getRoute(true, true);
236 $(".directions_form").on("submit", function (e) {
238 getRoute(true, true);
241 $(".routing_marker_column img").on("dragstart", function (e) {
242 const dt = e.originalEvent.dataTransfer;
243 dt.effectAllowed = "move";
244 const dragData = { type: $(this).data("type") };
245 dt.setData("text", JSON.stringify(dragData));
246 if (dt.setDragImage) {
247 const img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
248 dt.setDragImage(img.get(0), 12, 21);
254 page.pushstate = page.popstate = function () {
255 $(".search_form").hide();
256 $(".directions_form").show();
258 $("#map").on("dragend dragover", function (e) {
262 $("#map").on("drop", function (e) {
264 const oe = e.originalEvent;
265 const dragData = JSON.parse(oe.dataTransfer.getData("text"));
266 const type = dragData.type;
267 const pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
269 const ll = map.containerPointToLatLng(pt);
270 const llWithPrecision = OSM.cropLocation(ll, map.getZoom());
271 endpoints[type === "from" ? 0 : 1].setValue(llWithPrecision.join(", "));
274 endpoints[0].enable();
275 endpoints[1].enable();
277 const params = new URLSearchParams(location.search),
278 route = (params.get("route") || "").split(";");
280 if (params.has("engine")) setEngine(params.get("engine"));
282 endpoints[0].setValue(params.get("from") || route[0] || "");
283 endpoints[1].setValue(params.get("to") || route[1] || "");
285 map.setSidebarOverlaid(!endpoints[0].latlng || !endpoints[1].latlng);
288 page.load = function () {
292 page.unload = function () {
293 $(".search_form").show();
294 $(".directions_form").hide();
295 $("#map").off("dragend dragover drop");
297 endpoints[0].disable();
298 endpoints[1].disable();
302 .removeLayer(polyline);
308 OSM.Directions.engines = [];
310 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
311 if (document.location.protocol === "http:" || supportsHTTPS) {
312 engine.id = engine.provider + "_" + engine.mode;
313 engine.localeId = `${
314 I18n.t("site.search.modes." + engine.mode)
316 I18n.t("site.search.providers." + engine.provider)
318 OSM.Directions.engines.push(engine);