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