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 $("#directions_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>"));
162 $("#directions_content")
170 route.steps.forEach(function (step) {
171 const [ll, direction, instruction, dist, lineseg] = step;
173 const row = $("<tr class='turn'/>");
175 row.append("<td class='border-0'><svg width='20' height='20' class='d-block'><use href='#routing-sprite-" + direction + "' /></svg></td>");
177 row.append("<td class='border-0'>");
179 row.append("<td>" + instruction);
180 row.append("<td class='distance text-body-secondary text-end'>" + getDistText(dist));
182 row.on("click", function () {
185 .setContent("<p>" + instruction + "</p>")
189 row.hover(function () {
194 map.removeLayer(highlight);
197 turnByTurnTable.append(row);
200 const blob = new Blob([JSON.stringify(polyline.toGeoJSON())], { type: "application/json" });
201 URL.revokeObjectURL(downloadURL);
202 downloadURL = URL.createObjectURL(blob);
204 $("#directions_content").append(`<p class="text-center"><a href="${downloadURL}" download="${
205 I18n.t("javascripts.directions.filename")
207 I18n.t("javascripts.directions.download")
210 $("#directions_content").append("<p class=\"text-center\">" +
211 I18n.t("javascripts.directions.instructions.courtesy", { link: chosenEngine.creditline }) +
213 }).catch(function () {
214 map.removeLayer(polyline);
216 $("#directions_content").html("<div class=\"alert alert-danger\">" + I18n.t("javascripts.directions.errors.no_route") + "</div>");
218 }).finally(function () {
222 function getDistText(dist) {
223 if (dist < 5) return "";
224 if (dist < 200) return String(Math.round(dist / 10) * 10) + "m";
225 if (dist < 1500) return String(Math.round(dist / 100) * 100) + "m";
226 if (dist < 5000) return String(Math.round(dist / 100) / 10) + "km";
227 return String(Math.round(dist / 1000)) + "km";
231 function hideRoute(e) {
233 map.removeLayer(polyline);
234 $("#directions_content").html("");
236 map.setSidebarOverlaid(true);
237 // TODO: collapse width of sidebar back to previous
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.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);
271 function sendstartinglocation({ latlng: { lat, lng } }) {
272 map.fire("startinglocation", { latlng: [lat, lng] });
275 function startingLocationListener({ latlng }) {
276 if (endpoints[0].value) return;
277 endpoints[0].setValue(latlng.join(", "));
280 map.on("locationfound", ({ latlng: { lat, lng } }) =>
281 lastLocation = [lat, lng]
282 ).on("locateactivate", () => {
283 map.once("startinglocation", startingLocationListener);
286 function initializeFromParams() {
287 const params = new URLSearchParams(location.search),
288 route = (params.get("route") || "").split(";");
290 if (params.has("engine")) setEngine(params.get("engine"));
292 endpoints[0].setValue(params.get("from") || route[0] || lastLocation.join(", "));
293 endpoints[1].setValue(params.get("to") || route[1] || "");
296 function enableListeners() {
297 $("#sidebar .sidebar-close-controls button").on("click", hideRoute);
299 $("#map").on("dragend dragover", function (e) {
303 $("#map").on("drop", function (e) {
305 const oe = e.originalEvent;
306 const dragData = JSON.parse(oe.dataTransfer.getData("text"));
307 const type = dragData.type;
308 const pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
310 const ll = map.containerPointToLatLng(pt);
311 const llWithPrecision = OSM.cropLocation(ll, map.getZoom());
312 endpoints[type === "from" ? 0 : 1].setValue(llWithPrecision.join(", "));
315 map.on("locationfound", sendstartinglocation);
317 endpoints[0].enableListeners();
318 endpoints[1].enableListeners();
323 page.pushstate = page.popstate = function () {
324 if ($("#directions_content").length) {
327 initializeFromParams();
329 $(".search_form").hide();
330 $(".directions_form").show();
332 OSM.loadSidebarContent("/directions", enableListeners);
334 map.setSidebarOverlaid(!endpoints[0].latlng || !endpoints[1].latlng);
338 page.load = function () {
339 initializeFromParams();
341 $(".search_form").hide();
342 $(".directions_form").show();
346 map.setSidebarOverlaid(!endpoints[0].latlng || !endpoints[1].latlng);
349 page.unload = function () {
350 $(".search_form").show();
351 $(".directions_form").hide();
353 $("#sidebar .sidebar-close-controls button").off("click", hideRoute);
354 $("#map").off("dragend dragover drop");
355 map.off("locationfound", sendstartinglocation);
357 endpoints[0].disableListeners();
358 endpoints[1].disableListeners();
360 endpoints[0].clearValue();
361 endpoints[1].clearValue();
365 .removeLayer(polyline);
371 OSM.Directions.engines = [];
373 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
374 if (location.protocol === "http:" || supportsHTTPS) {
375 engine.id = engine.provider + "_" + engine.mode;
376 OSM.Directions.engines.push(engine);