1 //= require ./directions-endpoint
2 //= require ./directions-route-output
4 //= require_tree ./directions
6 OSM.Directions = function (map) {
7 let controller = null; // the AbortController for the current route request if a route request is in progress
11 let sidebarReadyPromise = null;
13 const routeOutput = OSM.DirectionsRouteOutput(map);
15 const endpointDragCallback = function (dragging) {
16 if (!routeOutput.isVisible()) return;
17 if (dragging && !chosenEngine.draggable) return;
18 if (dragging && controller) return;
20 getRoute(false, !dragging);
22 const endpointChangeCallback = function () {
27 OSM.DirectionsEndpoint(map, $("input[name='route_from']"), { icon: "MARKER_GREEN" }, endpointDragCallback, endpointChangeCallback),
28 OSM.DirectionsEndpoint(map, $("input[name='route_to']"), { icon: "MARKER_RED" }, endpointDragCallback, endpointChangeCallback)
31 const expiry = new Date();
32 expiry.setYear(expiry.getFullYear() + 10);
34 const modeGroup = $(".routing_modes");
35 const select = $("select.routing_engines");
37 $(".directions_form .reverse_directions").on("click", function () {
38 const coordFrom = endpoints[0].latlng,
39 coordTo = endpoints[1].latlng;
43 routeFrom = coordFrom.lat + "," + coordFrom.lng;
46 routeTo = coordTo.lat + "," + coordTo.lng;
48 endpoints[0].swapCachedReverseGeocodes(endpoints[1]);
50 OSM.router.route("/directions?" + new URLSearchParams({
51 route: routeTo + ";" + routeFrom
55 $(".directions_form .btn-close").on("click", function (e) {
57 $(".describe_location").toggle(!endpoints[1].value);
58 $(".search_form input[name='query']").val(endpoints[1].value);
59 OSM.router.route("/" + OSM.formatHash(map));
62 function setEngine(id) {
63 const engines = OSM.Directions.engines;
64 const desired = engines.find(engine => engine.id === id);
65 if (!desired || (chosenEngine && chosenEngine.id === id)) return;
66 chosenEngine = desired;
69 .filter(engine => engine.provider === chosenEngine.provider)
70 .map(engine => engine.mode);
73 .prop("disabled", function () {
74 return !modes.includes(this.id);
76 .prop("checked", function () {
77 return this.id === chosenEngine.mode;
80 const providers = engines
81 .filter(engine => engine.mode === chosenEngine.mode)
82 .map(engine => engine.provider);
84 .find("option[value]")
85 .prop("disabled", function () {
86 return !providers.includes(this.value);
88 select.val(chosenEngine.provider);
91 function getRoute(fitRoute, reportErrors) {
92 // Cancel any route that is already in progress
93 if (controller) controller.abort();
95 const points = endpoints.map(p => p.latlng);
97 if (!points[0] || !points[1]) return;
98 $("header").addClass("closed");
100 OSM.router.replace("/directions?" + new URLSearchParams({
101 engine: chosenEngine.id,
102 route: points.map(p => `${p.lat},${p.lng}`).join(";")
105 $("#directions_loader").prop("hidden", false);
106 $("#directions_error").prop("hidden", true).empty();
107 $("#directions_route").prop("hidden", true);
108 map.setSidebarOverlaid(false);
109 controller = new AbortController();
110 chosenEngine.getRoute(points, controller.signal).then(async function (route) {
111 await sidebarLoaded();
112 $("#directions_route").prop("hidden", false);
113 routeOutput.write(route);
117 }).catch(async function () {
118 await sidebarLoaded();
119 routeOutput.remove();
121 $("#directions_error")
122 .prop("hidden", false)
123 .html("<div class=\"alert alert-danger\">" + OSM.i18n.t("javascripts.directions.errors.no_route") + "</div>");
125 }).finally(function () {
126 $("#directions_loader").prop("hidden", true);
131 function closeButtonListener(e) {
133 routeOutput.remove();
134 sidebarReadyPromise = null;
135 map.setSidebarOverlaid(true);
136 // TODO: collapse width of sidebar back to previous
139 setEngine("fossgis_osrm_car");
140 setEngine(Cookies.get("_osm_directions_engine"));
142 modeGroup.on("change", "input[name='modes']", function (e) {
143 setEngine(chosenEngine.provider + "_" + e.target.id);
144 Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
145 getRoute(true, true);
148 select.on("change", function (e) {
149 setEngine(e.target.value + "_" + chosenEngine.mode);
150 Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
151 getRoute(true, true);
154 $(".directions_form").on("submit", function (e) {
156 getRoute(true, true);
159 $(".routing_marker_column img").on("dragstart", function (e) {
160 const dt = e.originalEvent.dataTransfer;
161 dt.effectAllowed = "move";
162 const dragData = { type: $(this).data("type") };
163 dt.setData("text", JSON.stringify(dragData));
164 if (dt.setDragImage) {
165 const img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
166 dt.setDragImage(img.get(0), 12, 21);
170 function sendstartinglocation({ latlng: { lat, lng } }) {
171 map.fire("startinglocation", { latlng: [lat, lng] });
174 function startingLocationListener({ latlng }) {
175 if (endpoints[0].value) return;
176 endpoints[0].setValue(latlng.join(", "));
179 map.on("locationfound", ({ latlng: { lat, lng } }) =>
180 lastLocation = [lat, lng]
181 ).on("locateactivate", () => {
182 map.once("startinglocation", startingLocationListener);
185 function initializeFromParams() {
186 const params = new URLSearchParams(location.search),
187 route = (params.get("route") || "").split(";");
189 if (params.has("engine")) setEngine(params.get("engine"));
191 endpoints[0].setValue(params.get("from") || route[0] || lastLocation.join(", "));
192 endpoints[1].setValue(params.get("to") || route[1] || "");
195 function enableListeners() {
196 $("#sidebar .sidebar-close-controls button").on("click", closeButtonListener);
198 $("#map").on("dragend dragover", function (e) {
202 $("#map").on("drop", function (e) {
204 const oe = e.originalEvent;
205 const dragData = JSON.parse(oe.dataTransfer.getData("text"));
206 const type = dragData.type;
207 const pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
209 const ll = map.containerPointToLatLng(pt);
210 const llWithPrecision = OSM.cropLocation(ll, map.getZoom());
211 endpoints[type === "from" ? 0 : 1].setValue(llWithPrecision.join(", "));
214 map.on("locationfound", sendstartinglocation);
216 endpoints[0].enableListeners();
217 endpoints[1].enableListeners();
222 function sidebarLoaded() {
223 if ($("#directions_route").length) {
224 sidebarReadyPromise = null;
225 return Promise.resolve();
227 if (sidebarReadyPromise) return sidebarReadyPromise;
228 sidebarReadyPromise = new Promise(resolve => OSM.loadSidebarContent("/directions", resolve));
229 return sidebarReadyPromise;
232 page.pushstate = page.popstate = page.load = function () {
233 initializeFromParams();
235 $(".search_form").hide();
236 $(".directions_form").show();
238 sidebarLoaded().then(enableListeners);
240 map.setSidebarOverlaid(!endpoints[0].latlng || !endpoints[1].latlng);
243 page.unload = function () {
244 $(".search_form").show();
245 $(".directions_form").hide();
247 $("#sidebar .sidebar-close-controls button").off("click", closeButtonListener);
248 $("#map").off("dragend dragover drop");
249 map.off("locationfound", sendstartinglocation);
251 endpoints[0].disableListeners();
252 endpoints[1].disableListeners();
254 endpoints[0].clearValue();
255 endpoints[1].clearValue();
257 routeOutput.remove();
259 sidebarReadyPromise = null;
265 OSM.Directions.engines = [];
267 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
268 if (location.protocol === "http:" || supportsHTTPS) {
269 engine.id = engine.provider + "_" + engine.mode;
270 OSM.Directions.engines.push(engine);