1 //= require ./directions-endpoint
2 //= require ./directions-route-output
4 //= require_tree ./directions
6 OSM.Directions = function (map) {
7 let controller = null; // the AbortController for the current route request if a route request is in progress
11 let scheduledRouteArguments = null;
13 const routeOutput = OSM.DirectionsRouteOutput(map);
15 const endpointDragCallback = function (dragging) {
16 if (!routeOutput.isVisible()) return;
17 if (dragging && !chosenEngine.draggable) return;
18 if (dragging && controller) return;
20 getRoute(false, !dragging);
22 const endpointChangeCallback = function () {
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)
31 const expiry = new Date();
32 expiry.setYear(expiry.getFullYear() + 10);
34 const modeGroup = $(".routing_modes");
35 const select = $("select.routing_engines");
37 $(".directions_form .reverse_directions").on("click", function () {
38 const coordFrom = endpoints[0].latlng,
39 coordTo = endpoints[1].latlng;
43 routeFrom = coordFrom.lat + "," + coordFrom.lng;
46 routeTo = coordTo.lat + "," + coordTo.lng;
48 endpoints[0].swapCachedReverseGeocodes(endpoints[1]);
50 OSM.router.route("/directions?" + new URLSearchParams({
51 route: routeTo + ";" + routeFrom
55 $(".directions_form .btn-close").on("click", function (e) {
57 $(".describe_location").toggle(!endpoints[1].value);
58 $(".search_form input[name='query']").val(endpoints[1].value);
59 OSM.router.route("/" + OSM.formatHash(map));
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;
69 .filter(engine => engine.provider === chosenEngine.provider)
70 .map(engine => engine.mode);
73 .prop("disabled", function () {
74 return !modes.includes(this.id);
76 .prop("checked", function () {
77 return this.id === chosenEngine.mode;
80 const providers = engines
81 .filter(engine => engine.mode === chosenEngine.mode)
82 .map(engine => engine.provider);
84 .find("option[value]")
85 .prop("disabled", function () {
86 return !providers.includes(this.value);
88 select.val(chosenEngine.provider);
91 function getRoute(...routeArguments) {
92 if ($("#directions_content").length) {
93 getScheduledRoute(...routeArguments);
95 scheduledRouteArguments = routeArguments;
99 function getScheduledRoute(fitRoute, reportErrors) {
100 // Cancel any route that is already in progress
101 if (controller) controller.abort();
103 const points = endpoints.map(p => p.latlng);
105 if (!points[0] || !points[1]) return;
106 $("header").addClass("closed");
108 OSM.router.replace("/directions?" + new URLSearchParams({
109 engine: chosenEngine.id,
110 route: points.map(p => `${p.lat},${p.lng}`).join(";")
113 // copy loading item to sidebar and display it. we copy it, rather than
114 // just using it in-place and replacing it in case it has to be used
116 $("#directions_content").html($(".directions_form .loader_copy").html());
117 map.setSidebarOverlaid(false);
118 controller = new AbortController();
119 chosenEngine.getRoute(points, controller.signal).then(function (route) {
120 routeOutput.write($("#directions_content"), route);
124 }).catch(function () {
125 routeOutput.remove($("#directions_content"));
127 $("#directions_content").html("<div class=\"alert alert-danger\">" + OSM.i18n.t("javascripts.directions.errors.no_route") + "</div>");
129 }).finally(function () {
134 function closeButtonListener(e) {
136 routeOutput.remove($("#directions_content"));
137 map.setSidebarOverlaid(true);
138 // TODO: collapse width of sidebar back to previous
141 setEngine("fossgis_osrm_car");
142 setEngine(Cookies.get("_osm_directions_engine"));
144 modeGroup.on("change", "input[name='modes']", function (e) {
145 setEngine(chosenEngine.provider + "_" + e.target.id);
146 Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
147 getRoute(true, true);
150 select.on("change", function (e) {
151 setEngine(e.target.value + "_" + chosenEngine.mode);
152 Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
153 getRoute(true, true);
156 $(".directions_form").on("submit", function (e) {
158 getRoute(true, true);
161 $(".routing_marker_column img").on("dragstart", function (e) {
162 const dt = e.originalEvent.dataTransfer;
163 dt.effectAllowed = "move";
164 const dragData = { type: $(this).data("type") };
165 dt.setData("text", JSON.stringify(dragData));
166 if (dt.setDragImage) {
167 const img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
168 dt.setDragImage(img.get(0), 12, 21);
172 function sendstartinglocation({ latlng: { lat, lng } }) {
173 map.fire("startinglocation", { latlng: [lat, lng] });
176 function startingLocationListener({ latlng }) {
177 if (endpoints[0].value) return;
178 endpoints[0].setValue(latlng.join(", "));
181 map.on("locationfound", ({ latlng: { lat, lng } }) =>
182 lastLocation = [lat, lng]
183 ).on("locateactivate", () => {
184 map.once("startinglocation", startingLocationListener);
187 function initializeFromParams() {
188 const params = new URLSearchParams(location.search),
189 route = (params.get("route") || "").split(";");
191 if (params.has("engine")) setEngine(params.get("engine"));
193 endpoints[0].setValue(params.get("from") || route[0] || lastLocation.join(", "));
194 endpoints[1].setValue(params.get("to") || route[1] || "");
197 function enableListeners() {
198 $("#sidebar .sidebar-close-controls button").on("click", closeButtonListener);
200 $("#map").on("dragend dragover", function (e) {
204 $("#map").on("drop", function (e) {
206 const oe = e.originalEvent;
207 const dragData = JSON.parse(oe.dataTransfer.getData("text"));
208 const type = dragData.type;
209 const pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
211 const ll = map.containerPointToLatLng(pt);
212 const llWithPrecision = OSM.cropLocation(ll, map.getZoom());
213 endpoints[type === "from" ? 0 : 1].setValue(llWithPrecision.join(", "));
216 map.on("locationfound", sendstartinglocation);
218 endpoints[0].enableListeners();
219 endpoints[1].enableListeners();
224 page.pushstate = page.popstate = function () {
227 if ($("#directions_content").length) return;
229 OSM.loadSidebarContent("/directions", () => {
230 if (scheduledRouteArguments) {
231 getScheduledRoute(...scheduledRouteArguments);
232 scheduledRouteArguments = null;
236 map.setSidebarOverlaid(!endpoints[0].latlng || !endpoints[1].latlng);
239 page.load = function () {
240 initializeFromParams();
242 $(".search_form").hide();
243 $(".directions_form").show();
247 map.setSidebarOverlaid(!endpoints[0].latlng || !endpoints[1].latlng);
250 page.unload = function () {
251 $(".search_form").show();
252 $(".directions_form").hide();
254 $("#sidebar .sidebar-close-controls button").off("click", closeButtonListener);
255 $("#map").off("dragend dragover drop");
256 map.off("locationfound", sendstartinglocation);
258 endpoints[0].disableListeners();
259 endpoints[1].disableListeners();
261 endpoints[0].clearValue();
262 endpoints[1].clearValue();
264 routeOutput.remove($("#directions_content"));
266 scheduledRouteArguments = null;
272 OSM.Directions.engines = [];
274 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
275 if (location.protocol === "http:" || supportsHTTPS) {
276 engine.id = engine.provider + "_" + engine.mode;
277 OSM.Directions.engines.push(engine);