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
10 const popup = L.popup({ autoPanPadding: [100, 100] });
12 const polyline = L.polyline([], {
18 const highlight = L.polyline([], {
24 const endpointDragCallback = function (dragging) {
25 if (!map.hasLayer(polyline)) return;
26 if (dragging && !chosenEngine.draggable) return;
27 if (dragging && controller) return;
29 getRoute(false, !dragging);
31 const endpointChangeCallback = function () {
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)
40 let downloadURL = null;
42 const expiry = new Date();
43 expiry.setYear(expiry.getFullYear() + 10);
45 const modeGroup = $(".routing_modes");
46 const select = $("select.routing_engines");
48 $(".directions_form .reverse_directions").on("click", function () {
49 const coordFrom = endpoints[0].latlng,
50 coordTo = endpoints[1].latlng;
54 routeFrom = coordFrom.lat + "," + coordFrom.lng;
57 routeTo = coordTo.lat + "," + coordTo.lng;
59 endpoints[0].swapCachedReverseGeocodes(endpoints[1]);
61 OSM.router.route("/directions?" + new URLSearchParams({
62 route: routeTo + ";" + routeFrom
66 $(".directions_form .btn-close").on("click", function (e) {
68 $(".describe_location").toggle(!endpoints[1].value);
69 $(".search_form input[name='query']").val(endpoints[1].value);
70 OSM.router.route("/" + OSM.formatHash(map));
73 function formatDistance(m) {
74 const unitTemplate = "javascripts.directions.distance_";
75 if (m < 1000) return I18n.t(unitTemplate + "m", { distance: Math.round(m) });
76 if (m < 10000) return I18n.t(unitTemplate + "km", { distance: (m / 1000.0).toFixed(1) });
77 return I18n.t(unitTemplate + "km", { distance: Math.round(m / 1000) });
80 function formatHeight(m) {
81 return I18n.t("javascripts.directions.distance_m", { distance: Math.round(m) });
84 function formatTime(s) {
85 let m = Math.round(s / 60);
86 const h = Math.floor(m / 60);
88 return h + ":" + (m < 10 ? "0" : "") + m;
91 function setEngine(id) {
92 const engines = OSM.Directions.engines;
93 const desired = engines.find(engine => engine.id === id);
94 if (!desired || (chosenEngine && chosenEngine.id === id)) return;
95 chosenEngine = desired;
98 .filter(engine => engine.provider === chosenEngine.provider)
99 .map(engine => engine.mode);
102 .prop("disabled", function () {
103 return !modes.includes(this.id);
105 .prop("checked", function () {
106 return this.id === chosenEngine.mode;
109 const providers = engines
110 .filter(engine => engine.mode === chosenEngine.mode)
111 .map(engine => engine.provider);
113 .find("option[value]")
114 .prop("disabled", function () {
115 return !providers.includes(this.value);
117 select.val(chosenEngine.provider);
120 function getRoute(fitRoute, reportErrors) {
121 // Cancel any route that is already in progress
122 if (controller) controller.abort();
124 const points = endpoints.map(p => p.latlng);
126 if (!points[0] || !points[1]) return;
127 $("header").addClass("closed");
129 OSM.router.replace("/directions?" + new URLSearchParams({
130 engine: chosenEngine.id,
131 route: points.map(p => OSM.cropLocation(p, map.getZoom()).join()).join(";")
134 // copy loading item to sidebar and display it. we copy it, rather than
135 // just using it in-place and replacing it in case it has to be used
137 $("#sidebar_content").html($(".directions_form .loader_copy").html());
138 map.setSidebarOverlaid(false);
139 controller = new AbortController();
140 chosenEngine.getRoute(points, controller.signal).then(function (route) {
142 .setLatLngs(route.line)
146 map.fitBounds(polyline.getBounds().pad(0.05));
149 const distanceText = $("<p>").append(
150 I18n.t("javascripts.directions.distance") + ": " + formatDistance(route.distance) + ". " +
151 I18n.t("javascripts.directions.time") + ": " + formatTime(route.time) + ".");
152 if (typeof route.ascend !== "undefined" && typeof route.descend !== "undefined") {
155 I18n.t("javascripts.directions.ascend") + ": " + formatHeight(route.ascend) + ". " +
156 I18n.t("javascripts.directions.descend") + ": " + formatHeight(route.descend) + ".");
159 const turnByTurnTable = $("<table class='table table-hover table-sm mb-3'>")
160 .append($("<tbody>"));
161 const directionsCloseButton = $("<button type='button' class='btn-close'>")
162 .attr("aria-label", I18n.t("javascripts.close"));
164 $("#sidebar_content")
167 $("<div class='d-flex'>").append(
168 $("<h2 class='flex-grow-1 text-break'>")
169 .text(I18n.t("javascripts.directions.directions")),
170 $("<div>").append(directionsCloseButton)),
176 route.steps.forEach(function (step) {
177 const [ll, direction, instruction, dist, lineseg] = step;
179 const row = $("<tr class='turn'/>");
180 row.append("<td class='border-0'><div class='direction i" + direction + "'/></td> ");
181 row.append("<td>" + instruction);
182 row.append("<td class='distance text-body-secondary text-end'>" + getDistText(dist));
184 row.on("click", function () {
187 .setContent("<p>" + instruction + "</p>")
191 row.hover(function () {
196 map.removeLayer(highlight);
199 turnByTurnTable.append(row);
202 const blob = new Blob([JSON.stringify(polyline.toGeoJSON())], { type: "application/json" });
203 URL.revokeObjectURL(downloadURL);
204 downloadURL = URL.createObjectURL(blob);
206 $("#sidebar_content").append(`<p class="text-center"><a href="${downloadURL}" download="${
207 I18n.t("javascripts.directions.filename")
209 I18n.t("javascripts.directions.download")
212 $("#sidebar_content").append("<p class=\"text-center\">" +
213 I18n.t("javascripts.directions.instructions.courtesy", { link: chosenEngine.creditline }) +
216 directionsCloseButton.on("click", function () {
217 map.removeLayer(polyline);
218 $("#sidebar_content").html("");
220 map.setSidebarOverlaid(true);
221 // TODO: collapse width of sidebar back to previous
223 }).catch(function () {
224 map.removeLayer(polyline);
226 $("#sidebar_content").html("<div class=\"alert alert-danger\">" + I18n.t("javascripts.directions.errors.no_route") + "</div>");
228 }).finally(function () {
232 function getDistText(dist) {
233 if (dist < 5) return "";
234 if (dist < 200) return String(Math.round(dist / 10) * 10) + "m";
235 if (dist < 1500) return String(Math.round(dist / 100) * 100) + "m";
236 if (dist < 5000) return String(Math.round(dist / 100) / 10) + "km";
237 return String(Math.round(dist / 1000)) + "km";
241 setEngine("fossgis_osrm_car");
242 setEngine(Cookies.get("_osm_directions_engine"));
244 modeGroup.on("change", "input[name='modes']", function (e) {
245 setEngine(chosenEngine.provider + "_" + e.target.id);
246 Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
247 getRoute(true, true);
250 select.on("change", function (e) {
251 setEngine(e.target.value + "_" + chosenEngine.mode);
252 Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
253 getRoute(true, true);
256 $(".directions_form").on("submit", function (e) {
258 getRoute(true, true);
261 $(".routing_marker_column img").on("dragstart", function (e) {
262 const dt = e.originalEvent.dataTransfer;
263 dt.effectAllowed = "move";
264 const dragData = { type: $(this).data("type") };
265 dt.setData("text", JSON.stringify(dragData));
266 if (dt.setDragImage) {
267 const img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
268 dt.setDragImage(img.get(0), 12, 21);
272 function sendstartinglocation({ latlng: { lat, lng } }) {
273 map.fire("startinglocation", { latlng: [lat, lng] });
276 map.on("locationfound", ({ latlng: { lat, lng } }) =>
277 lastLocation = [lat, lng]
278 ).on("locateactivate", () => {
279 map.once("startinglocation", ({ latlng }) => {
280 if (endpoints[0].value) return;
281 endpoints[0].setValue(latlng.join(", "));
287 page.pushstate = page.popstate = function () {
288 $(".search_form").hide();
289 $(".directions_form").show();
291 $("#map").on("dragend dragover", function (e) {
295 $("#map").on("drop", function (e) {
297 const oe = e.originalEvent;
298 const dragData = JSON.parse(oe.dataTransfer.getData("text"));
299 const type = dragData.type;
300 const pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
302 const ll = map.containerPointToLatLng(pt);
303 const llWithPrecision = OSM.cropLocation(ll, map.getZoom());
304 endpoints[type === "from" ? 0 : 1].setValue(llWithPrecision.join(", "));
307 map.on("locationfound", sendstartinglocation);
309 endpoints[0].enable();
310 endpoints[1].enable();
312 const params = new URLSearchParams(location.search),
313 route = (params.get("route") || "").split(";");
315 if (params.has("engine")) setEngine(params.get("engine"));
317 endpoints[0].setValue(params.get("from") || route[0] || lastLocation.join(", "));
318 endpoints[1].setValue(params.get("to") || route[1] || "");
320 map.setSidebarOverlaid(!endpoints[0].latlng || !endpoints[1].latlng);
323 page.load = function () {
327 page.unload = function () {
328 $(".search_form").show();
329 $(".directions_form").hide();
330 $("#map").off("dragend dragover drop");
331 map.off("locationfound", sendstartinglocation);
333 endpoints[0].disable();
334 endpoints[1].disable();
338 .removeLayer(polyline);
344 OSM.Directions.engines = [];
346 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
347 if (document.location.protocol === "http:" || supportsHTTPS) {
348 engine.id = engine.provider + "_" + engine.mode;
349 OSM.Directions.engines.push(engine);