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);
24 OSM.DirectionsEndpoint(map, $("input[name='route_from']"), { icon: "start", color: "var(--marker-green)" }, endpointDragCallback, getRoute),
25 OSM.DirectionsEndpoint(map, $("input[name='route_to']"), { icon: "destination", color: "var(--marker-red)" }, endpointDragCallback, getRoute)
28 const expires = new Date();
30 expires.setFullYear(expires.getFullYear() + 10);
32 const modeGroup = $(".routing_modes");
33 const select = $("select#routing_engines");
35 $(".directions_form .reverse_directions").on("click", function () {
36 const coordFrom = endpoints[0].latlng,
37 coordTo = endpoints[1].latlng;
42 routeFrom = coordFrom.lat + "," + coordFrom.lng;
46 routeTo = coordTo.lat + "," + coordTo.lng;
49 endpoints[0].swapCachedReverseGeocodes(endpoints[1]);
51 OSM.router.route("/directions?" + new URLSearchParams({
52 route: routeTo + ";" + routeFrom
56 $(".directions_form .btn-close").on("click", function (e) {
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);
66 if (!desired || (chosenEngine && chosenEngine.id === id)) return;
68 chosenEngine = desired;
71 .filter(engine => engine.provider === chosenEngine.provider)
72 .map(engine => engine.mode);
76 .prop("disabled", function () {
77 return !modes.includes(this.value);
79 .prop("checked", function () {
80 return this.value === chosenEngine.mode;
83 const providers = engines
84 .filter(engine => engine.mode === chosenEngine.mode)
85 .map(engine => engine.provider);
88 .find("option[value]")
89 .prop("disabled", function () {
90 return !providers.includes(this.value);
92 select.val(chosenEngine.provider);
95 function getRoute(fitRoute = true, reportErrors = true) {
96 // Cancel any route that is already in progress
97 if (controller) controller.abort();
99 const points = endpoints.map(p => p.latlng);
101 if (!points[0] || !points[1]) return;
103 $("header").addClass("closed");
105 OSM.router.replace("/directions?" + new URLSearchParams({
106 engine: chosenEngine.id,
107 route: points.map(p => `${p.lat},${p.lng}`).join(";")
110 $("#directions_loader").prop("hidden", false);
111 $("#directions_error").prop("hidden", true).empty();
112 $("#directions_route").prop("hidden", true);
113 map.setSidebarOverlaid(false);
114 controller = new AbortController();
115 chosenEngine.getRoute(points, controller.signal).then(async function (route) {
116 await sidebarLoaded();
117 $("#directions_route").prop("hidden", false);
118 routeOutput.write(route);
123 }).catch(async function (error) {
124 if (error.name === "AbortError") return;
126 await sidebarLoaded();
127 routeOutput.remove();
130 $("#directions_error")
131 .prop("hidden", false)
132 .html("<div class=\"alert alert-danger\">" + OSM.i18n.t("javascripts.directions.errors.no_route") + "</div>");
134 }).finally(function () {
135 $("#directions_loader").prop("hidden", true);
140 function closeButtonListener(e) {
142 routeOutput.remove();
143 sidebarReadyPromise = null;
144 map.setSidebarOverlaid(true);
147 setEngine("fossgis_osrm_car");
148 setEngine(OSM.cookies.get("_osm_directions_engine"));
150 modeGroup.on("change", "input[name='modes']", function (e) {
151 setEngine(chosenEngine.provider + "_" + e.target.value);
152 OSM.cookies.set("_osm_directions_engine", chosenEngine.id, { expires });
156 select.on("change", function (e) {
157 setEngine(e.target.value + "_" + chosenEngine.mode);
158 OSM.cookies.set("_osm_directions_engine", chosenEngine.id, { expires });
162 $(".directions_form").on("submit", function (e) {
167 $(".routing_marker_column span").on("dragstart", function (e) {
168 const dt = e.originalEvent.dataTransfer;
170 dt.effectAllowed = "move";
172 const jqthis = $(this);
174 dt.setData("text", JSON.stringify(jqthis.data()));
176 if (dt.setDragImage) {
177 const img = jqthis.clone()
178 .appendTo(document.body);
181 .toggleClass("position-absolute bottom-100 end-100")
182 .attr({ width: "25", height: "40" });
183 dt.setDragImage(img.get(0), 12, 21);
184 setTimeout(() => img.remove(), 0);
188 function sendstartinglocation({ latlng: { lat, lng } }) {
189 map.fire("startinglocation", { latlng: [lat, lng] });
192 function startingLocationListener({ latlng }) {
193 if (endpoints[0].value) return;
195 endpoints[0].setValue(latlng.join(", "));
198 map.on("locationfound", ({ latlng: { lat, lng } }) =>
199 lastLocation = [lat, lng]
200 ).on("locateactivate", () => {
201 map.once("startinglocation", startingLocationListener);
204 function initializeFromParams() {
205 const params = new URLSearchParams(location.search),
206 route = (params.get("route") || "").split(";");
208 if (params.has("engine")) setEngine(params.get("engine"));
210 endpoints[0].setValue(params.get("from") || route[0] || lastLocation.join(", "));
211 endpoints[1].setValue(params.get("to") || route[1] || "");
214 function enableListeners() {
215 $("#sidebar .sidebar-close-controls button").on("click", closeButtonListener);
217 $("#map").on("dragend dragover", function (e) {
221 $("#map").on("drop", function (e) {
224 const oe = e.originalEvent;
225 const dragData = JSON.parse(oe.dataTransfer.getData("text"));
226 const type = dragData.type;
227 const pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
231 const ll = map.containerPointToLatLng(pt);
232 const llWithPrecision = OSM.cropLocation(ll, map.getZoom());
234 endpoints[type === "from" ? 0 : 1].setValue(llWithPrecision.join(", "));
237 map.on("locationfound", sendstartinglocation);
239 endpoints[0].enableListeners();
240 endpoints[1].enableListeners();
245 function sidebarLoaded() {
246 if ($("#directions_route").length) {
247 sidebarReadyPromise = null;
249 return Promise.resolve();
252 if (sidebarReadyPromise) return sidebarReadyPromise;
254 sidebarReadyPromise = new Promise(resolve => OSM.loadSidebarContent("/directions", resolve));
256 return sidebarReadyPromise;
259 page.pushstate = page.popstate = page.load = function () {
260 initializeFromParams();
262 $(".search_form").hide();
263 $(".directions_form").show();
265 sidebarLoaded().then(enableListeners);
267 map.setSidebarOverlaid(!endpoints[0].latlng || !endpoints[1].latlng);
270 page.unload = function () {
271 $(".search_form").show();
272 $(".directions_form").hide();
274 $("#sidebar .sidebar-close-controls button").off("click", closeButtonListener);
275 $("#map").off("dragend dragover drop");
276 map.off("locationfound", sendstartinglocation);
278 endpoints[0].disableListeners();
279 endpoints[1].disableListeners();
281 endpoints[0].clearValue();
282 endpoints[1].clearValue();
284 routeOutput.remove();
286 sidebarReadyPromise = null;
292 OSM.Directions.engines = [];
294 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
295 if (location.protocol === "http:" || supportsHTTPS) {
296 engine.id = engine.provider + "_" + engine.mode;
297 OSM.Directions.engines.push(engine);