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 const routeOutput = OSM.DirectionsRouteOutput(map);
13 const endpointDragCallback = function (dragging) {
14 if (!routeOutput.isVisible()) return;
15 if (dragging && !chosenEngine.draggable) return;
16 if (dragging && controller) return;
18 getRoute(false, !dragging);
20 const endpointChangeCallback = function () {
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)
29 const expiry = new Date();
30 expiry.setYear(expiry.getFullYear() + 10);
32 const modeGroup = $(".routing_modes");
33 const select = $("select.routing_engines");
35 $(".directions_form .reverse_directions").on("click", function () {
36 const coordFrom = endpoints[0].latlng,
37 coordTo = endpoints[1].latlng;
41 routeFrom = coordFrom.lat + "," + coordFrom.lng;
44 routeTo = coordTo.lat + "," + coordTo.lng;
46 endpoints[0].swapCachedReverseGeocodes(endpoints[1]);
48 OSM.router.route("/directions?" + new URLSearchParams({
49 route: routeTo + ";" + routeFrom
53 $(".directions_form .btn-close").on("click", function (e) {
55 $(".describe_location").toggle(!endpoints[1].value);
56 $(".search_form input[name='query']").val(endpoints[1].value);
57 OSM.router.route("/" + OSM.formatHash(map));
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;
67 .filter(engine => engine.provider === chosenEngine.provider)
68 .map(engine => engine.mode);
71 .prop("disabled", function () {
72 return !modes.includes(this.id);
74 .prop("checked", function () {
75 return this.id === chosenEngine.mode;
78 const providers = engines
79 .filter(engine => engine.mode === chosenEngine.mode)
80 .map(engine => engine.provider);
82 .find("option[value]")
83 .prop("disabled", function () {
84 return !providers.includes(this.value);
86 select.val(chosenEngine.provider);
89 function getRoute(fitRoute, reportErrors) {
90 // Cancel any route that is already in progress
91 if (controller) controller.abort();
93 const points = endpoints.map(p => p.latlng);
95 if (!points[0] || !points[1]) return;
96 $("header").addClass("closed");
98 OSM.router.replace("/directions?" + new URLSearchParams({
99 engine: chosenEngine.id,
100 route: points.map(p => `${p.lat},${p.lng}`).join(";")
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
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);
114 }).catch(function () {
115 routeOutput.remove($("#directions_content"));
117 $("#directions_content").html("<div class=\"alert alert-danger\">" + OSM.i18n.t("javascripts.directions.errors.no_route") + "</div>");
119 }).finally(function () {
124 function closeButtonListener(e) {
126 routeOutput.remove($("#directions_content"));
127 map.setSidebarOverlaid(true);
128 // TODO: collapse width of sidebar back to previous
131 setEngine("fossgis_osrm_car");
132 setEngine(Cookies.get("_osm_directions_engine"));
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);
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);
146 $(".directions_form").on("submit", function (e) {
148 getRoute(true, true);
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);
162 function sendstartinglocation({ latlng: { lat, lng } }) {
163 map.fire("startinglocation", { latlng: [lat, lng] });
166 function startingLocationListener({ latlng }) {
167 if (endpoints[0].value) return;
168 endpoints[0].setValue(latlng.join(", "));
171 map.on("locationfound", ({ latlng: { lat, lng } }) =>
172 lastLocation = [lat, lng]
173 ).on("locateactivate", () => {
174 map.once("startinglocation", startingLocationListener);
177 function initializeFromParams() {
178 const params = new URLSearchParams(location.search),
179 route = (params.get("route") || "").split(";");
181 if (params.has("engine")) setEngine(params.get("engine"));
183 endpoints[0].setValue(params.get("from") || route[0] || lastLocation.join(", "));
184 endpoints[1].setValue(params.get("to") || route[1] || "");
187 function enableListeners() {
188 $("#sidebar .sidebar-close-controls button").on("click", closeButtonListener);
190 $("#map").on("dragend dragover", function (e) {
194 $("#map").on("drop", function (e) {
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
201 const ll = map.containerPointToLatLng(pt);
202 const llWithPrecision = OSM.cropLocation(ll, map.getZoom());
203 endpoints[type === "from" ? 0 : 1].setValue(llWithPrecision.join(", "));
206 map.on("locationfound", sendstartinglocation);
208 endpoints[0].enableListeners();
209 endpoints[1].enableListeners();
214 page.pushstate = page.popstate = function () {
215 if ($("#directions_content").length) {
218 initializeFromParams();
220 $(".search_form").hide();
221 $(".directions_form").show();
223 OSM.loadSidebarContent("/directions", enableListeners);
225 map.setSidebarOverlaid(!endpoints[0].latlng || !endpoints[1].latlng);
229 page.load = function () {
230 initializeFromParams();
232 $(".search_form").hide();
233 $(".directions_form").show();
237 map.setSidebarOverlaid(!endpoints[0].latlng || !endpoints[1].latlng);
240 page.unload = function () {
241 $(".search_form").show();
242 $(".directions_form").hide();
244 $("#sidebar .sidebar-close-controls button").off("click", closeButtonListener);
245 $("#map").off("dragend dragover drop");
246 map.off("locationfound", sendstartinglocation);
248 endpoints[0].disableListeners();
249 endpoints[1].disableListeners();
251 endpoints[0].clearValue();
252 endpoints[1].clearValue();
254 routeOutput.remove($("#directions_content"));
260 OSM.Directions.engines = [];
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);