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) {
75 return I18n.t("javascripts.directions.distance_m", { distance: Math.round(m) });
76 } else if (m < 10000) {
77 return I18n.t("javascripts.directions.distance_km", { distance: (m / 1000.0).toFixed(1) });
79 return I18n.t("javascripts.directions.distance_km", { distance: Math.round(m / 1000) });
83 function getDistText(dist) {
84 if (dist < 5) return "";
85 if (dist < 200) return String(Math.round(dist / 10) * 10) + "m";
86 if (dist < 1500) return String(Math.round(dist / 100) * 100) + "m";
87 if (dist < 5000) return String(Math.round(dist / 100) / 10) + "km";
88 return String(Math.round(dist / 1000)) + "km";
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 setEngine(id) {
103 const engines = OSM.Directions.engines;
104 const desired = engines.find(engine => engine.id === id);
105 if (!desired || (chosenEngine && chosenEngine.id === id)) return;
106 chosenEngine = desired;
108 const modes = engines
109 .filter(engine => engine.provider === chosenEngine.provider)
110 .map(engine => engine.mode);
113 .prop("disabled", function () {
114 return !modes.includes(this.id);
116 .prop("checked", function () {
117 return this.id === chosenEngine.mode;
120 const providers = engines
121 .filter(engine => engine.mode === chosenEngine.mode)
122 .map(engine => engine.provider);
124 .find("option[value]")
125 .prop("disabled", function () {
126 return !providers.includes(this.value);
128 select.val(chosenEngine.provider);
131 function getRoute(fitRoute, reportErrors) {
132 // Cancel any route that is already in progress
133 if (controller) controller.abort();
135 const points = endpoints.map(p => p.latlng);
137 if (!points[0] || !points[1]) return;
138 $("header").addClass("closed");
140 OSM.router.replace("/directions?" + new URLSearchParams({
141 engine: chosenEngine.id,
142 route: points.map(p => OSM.cropLocation(p, map.getZoom()).join()).join(";")
145 // copy loading item to sidebar and display it. we copy it, rather than
146 // just using it in-place and replacing it in case it has to be used
148 $("#directions_content").html($(".directions_form .loader_copy").html());
149 map.setSidebarOverlaid(false);
150 controller = new AbortController();
151 chosenEngine.getRoute(points, controller.signal).then(function (route) {
153 .setLatLngs(route.line)
157 map.fitBounds(polyline.getBounds().pad(0.05));
160 const distanceText = $("<p>").append(
161 I18n.t("javascripts.directions.distance") + ": " + formatDistance(route.distance) + ". " +
162 I18n.t("javascripts.directions.time") + ": " + formatTime(route.time) + ".");
163 if (typeof route.ascend !== "undefined" && typeof route.descend !== "undefined") {
166 I18n.t("javascripts.directions.ascend") + ": " + formatHeight(route.ascend) + ". " +
167 I18n.t("javascripts.directions.descend") + ": " + formatHeight(route.descend) + ".");
170 const turnByTurnTable = $("<table class='table table-hover table-sm mb-3'>")
171 .append($("<tbody>"));
173 $("#directions_content")
181 route.steps.forEach(function (step) {
182 const [ll, direction, instruction, dist, lineseg] = step;
184 const row = $("<tr class='turn'/>");
186 row.append("<td class='border-0'><svg width='20' height='20' class='d-block'><use href='#routing-sprite-" + direction + "' /></svg></td>");
188 row.append("<td class='border-0'>");
190 row.append("<td>" + instruction);
191 row.append("<td class='distance text-body-secondary text-end'>" + getDistText(dist));
193 row.on("click", function () {
196 .setContent("<p>" + instruction + "</p>")
200 row.hover(function () {
205 map.removeLayer(highlight);
208 turnByTurnTable.append(row);
211 const blob = new Blob([JSON.stringify(polyline.toGeoJSON())], { type: "application/json" });
212 URL.revokeObjectURL(downloadURL);
213 downloadURL = URL.createObjectURL(blob);
215 $("#directions_content").append(`<p class="text-center"><a href="${downloadURL}" download="${
216 I18n.t("javascripts.directions.filename")
218 I18n.t("javascripts.directions.download")
221 $("#directions_content").append("<p class=\"text-center\">" +
222 I18n.t("javascripts.directions.instructions.courtesy", { link: chosenEngine.creditline }) +
224 }).catch(function () {
225 map.removeLayer(polyline);
227 $("#directions_content").html("<div class=\"alert alert-danger\">" + I18n.t("javascripts.directions.errors.no_route") + "</div>");
229 }).finally(function () {
234 function hideRoute(e) {
236 map.removeLayer(polyline);
237 $("#directions_content").html("");
239 map.setSidebarOverlaid(true);
240 // TODO: collapse width of sidebar back to previous
243 setEngine("fossgis_osrm_car");
244 setEngine(Cookies.get("_osm_directions_engine"));
246 modeGroup.on("change", "input[name='modes']", function (e) {
247 setEngine(chosenEngine.provider + "_" + e.target.id);
248 Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
249 getRoute(true, true);
252 select.on("change", function (e) {
253 setEngine(e.target.value + "_" + chosenEngine.mode);
254 Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
255 getRoute(true, true);
258 $(".directions_form").on("submit", function (e) {
260 getRoute(true, true);
263 $(".routing_marker_column img").on("dragstart", function (e) {
264 const dt = e.originalEvent.dataTransfer;
265 dt.effectAllowed = "move";
266 const dragData = { type: $(this).data("type") };
267 dt.setData("text", JSON.stringify(dragData));
268 if (dt.setDragImage) {
269 const img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
270 dt.setDragImage(img.get(0), 12, 21);
274 function sendstartinglocation({ latlng: { lat, lng } }) {
275 map.fire("startinglocation", { latlng: [lat, lng] });
278 function startingLocationListener({ latlng }) {
279 if (endpoints[0].value) return;
280 endpoints[0].setValue(latlng.join(", "));
283 map.on("locationfound", ({ latlng: { lat, lng } }) =>
284 lastLocation = [lat, lng]
285 ).on("locateactivate", () => {
286 map.once("startinglocation", startingLocationListener);
289 function initializeFromParams() {
290 const params = new URLSearchParams(location.search),
291 route = (params.get("route") || "").split(";");
293 if (params.has("engine")) setEngine(params.get("engine"));
295 endpoints[0].setValue(params.get("from") || route[0] || lastLocation.join(", "));
296 endpoints[1].setValue(params.get("to") || route[1] || "");
299 function enableListeners() {
300 $("#sidebar .sidebar-close-controls button").on("click", hideRoute);
302 $("#map").on("dragend dragover", function (e) {
306 $("#map").on("drop", function (e) {
308 const oe = e.originalEvent;
309 const dragData = JSON.parse(oe.dataTransfer.getData("text"));
310 const type = dragData.type;
311 const pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
313 const ll = map.containerPointToLatLng(pt);
314 const llWithPrecision = OSM.cropLocation(ll, map.getZoom());
315 endpoints[type === "from" ? 0 : 1].setValue(llWithPrecision.join(", "));
318 map.on("locationfound", sendstartinglocation);
320 endpoints[0].enableListeners();
321 endpoints[1].enableListeners();
326 page.pushstate = page.popstate = function () {
327 if ($("#directions_content").length) {
330 initializeFromParams();
332 $(".search_form").hide();
333 $(".directions_form").show();
335 OSM.loadSidebarContent("/directions", enableListeners);
337 map.setSidebarOverlaid(!endpoints[0].latlng || !endpoints[1].latlng);
341 page.load = function () {
342 initializeFromParams();
344 $(".search_form").hide();
345 $(".directions_form").show();
349 map.setSidebarOverlaid(!endpoints[0].latlng || !endpoints[1].latlng);
352 page.unload = function () {
353 $(".search_form").show();
354 $(".directions_form").hide();
356 $("#sidebar .sidebar-close-controls button").off("click", hideRoute);
357 $("#map").off("dragend dragover drop");
358 map.off("locationfound", sendstartinglocation);
360 endpoints[0].disableListeners();
361 endpoints[1].disableListeners();
363 endpoints[0].clearValue();
364 endpoints[1].clearValue();
368 .removeLayer(polyline);
374 OSM.Directions.engines = [];
376 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
377 if (location.protocol === "http:" || supportsHTTPS) {
378 engine.id = engine.provider + "_" + engine.mode;
379 OSM.Directions.engines.push(engine);