]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/directions.js
Merge remote-tracking branch 'upstream/pull/5915'
[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 scheduledRouteArguments = 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: "MARKER_GREEN" }, endpointDragCallback, endpointChangeCallback),
28     OSM.DirectionsEndpoint(map, $("input[name='route_to']"), { icon: "MARKER_RED" }, endpointDragCallback, endpointChangeCallback)
29   ];
30
31   const expiry = new Date();
32   expiry.setYear(expiry.getFullYear() + 10);
33
34   const modeGroup = $(".routing_modes");
35   const select = $("select.routing_engines");
36
37   $(".directions_form .reverse_directions").on("click", function () {
38     const coordFrom = endpoints[0].latlng,
39           coordTo = endpoints[1].latlng;
40     let routeFrom = "",
41         routeTo = "";
42     if (coordFrom) {
43       routeFrom = coordFrom.lat + "," + coordFrom.lng;
44     }
45     if (coordTo) {
46       routeTo = coordTo.lat + "," + coordTo.lng;
47     }
48     endpoints[0].swapCachedReverseGeocodes(endpoints[1]);
49
50     OSM.router.route("/directions?" + new URLSearchParams({
51       route: routeTo + ";" + routeFrom
52     }));
53   });
54
55   $(".directions_form .btn-close").on("click", function (e) {
56     e.preventDefault();
57     $(".describe_location").toggle(!endpoints[1].value);
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     if (!desired || (chosenEngine && chosenEngine.id === id)) return;
66     chosenEngine = desired;
67
68     const modes = engines
69       .filter(engine => engine.provider === chosenEngine.provider)
70       .map(engine => engine.mode);
71     modeGroup
72       .find("input[id]")
73       .prop("disabled", function () {
74         return !modes.includes(this.id);
75       })
76       .prop("checked", function () {
77         return this.id === chosenEngine.mode;
78       });
79
80     const providers = engines
81       .filter(engine => engine.mode === chosenEngine.mode)
82       .map(engine => engine.provider);
83     select
84       .find("option[value]")
85       .prop("disabled", function () {
86         return !providers.includes(this.value);
87       });
88     select.val(chosenEngine.provider);
89   }
90
91   function getRoute(...routeArguments) {
92     if ($("#directions_route").length) {
93       getScheduledRoute(...routeArguments);
94     } else {
95       scheduledRouteArguments = routeArguments;
96     }
97   }
98
99   function getScheduledRoute(fitRoute, reportErrors) {
100     // Cancel any route that is already in progress
101     if (controller) controller.abort();
102
103     const points = endpoints.map(p => p.latlng);
104
105     if (!points[0] || !points[1]) return;
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(function (route) {
119       $("#directions_route").prop("hidden", false);
120       routeOutput.write(route);
121       if (fitRoute) {
122         routeOutput.fit();
123       }
124     }).catch(function () {
125       routeOutput.remove();
126       if (reportErrors) {
127         $("#directions_error")
128           .prop("hidden", false)
129           .html("<div class=\"alert alert-danger\">" + OSM.i18n.t("javascripts.directions.errors.no_route") + "</div>");
130       }
131     }).finally(function () {
132       $("#directions_loader").prop("hidden", true);
133       controller = null;
134     });
135   }
136
137   function closeButtonListener(e) {
138     e.stopPropagation();
139     routeOutput.remove();
140     map.setSidebarOverlaid(true);
141     // TODO: collapse width of sidebar back to previous
142   }
143
144   setEngine("fossgis_osrm_car");
145   setEngine(Cookies.get("_osm_directions_engine"));
146
147   modeGroup.on("change", "input[name='modes']", function (e) {
148     setEngine(chosenEngine.provider + "_" + e.target.id);
149     Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
150     getRoute(true, true);
151   });
152
153   select.on("change", function (e) {
154     setEngine(e.target.value + "_" + chosenEngine.mode);
155     Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
156     getRoute(true, true);
157   });
158
159   $(".directions_form").on("submit", function (e) {
160     e.preventDefault();
161     getRoute(true, true);
162   });
163
164   $(".routing_marker_column img").on("dragstart", function (e) {
165     const dt = e.originalEvent.dataTransfer;
166     dt.effectAllowed = "move";
167     const dragData = { type: $(this).data("type") };
168     dt.setData("text", JSON.stringify(dragData));
169     if (dt.setDragImage) {
170       const img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
171       dt.setDragImage(img.get(0), 12, 21);
172     }
173   });
174
175   function sendstartinglocation({ latlng: { lat, lng } }) {
176     map.fire("startinglocation", { latlng: [lat, lng] });
177   }
178
179   function startingLocationListener({ latlng }) {
180     if (endpoints[0].value) return;
181     endpoints[0].setValue(latlng.join(", "));
182   }
183
184   map.on("locationfound", ({ latlng: { lat, lng } }) =>
185     lastLocation = [lat, lng]
186   ).on("locateactivate", () => {
187     map.once("startinglocation", startingLocationListener);
188   });
189
190   function initializeFromParams() {
191     const params = new URLSearchParams(location.search),
192           route = (params.get("route") || "").split(";");
193
194     if (params.has("engine")) setEngine(params.get("engine"));
195
196     endpoints[0].setValue(params.get("from") || route[0] || lastLocation.join(", "));
197     endpoints[1].setValue(params.get("to") || route[1] || "");
198   }
199
200   function enableListeners() {
201     $("#sidebar .sidebar-close-controls button").on("click", closeButtonListener);
202
203     $("#map").on("dragend dragover", function (e) {
204       e.preventDefault();
205     });
206
207     $("#map").on("drop", function (e) {
208       e.preventDefault();
209       const oe = e.originalEvent;
210       const dragData = JSON.parse(oe.dataTransfer.getData("text"));
211       const type = dragData.type;
212       const pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
213       pt.y += 20;
214       const ll = map.containerPointToLatLng(pt);
215       const llWithPrecision = OSM.cropLocation(ll, map.getZoom());
216       endpoints[type === "from" ? 0 : 1].setValue(llWithPrecision.join(", "));
217     });
218
219     map.on("locationfound", sendstartinglocation);
220
221     endpoints[0].enableListeners();
222     endpoints[1].enableListeners();
223   }
224
225   const page = {};
226
227   page.pushstate = page.popstate = function () {
228     page.load();
229
230     if ($("#directions_route").length) return;
231
232     OSM.loadSidebarContent("/directions", () => {
233       if (scheduledRouteArguments) {
234         getScheduledRoute(...scheduledRouteArguments);
235         scheduledRouteArguments = null;
236       }
237     });
238
239     map.setSidebarOverlaid(!endpoints[0].latlng || !endpoints[1].latlng);
240   };
241
242   page.load = function () {
243     initializeFromParams();
244
245     $(".search_form").hide();
246     $(".directions_form").show();
247
248     enableListeners();
249
250     map.setSidebarOverlaid(!endpoints[0].latlng || !endpoints[1].latlng);
251   };
252
253   page.unload = function () {
254     $(".search_form").show();
255     $(".directions_form").hide();
256
257     $("#sidebar .sidebar-close-controls button").off("click", closeButtonListener);
258     $("#map").off("dragend dragover drop");
259     map.off("locationfound", sendstartinglocation);
260
261     endpoints[0].disableListeners();
262     endpoints[1].disableListeners();
263
264     endpoints[0].clearValue();
265     endpoints[1].clearValue();
266
267     routeOutput.remove();
268
269     scheduledRouteArguments = null;
270   };
271
272   return page;
273 };
274
275 OSM.Directions.engines = [];
276
277 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
278   if (location.protocol === "http:" || supportsHTTPS) {
279     engine.id = engine.provider + "_" + engine.mode;
280     OSM.Directions.engines.push(engine);
281   }
282 };