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