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 engines = OSM.Directions.engines;
47 engines.sort(function (a, b) {
48 const localised_a = I18n.t("javascripts.directions.engines." + a.id),
49 localised_b = I18n.t("javascripts.directions.engines." + b.id);
50 return localised_a.localeCompare(localised_b);
53 const select = $("select.routing_engines");
55 engines.forEach(function (engine, i) {
56 select.append("<option value='" + i + "'>" + I18n.t("javascripts.directions.engines." + engine.id) + "</option>");
59 $(".directions_form .reverse_directions").on("click", function () {
60 const coordFrom = endpoints[0].latlng,
61 coordTo = endpoints[1].latlng;
65 routeFrom = coordFrom.lat + "," + coordFrom.lng;
68 routeTo = coordTo.lat + "," + coordTo.lng;
70 endpoints[0].swapCachedReverseGeocodes(endpoints[1]);
72 OSM.router.route("/directions?" + new URLSearchParams({
73 route: routeTo + ";" + routeFrom
77 $(".directions_form .btn-close").on("click", function (e) {
79 $(".describe_location").toggle(!endpoints[1].value);
80 $(".search_form input[name='query']").val(endpoints[1].value);
81 OSM.router.route("/" + OSM.formatHash(map));
84 function formatDistance(m) {
85 const unitTemplate = "javascripts.directions.distance_";
86 if (m < 1000) return I18n.t(unitTemplate + "m", { distance: Math.round(m) });
87 if (m < 10000) return I18n.t(unitTemplate + "km", { distance: (m / 1000.0).toFixed(1) });
88 return I18n.t(unitTemplate + "km", { distance: Math.round(m / 1000) });
91 function formatHeight(m) {
92 return I18n.t("javascripts.directions.distance_m", { distance: Math.round(m) });
95 function formatTime(s) {
96 let m = Math.round(s / 60);
97 const h = Math.floor(m / 60);
99 return h + ":" + (m < 10 ? "0" : "") + m;
102 function findEngine(id) {
103 return engines.findIndex(function (engine) {
104 return engine.id === id;
108 function setEngine(index) {
109 chosenEngine = engines[index];
113 function getRoute(fitRoute, reportErrors) {
114 // Cancel any route that is already in progress
115 if (controller) controller.abort();
117 const points = endpoints.map(p => p.latlng);
119 if (!points[0] || !points[1]) return;
120 $("header").addClass("closed");
122 OSM.router.replace("/directions?" + new URLSearchParams({
123 engine: chosenEngine.id,
124 route: points.map(p => OSM.cropLocation(p, map.getZoom()).join()).join(";")
127 // copy loading item to sidebar and display it. we copy it, rather than
128 // just using it in-place and replacing it in case it has to be used
130 $("#sidebar_content").html($(".directions_form .loader_copy").html());
131 map.setSidebarOverlaid(false);
132 controller = new AbortController();
133 chosenEngine.getRoute(points, controller.signal).then(function (route) {
135 .setLatLngs(route.line)
139 map.fitBounds(polyline.getBounds().pad(0.05));
142 const distanceText = $("<p>").append(
143 I18n.t("javascripts.directions.distance") + ": " + formatDistance(route.distance) + ". " +
144 I18n.t("javascripts.directions.time") + ": " + formatTime(route.time) + ".");
145 if (typeof route.ascend !== "undefined" && typeof route.descend !== "undefined") {
148 I18n.t("javascripts.directions.ascend") + ": " + formatHeight(route.ascend) + ". " +
149 I18n.t("javascripts.directions.descend") + ": " + formatHeight(route.descend) + ".");
152 const turnByTurnTable = $("<table class='table table-hover table-sm mb-3'>")
153 .append($("<tbody>"));
154 const directionsCloseButton = $("<button type='button' class='btn-close'>")
155 .attr("aria-label", I18n.t("javascripts.close"));
157 $("#sidebar_content")
160 $("<div class='d-flex'>").append(
161 $("<h2 class='flex-grow-1 text-break'>")
162 .text(I18n.t("javascripts.directions.directions")),
163 $("<div>").append(directionsCloseButton)),
169 route.steps.forEach(function (step) {
170 const [ll, direction, instruction, dist, lineseg] = step;
172 const row = $("<tr class='turn'/>");
173 row.append("<td class='border-0'><div class='direction i" + direction + "'/></td> ");
174 row.append("<td>" + instruction);
175 row.append("<td class='distance text-body-secondary text-end'>" + getDistText(dist));
177 row.on("click", function () {
180 .setContent("<p>" + instruction + "</p>")
184 row.hover(function () {
189 map.removeLayer(highlight);
192 turnByTurnTable.append(row);
195 const blob = new Blob([JSON.stringify(polyline.toGeoJSON())], { type: "application/json" });
196 URL.revokeObjectURL(downloadURL);
197 downloadURL = URL.createObjectURL(blob);
199 $("#sidebar_content").append(`<p class="text-center"><a href="${downloadURL}" download="${
200 I18n.t("javascripts.directions.filename")
202 I18n.t("javascripts.directions.download")
205 $("#sidebar_content").append("<p class=\"text-center\">" +
206 I18n.t("javascripts.directions.instructions.courtesy", { link: chosenEngine.creditline }) +
209 directionsCloseButton.on("click", function () {
210 map.removeLayer(polyline);
211 $("#sidebar_content").html("");
213 map.setSidebarOverlaid(true);
214 // TODO: collapse width of sidebar back to previous
216 }).catch(function () {
217 map.removeLayer(polyline);
219 $("#sidebar_content").html("<div class=\"alert alert-danger\">" + I18n.t("javascripts.directions.errors.no_route") + "</div>");
221 }).finally(function () {
225 function getDistText(dist) {
226 if (dist < 5) return "";
227 if (dist < 200) return String(Math.round(dist / 10) * 10) + "m";
228 if (dist < 1500) return String(Math.round(dist / 100) * 100) + "m";
229 if (dist < 5000) return String(Math.round(dist / 100) / 10) + "km";
230 return String(Math.round(dist / 1000)) + "km";
234 let chosenEngineIndex = findEngine("fossgis_osrm_car");
235 if (Cookies.get("_osm_directions_engine")) {
236 chosenEngineIndex = findEngine(Cookies.get("_osm_directions_engine"));
238 setEngine(chosenEngineIndex);
240 select.on("change", function (e) {
241 chosenEngine = engines[e.target.selectedIndex];
242 Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
243 getRoute(true, true);
246 $(".directions_form").on("submit", function (e) {
248 getRoute(true, true);
251 $(".routing_marker_column img").on("dragstart", function (e) {
252 const dt = e.originalEvent.dataTransfer;
253 dt.effectAllowed = "move";
254 const dragData = { type: $(this).data("type") };
255 dt.setData("text", JSON.stringify(dragData));
256 if (dt.setDragImage) {
257 const img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
258 dt.setDragImage(img.get(0), 12, 21);
262 function sendstartinglocation({ latlng: { lat, lng } }) {
263 map.fire("startinglocation", { latlng: [lat, lng] });
266 map.on("locationfound", ({ latlng: { lat, lng } }) =>
267 lastLocation = [lat, lng]
268 ).on("locateactivate", () => {
269 map.once("startinglocation", ({ latlng }) => {
270 if (endpoints[0].value) return;
271 endpoints[0].setValue(latlng.join(", "));
277 page.pushstate = page.popstate = function () {
278 $(".search_form").hide();
279 $(".directions_form").show();
281 $("#map").on("dragend dragover", function (e) {
285 $("#map").on("drop", function (e) {
287 const oe = e.originalEvent;
288 const dragData = JSON.parse(oe.dataTransfer.getData("text"));
289 const type = dragData.type;
290 const pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
292 const ll = map.containerPointToLatLng(pt);
293 const llWithPrecision = OSM.cropLocation(ll, map.getZoom());
294 endpoints[type === "from" ? 0 : 1].setValue(llWithPrecision.join(", "));
297 map.on("locationfound", sendstartinglocation);
299 endpoints[0].enable();
300 endpoints[1].enable();
302 const params = new URLSearchParams(location.search),
303 route = (params.get("route") || "").split(";");
305 if (params.has("engine")) {
306 const engineIndex = findEngine(params.get("engine"));
308 if (engineIndex >= 0) {
309 setEngine(engineIndex);
313 endpoints[0].setValue(params.get("from") || route[0] || lastLocation.join(", "));
314 endpoints[1].setValue(params.get("to") || route[1] || "");
316 map.setSidebarOverlaid(!endpoints[0].latlng || !endpoints[1].latlng);
319 page.load = function () {
323 page.unload = function () {
324 $(".search_form").show();
325 $(".directions_form").hide();
326 $("#map").off("dragend dragover drop");
327 map.off("locationfound", sendstartinglocation);
329 endpoints[0].disable();
330 endpoints[1].disable();
334 .removeLayer(polyline);
340 OSM.Directions.engines = [];
342 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
343 if (document.location.protocol === "http:" || supportsHTTPS) {
344 OSM.Directions.engines.push(engine);