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 $("#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);
114 }).catch(function () {
115 routeOutput.remove($("#directions_route"));
117 $("#directions_error")
118 .prop("hidden", false)
119 .html("<div class=\"alert alert-danger\">" + OSM.i18n.t("javascripts.directions.errors.no_route") + "</div>");
121 }).finally(function () {
122 $("#directions_loader").prop("hidden", true);
127 function closeButtonListener(e) {
129 routeOutput.remove($("#directions_route"));
130 map.setSidebarOverlaid(true);
131 // TODO: collapse width of sidebar back to previous
134 setEngine("fossgis_osrm_car");
135 setEngine(Cookies.get("_osm_directions_engine"));
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);
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);
149 $(".directions_form").on("submit", function (e) {
151 getRoute(true, true);
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);
165 function sendstartinglocation({ latlng: { lat, lng } }) {
166 map.fire("startinglocation", { latlng: [lat, lng] });
169 function startingLocationListener({ latlng }) {
170 if (endpoints[0].value) return;
171 endpoints[0].setValue(latlng.join(", "));
174 map.on("locationfound", ({ latlng: { lat, lng } }) =>
175 lastLocation = [lat, lng]
176 ).on("locateactivate", () => {
177 map.once("startinglocation", startingLocationListener);
180 function initializeFromParams() {
181 const params = new URLSearchParams(location.search),
182 route = (params.get("route") || "").split(";");
184 if (params.has("engine")) setEngine(params.get("engine"));
186 endpoints[0].setValue(params.get("from") || route[0] || lastLocation.join(", "));
187 endpoints[1].setValue(params.get("to") || route[1] || "");
190 function enableListeners() {
191 $("#sidebar .sidebar-close-controls button").on("click", closeButtonListener);
193 $("#map").on("dragend dragover", function (e) {
197 $("#map").on("drop", function (e) {
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
204 const ll = map.containerPointToLatLng(pt);
205 const llWithPrecision = OSM.cropLocation(ll, map.getZoom());
206 endpoints[type === "from" ? 0 : 1].setValue(llWithPrecision.join(", "));
209 map.on("locationfound", sendstartinglocation);
211 endpoints[0].enableListeners();
212 endpoints[1].enableListeners();
217 page.pushstate = page.popstate = function () {
218 if ($("#directions_route").length) {
221 initializeFromParams();
223 $(".search_form").hide();
224 $(".directions_form").show();
226 OSM.loadSidebarContent("/directions", enableListeners);
228 map.setSidebarOverlaid(!endpoints[0].latlng || !endpoints[1].latlng);
232 page.load = function () {
233 initializeFromParams();
235 $(".search_form").hide();
236 $(".directions_form").show();
240 map.setSidebarOverlaid(!endpoints[0].latlng || !endpoints[1].latlng);
243 page.unload = function () {
244 $(".search_form").show();
245 $(".directions_form").hide();
247 $("#sidebar .sidebar-close-controls button").off("click", closeButtonListener);
248 $("#map").off("dragend dragover drop");
249 map.off("locationfound", sendstartinglocation);
251 endpoints[0].disableListeners();
252 endpoints[1].disableListeners();
254 endpoints[0].clearValue();
255 endpoints[1].clearValue();
257 routeOutput.remove($("#directions_route"));
263 OSM.Directions.engines = [];
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);