]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/directions.js
Localisation updates from https://translatewiki.net.
[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: "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(fitRoute, reportErrors) {
92     // Cancel any route that is already in progress
93     if (controller) controller.abort();
94
95     const points = endpoints.map(p => p.latlng);
96
97     if (!points[0] || !points[1]) return;
98     $("header").addClass("closed");
99
100     OSM.router.replace("/directions?" + new URLSearchParams({
101       engine: chosenEngine.id,
102       route: points.map(p => `${p.lat},${p.lng}`).join(";")
103     }));
104
105     $("#directions_loader").prop("hidden", false);
106     $("#directions_error").prop("hidden", true).empty();
107     $("#directions_route").prop("hidden", true);
108     map.setSidebarOverlaid(false);
109     controller = new AbortController();
110     chosenEngine.getRoute(points, controller.signal).then(async function (route) {
111       await sidebarLoaded();
112       $("#directions_route").prop("hidden", false);
113       routeOutput.write(route);
114       if (fitRoute) {
115         routeOutput.fit();
116       }
117     }).catch(async function (error) {
118       if (error.name === "AbortError") return;
119       await sidebarLoaded();
120       routeOutput.remove();
121       if (reportErrors) {
122         $("#directions_error")
123           .prop("hidden", false)
124           .html("<div class=\"alert alert-danger\">" + OSM.i18n.t("javascripts.directions.errors.no_route") + "</div>");
125       }
126     }).finally(function () {
127       $("#directions_loader").prop("hidden", true);
128       controller = null;
129     });
130   }
131
132   function closeButtonListener(e) {
133     e.stopPropagation();
134     routeOutput.remove();
135     sidebarReadyPromise = null;
136     map.setSidebarOverlaid(true);
137     // TODO: collapse width of sidebar back to previous
138   }
139
140   setEngine("fossgis_osrm_car");
141   setEngine(Cookies.get("_osm_directions_engine"));
142
143   modeGroup.on("change", "input[name='modes']", function (e) {
144     setEngine(chosenEngine.provider + "_" + e.target.id);
145     Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
146     getRoute(true, true);
147   });
148
149   select.on("change", function (e) {
150     setEngine(e.target.value + "_" + chosenEngine.mode);
151     Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
152     getRoute(true, true);
153   });
154
155   $(".directions_form").on("submit", function (e) {
156     e.preventDefault();
157     getRoute(true, true);
158   });
159
160   $(".routing_marker_column img").on("dragstart", function (e) {
161     const dt = e.originalEvent.dataTransfer;
162     dt.effectAllowed = "move";
163     const dragData = { type: $(this).data("type") };
164     dt.setData("text", JSON.stringify(dragData));
165     if (dt.setDragImage) {
166       const img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
167       dt.setDragImage(img.get(0), 12, 21);
168     }
169   });
170
171   function sendstartinglocation({ latlng: { lat, lng } }) {
172     map.fire("startinglocation", { latlng: [lat, lng] });
173   }
174
175   function startingLocationListener({ latlng }) {
176     if (endpoints[0].value) return;
177     endpoints[0].setValue(latlng.join(", "));
178   }
179
180   map.on("locationfound", ({ latlng: { lat, lng } }) =>
181     lastLocation = [lat, lng]
182   ).on("locateactivate", () => {
183     map.once("startinglocation", startingLocationListener);
184   });
185
186   function initializeFromParams() {
187     const params = new URLSearchParams(location.search),
188           route = (params.get("route") || "").split(";");
189
190     if (params.has("engine")) setEngine(params.get("engine"));
191
192     endpoints[0].setValue(params.get("from") || route[0] || lastLocation.join(", "));
193     endpoints[1].setValue(params.get("to") || route[1] || "");
194   }
195
196   function enableListeners() {
197     $("#sidebar .sidebar-close-controls button").on("click", closeButtonListener);
198
199     $("#map").on("dragend dragover", function (e) {
200       e.preventDefault();
201     });
202
203     $("#map").on("drop", function (e) {
204       e.preventDefault();
205       const oe = e.originalEvent;
206       const dragData = JSON.parse(oe.dataTransfer.getData("text"));
207       const type = dragData.type;
208       const pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
209       pt.y += 20;
210       const ll = map.containerPointToLatLng(pt);
211       const llWithPrecision = OSM.cropLocation(ll, map.getZoom());
212       endpoints[type === "from" ? 0 : 1].setValue(llWithPrecision.join(", "));
213     });
214
215     map.on("locationfound", sendstartinglocation);
216
217     endpoints[0].enableListeners();
218     endpoints[1].enableListeners();
219   }
220
221   const page = {};
222
223   function sidebarLoaded() {
224     if ($("#directions_route").length) {
225       sidebarReadyPromise = null;
226       return Promise.resolve();
227     }
228     if (sidebarReadyPromise) return sidebarReadyPromise;
229     sidebarReadyPromise = new Promise(resolve => OSM.loadSidebarContent("/directions", resolve));
230     return sidebarReadyPromise;
231   }
232
233   page.pushstate = page.popstate = page.load = function () {
234     initializeFromParams();
235
236     $(".search_form").hide();
237     $(".directions_form").show();
238
239     sidebarLoaded().then(enableListeners);
240
241     map.setSidebarOverlaid(!endpoints[0].latlng || !endpoints[1].latlng);
242   };
243
244   page.unload = function () {
245     $(".search_form").show();
246     $(".directions_form").hide();
247
248     $("#sidebar .sidebar-close-controls button").off("click", closeButtonListener);
249     $("#map").off("dragend dragover drop");
250     map.off("locationfound", sendstartinglocation);
251
252     endpoints[0].disableListeners();
253     endpoints[1].disableListeners();
254
255     endpoints[0].clearValue();
256     endpoints[1].clearValue();
257
258     routeOutput.remove();
259
260     sidebarReadyPromise = null;
261   };
262
263   return page;
264 };
265
266 OSM.Directions.engines = [];
267
268 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
269   if (location.protocol === "http:" || supportsHTTPS) {
270     engine.id = engine.provider + "_" + engine.mode;
271     OSM.Directions.engines.push(engine);
272   }
273 };