]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/directions.js
Fix header button height
[rails.git] / app / assets / javascripts / index / directions.js
1 //= require ./directions-endpoint
2 //= require ./directions-route-output
3 //= require_self
4 //= require_tree ./directions
5
6 OSM.Directions = function (map) {
7   let controller = null; // the AbortController for the current route request if a route request is in progress
8   let lastLocation = [];
9   let chosenEngine;
10
11   let sidebarReadyPromise = null;
12
13   const routeOutput = OSM.DirectionsRouteOutput(map);
14
15   const endpointDragCallback = function (dragging) {
16     if (!routeOutput.isVisible()) return;
17     if (dragging && !chosenEngine.draggable) return;
18     if (dragging && controller) return;
19
20     getRoute(false, !dragging);
21   };
22
23   const endpoints = [
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)
26   ];
27
28   const expires = new Date();
29
30   expires.setFullYear(expires.getFullYear() + 10);
31
32   const modeGroup = $(".routing_modes");
33   const select = $("select#routing_engines");
34
35   $(".directions_form .reverse_directions").on("click", function () {
36     const coordFrom = endpoints[0].latlng,
37           coordTo = endpoints[1].latlng;
38     let routeFrom = "",
39         routeTo = "";
40
41     if (coordFrom) {
42       routeFrom = coordFrom.lat + "," + coordFrom.lng;
43     }
44
45     if (coordTo) {
46       routeTo = coordTo.lat + "," + coordTo.lng;
47     }
48
49     endpoints[0].swapCachedReverseGeocodes(endpoints[1]);
50
51     OSM.router.route("/directions?" + new URLSearchParams({
52       route: routeTo + ";" + routeFrom
53     }));
54   });
55
56   $(".directions_form .btn-close").on("click", function (e) {
57     e.preventDefault();
58     $(".search_form input[name='query']").val(endpoints[1].value);
59     OSM.router.route("/" + OSM.formatHash(map));
60   });
61
62   function setEngine(id) {
63     const engines = OSM.Directions.engines;
64     const desired = engines.find(engine => engine.id === id);
65
66     if (!desired || (chosenEngine && chosenEngine.id === id)) return;
67
68     chosenEngine = desired;
69
70     const modes = engines
71       .filter(engine => engine.provider === chosenEngine.provider)
72       .map(engine => engine.mode);
73
74     modeGroup
75       .find("input[id]")
76       .prop("disabled", function () {
77         return !modes.includes(this.value);
78       })
79       .prop("checked", function () {
80         return this.value === chosenEngine.mode;
81       });
82
83     const providers = engines
84       .filter(engine => engine.mode === chosenEngine.mode)
85       .map(engine => engine.provider);
86
87     select
88       .find("option[value]")
89       .prop("disabled", function () {
90         return !providers.includes(this.value);
91       });
92     select.val(chosenEngine.provider);
93   }
94
95   function getRoute(fitRoute = true, reportErrors = true) {
96     // Cancel any route that is already in progress
97     if (controller) controller.abort();
98
99     const points = endpoints.map(p => p.latlng);
100
101     if (!points[0] || !points[1]) return;
102
103     $("header").addClass("closed");
104
105     OSM.router.replace("/directions?" + new URLSearchParams({
106       engine: chosenEngine.id,
107       route: points.map(p => `${p.lat},${p.lng}`).join(";")
108     }));
109
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);
119
120       if (fitRoute) {
121         routeOutput.fit();
122       }
123     }).catch(async function (error) {
124       if (error.name === "AbortError") return;
125
126       await sidebarLoaded();
127       routeOutput.remove();
128
129       if (reportErrors) {
130         $("#directions_error")
131           .prop("hidden", false)
132           .html("<div class=\"alert alert-danger\">" + OSM.i18n.t("javascripts.directions.errors.no_route") + "</div>");
133       }
134     }).finally(function () {
135       $("#directions_loader").prop("hidden", true);
136       controller = null;
137     });
138   }
139
140   function closeButtonListener(e) {
141     e.stopPropagation();
142     routeOutput.remove();
143     sidebarReadyPromise = null;
144     map.setSidebarOverlaid(true);
145   }
146
147   setEngine("fossgis_osrm_car");
148   setEngine(OSM.cookies.get("_osm_directions_engine"));
149
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 });
153     getRoute();
154   });
155
156   select.on("change", function (e) {
157     setEngine(e.target.value + "_" + chosenEngine.mode);
158     OSM.cookies.set("_osm_directions_engine", chosenEngine.id, { expires });
159     getRoute();
160   });
161
162   $(".directions_form").on("submit", function (e) {
163     e.preventDefault();
164     getRoute();
165   });
166
167   $(".routing_marker_column span").on("dragstart", function (e) {
168     const dt = e.originalEvent.dataTransfer;
169
170     dt.effectAllowed = "move";
171
172     const jqthis = $(this);
173
174     dt.setData("text", JSON.stringify(jqthis.data()));
175
176     if (dt.setDragImage) {
177       const img = jqthis.clone()
178         .appendTo(document.body);
179
180       img.find("svg")
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);
185     }
186   });
187
188   function sendstartinglocation({ latlng: { lat, lng } }) {
189     map.fire("startinglocation", { latlng: [lat, lng] });
190   }
191
192   function startingLocationListener({ latlng }) {
193     if (endpoints[0].value) return;
194
195     endpoints[0].setValue(latlng.join(", "));
196   }
197
198   map.on("locationfound", ({ latlng: { lat, lng } }) =>
199     lastLocation = [lat, lng]
200   ).on("locateactivate", () => {
201     map.once("startinglocation", startingLocationListener);
202   });
203
204   function initializeFromParams() {
205     const params = new URLSearchParams(location.search),
206           route = (params.get("route") || "").split(";");
207
208     if (params.has("engine")) setEngine(params.get("engine"));
209
210     endpoints[0].setValue(params.get("from") || route[0] || lastLocation.join(", "));
211     endpoints[1].setValue(params.get("to") || route[1] || "");
212   }
213
214   function enableListeners() {
215     $("#sidebar .sidebar-close-controls button").on("click", closeButtonListener);
216
217     $("#map").on("dragend dragover", function (e) {
218       e.preventDefault();
219     });
220
221     $("#map").on("drop", function (e) {
222       e.preventDefault();
223
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
228
229       pt.y += 20;
230
231       const ll = map.containerPointToLatLng(pt);
232       const llWithPrecision = OSM.cropLocation(ll, map.getZoom());
233
234       endpoints[type === "from" ? 0 : 1].setValue(llWithPrecision.join(", "));
235     });
236
237     map.on("locationfound", sendstartinglocation);
238
239     endpoints[0].enableListeners();
240     endpoints[1].enableListeners();
241   }
242
243   const page = {};
244
245   function sidebarLoaded() {
246     if ($("#directions_route").length) {
247       sidebarReadyPromise = null;
248
249       return Promise.resolve();
250     }
251
252     if (sidebarReadyPromise) return sidebarReadyPromise;
253
254     sidebarReadyPromise = new Promise(resolve => OSM.loadSidebarContent("/directions", resolve));
255
256     return sidebarReadyPromise;
257   }
258
259   page.pushstate = page.popstate = page.load = function () {
260     initializeFromParams();
261
262     $(".search_form").hide();
263     $(".directions_form").show();
264
265     sidebarLoaded().then(enableListeners);
266
267     map.setSidebarOverlaid(!endpoints[0].latlng || !endpoints[1].latlng);
268   };
269
270   page.unload = function () {
271     $(".search_form").show();
272     $(".directions_form").hide();
273
274     $("#sidebar .sidebar-close-controls button").off("click", closeButtonListener);
275     $("#map").off("dragend dragover drop");
276     map.off("locationfound", sendstartinglocation);
277
278     endpoints[0].disableListeners();
279     endpoints[1].disableListeners();
280
281     endpoints[0].clearValue();
282     endpoints[1].clearValue();
283
284     routeOutput.remove();
285
286     sidebarReadyPromise = null;
287   };
288
289   return page;
290 };
291
292 OSM.Directions.engines = [];
293
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);
298   }
299 };