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: "start", color: "var(--marker-green)" }, endpointDragCallback, endpointChangeCallback),
28 OSM.DirectionsEndpoint(map, $("input[name='route_to']"), { icon: "destination", color: "var(--marker-red)" }, endpointDragCallback, endpointChangeCallback)
31 const expires = new Date();
33 expires.setFullYear(expires.getFullYear() + 10);
35 const modeGroup = $(".routing_modes");
36 const select = $("select#routing_engines");
38 $(".directions_form .reverse_directions").on("click", function () {
39 const coordFrom = endpoints[0].latlng,
40 coordTo = endpoints[1].latlng;
45 routeFrom = coordFrom.lat + "," + coordFrom.lng;
49 routeTo = coordTo.lat + "," + coordTo.lng;
52 endpoints[0].swapCachedReverseGeocodes(endpoints[1]);
54 OSM.router.route("/directions?" + new URLSearchParams({
55 route: routeTo + ";" + routeFrom
59 $(".directions_form .btn-close").on("click", function (e) {
61 $(".search_form input[name='query']").val(endpoints[1].value);
62 OSM.router.route("/" + OSM.formatHash(map));
65 function setEngine(id) {
66 const engines = OSM.Directions.engines;
67 const desired = engines.find(engine => engine.id === id);
69 if (!desired || (chosenEngine && chosenEngine.id === id)) return;
71 chosenEngine = desired;
74 .filter(engine => engine.provider === chosenEngine.provider)
75 .map(engine => engine.mode);
79 .prop("disabled", function () {
80 return !modes.includes(this.value);
82 .prop("checked", function () {
83 return this.value === chosenEngine.mode;
86 const providers = engines
87 .filter(engine => engine.mode === chosenEngine.mode)
88 .map(engine => engine.provider);
91 .find("option[value]")
92 .prop("disabled", function () {
93 return !providers.includes(this.value);
95 select.val(chosenEngine.provider);
98 function getRoute(fitRoute, reportErrors) {
99 // Cancel any route that is already in progress
100 if (controller) controller.abort();
102 const points = endpoints.map(p => p.latlng);
104 if (!points[0] || !points[1]) return;
106 $("header").addClass("closed");
108 OSM.router.replace("/directions?" + new URLSearchParams({
109 engine: chosenEngine.id,
110 route: points.map(p => `${p.lat},${p.lng}`).join(";")
113 $("#directions_loader").prop("hidden", false);
114 $("#directions_error").prop("hidden", true).empty();
115 $("#directions_route").prop("hidden", true);
116 map.setSidebarOverlaid(false);
117 controller = new AbortController();
118 chosenEngine.getRoute(points, controller.signal).then(async function (route) {
119 await sidebarLoaded();
120 $("#directions_route").prop("hidden", false);
121 routeOutput.write(route);
126 }).catch(async function (error) {
127 if (error.name === "AbortError") return;
129 await sidebarLoaded();
130 routeOutput.remove();
133 $("#directions_error")
134 .prop("hidden", false)
135 .html("<div class=\"alert alert-danger\">" + OSM.i18n.t("javascripts.directions.errors.no_route") + "</div>");
137 }).finally(function () {
138 $("#directions_loader").prop("hidden", true);
143 function closeButtonListener(e) {
145 routeOutput.remove();
146 sidebarReadyPromise = null;
147 map.setSidebarOverlaid(true);
150 setEngine("fossgis_osrm_car");
151 setEngine(OSM.cookies.get("_osm_directions_engine"));
153 modeGroup.on("change", "input[name='modes']", function (e) {
154 setEngine(chosenEngine.provider + "_" + e.target.value);
155 OSM.cookies.set("_osm_directions_engine", chosenEngine.id, { expires });
156 getRoute(true, true);
159 select.on("change", function (e) {
160 setEngine(e.target.value + "_" + chosenEngine.mode);
161 OSM.cookies.set("_osm_directions_engine", chosenEngine.id, { expires });
162 getRoute(true, true);
165 $(".directions_form").on("submit", function (e) {
167 getRoute(true, true);
170 $(".routing_marker_column span").on("dragstart", function (e) {
171 const dt = e.originalEvent.dataTransfer;
173 dt.effectAllowed = "move";
175 const jqthis = $(this);
177 dt.setData("text", JSON.stringify(jqthis.data()));
179 if (dt.setDragImage) {
180 const img = jqthis.clone()
181 .appendTo(document.body);
184 .toggleClass("position-absolute bottom-100 end-100")
185 .attr({ width: "25", height: "40" });
186 dt.setDragImage(img.get(0), 12, 21);
187 setTimeout(() => img.remove(), 0);
191 function sendstartinglocation({ latlng: { lat, lng } }) {
192 map.fire("startinglocation", { latlng: [lat, lng] });
195 function startingLocationListener({ latlng }) {
196 if (endpoints[0].value) return;
198 endpoints[0].setValue(latlng.join(", "));
201 map.on("locationfound", ({ latlng: { lat, lng } }) =>
202 lastLocation = [lat, lng]
203 ).on("locateactivate", () => {
204 map.once("startinglocation", startingLocationListener);
207 function initializeFromParams() {
208 const params = new URLSearchParams(location.search),
209 route = (params.get("route") || "").split(";");
211 if (params.has("engine")) setEngine(params.get("engine"));
213 endpoints[0].setValue(params.get("from") || route[0] || lastLocation.join(", "));
214 endpoints[1].setValue(params.get("to") || route[1] || "");
217 function enableListeners() {
218 $("#sidebar .sidebar-close-controls button").on("click", closeButtonListener);
220 $("#map").on("dragend dragover", function (e) {
224 $("#map").on("drop", function (e) {
227 const oe = e.originalEvent;
228 const dragData = JSON.parse(oe.dataTransfer.getData("text"));
229 const type = dragData.type;
230 const pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
234 const ll = map.containerPointToLatLng(pt);
235 const llWithPrecision = OSM.cropLocation(ll, map.getZoom());
237 endpoints[type === "from" ? 0 : 1].setValue(llWithPrecision.join(", "));
240 map.on("locationfound", sendstartinglocation);
242 endpoints[0].enableListeners();
243 endpoints[1].enableListeners();
248 function sidebarLoaded() {
249 if ($("#directions_route").length) {
250 sidebarReadyPromise = null;
252 return Promise.resolve();
255 if (sidebarReadyPromise) return sidebarReadyPromise;
257 sidebarReadyPromise = new Promise(resolve => OSM.loadSidebarContent("/directions", resolve));
259 return sidebarReadyPromise;
262 page.pushstate = page.popstate = page.load = function () {
263 initializeFromParams();
265 $(".search_form").hide();
266 $(".directions_form").show();
268 sidebarLoaded().then(enableListeners);
270 map.setSidebarOverlaid(!endpoints[0].latlng || !endpoints[1].latlng);
273 page.unload = function () {
274 $(".search_form").show();
275 $(".directions_form").hide();
277 $("#sidebar .sidebar-close-controls button").off("click", closeButtonListener);
278 $("#map").off("dragend dragover drop");
279 map.off("locationfound", sendstartinglocation);
281 endpoints[0].disableListeners();
282 endpoints[1].disableListeners();
284 endpoints[0].clearValue();
285 endpoints[1].clearValue();
287 routeOutput.remove();
289 sidebarReadyPromise = null;
295 OSM.Directions.engines = [];
297 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
298 if (location.protocol === "http:" || supportsHTTPS) {
299 engine.id = engine.provider + "_" + engine.mode;
300 OSM.Directions.engines.push(engine);