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