1 //= require ./directions-endpoint
3 //= require_tree ./directions
6 OSM.Directions = function (map) {
7 var routeRequest = null; // jqXHR object of an ongoing route request or null
10 var popup = L.popup({ autoPanPadding: [100, 100] });
12 var polyline = L.polyline([], {
18 var highlight = L.polyline([], {
24 var endpointDragCallback = function (dragging) {
25 if (!map.hasLayer(polyline)) return;
26 if (dragging && !chosenEngine.draggable) return;
27 if (dragging && routeRequest) return;
29 getRoute(false, !dragging);
31 var endpointChangeCallback = function () {
36 OSM.DirectionsEndpoint(map, $("input[name='route_from']"), OSM.MARKER_GREEN, endpointDragCallback, endpointChangeCallback),
37 OSM.DirectionsEndpoint(map, $("input[name='route_to']"), OSM.MARKER_RED, endpointDragCallback, endpointChangeCallback)
40 var expiry = new Date();
41 expiry.setYear(expiry.getFullYear() + 10);
43 var engines = OSM.Directions.engines;
45 engines.sort(function (a, b) {
46 var localised_a = I18n.t("javascripts.directions.engines." + a.id),
47 localised_b = I18n.t("javascripts.directions.engines." + b.id);
48 return localised_a.localeCompare(localised_b);
51 var select = $("select.routing_engines");
53 engines.forEach(function (engine, i) {
54 select.append("<option value='" + i + "'>" + I18n.t("javascripts.directions.engines." + engine.id) + "</option>");
57 $(".directions_form .reverse_directions").on("click", function () {
58 var coordFrom = endpoints[0].latlng,
59 coordTo = endpoints[1].latlng,
63 routeFrom = coordFrom.lat + "," + coordFrom.lng;
66 routeTo = coordTo.lat + "," + coordTo.lng;
69 OSM.router.route("/directions?" + Qs.stringify({
70 from: $("#route_to").val(),
71 to: $("#route_from").val(),
72 route: routeTo + ";" + routeFrom
76 $(".directions_form .btn-close").on("click", function (e) {
78 $(".describe_location").toggle(!endpoints[0].value);
79 $(".search_form input[name='query']").val(endpoints[0].value);
80 OSM.router.route("/" + OSM.formatHash(map));
83 function formatDistance(m) {
85 return I18n.t("javascripts.directions.distance_m", { distance: Math.round(m) });
86 } else if (m < 10000) {
87 return I18n.t("javascripts.directions.distance_km", { distance: (m / 1000.0).toFixed(1) });
89 return I18n.t("javascripts.directions.distance_km", { distance: Math.round(m / 1000) });
93 function formatHeight(m) {
94 return I18n.t("javascripts.directions.distance_m", { distance: Math.round(m) });
97 function formatTime(s) {
98 var m = Math.round(s / 60);
99 var h = Math.floor(m / 60);
101 return h + ":" + (m < 10 ? "0" : "") + m;
104 function findEngine(id) {
105 return engines.findIndex(function (engine) {
106 return engine.id === id;
110 function setEngine(index) {
111 chosenEngine = engines[index];
115 function getRoute(fitRoute, reportErrors) {
116 // Cancel any route that is already in progress
117 if (routeRequest) routeRequest.abort();
119 var o = endpoints[0].latlng,
120 d = endpoints[1].latlng;
122 if (!o || !d) return;
123 $("header").addClass("closed");
125 var precision = OSM.zoomPrecision(map.getZoom());
127 OSM.router.replace("/directions?" + Qs.stringify({
128 engine: chosenEngine.id,
129 route: o.lat.toFixed(precision) + "," + o.lng.toFixed(precision) + ";" +
130 d.lat.toFixed(precision) + "," + d.lng.toFixed(precision)
133 // copy loading item to sidebar and display it. we copy it, rather than
134 // just using it in-place and replacing it in case it has to be used
136 $("#sidebar_content").html($(".directions_form .loader_copy").html());
137 map.setSidebarOverlaid(false);
139 routeRequest = chosenEngine.getRoute([o, d], function (err, route) {
143 map.removeLayer(polyline);
146 $("#sidebar_content").html("<div class=\"alert alert-danger\">" + I18n.t("javascripts.directions.errors.no_route") + "</div>");
153 .setLatLngs(route.line)
157 map.fitBounds(polyline.getBounds().pad(0.05));
160 var distanceText = $("<p>").append(
161 I18n.t("javascripts.directions.distance") + ": " + formatDistance(route.distance) + ". " +
162 I18n.t("javascripts.directions.time") + ": " + formatTime(route.time) + ".");
163 if (typeof route.ascend !== "undefined" && typeof route.descend !== "undefined") {
166 I18n.t("javascripts.directions.ascend") + ": " + formatHeight(route.ascend) + ". " +
167 I18n.t("javascripts.directions.descend") + ": " + formatHeight(route.descend) + ".");
170 var turnByTurnTable = $("<table class='table table-hover table-sm mb-3'>")
171 .append($("<tbody>"));
172 var directionsCloseButton = $("<button type='button' class='btn-close'>")
173 .attr("aria-label", I18n.t("javascripts.close"));
175 $("#sidebar_content")
178 $("<div class='d-flex'>").append(
179 $("<h2 class='flex-grow-1 text-break'>")
180 .text(I18n.t("javascripts.directions.directions")),
181 $("<div>").append(directionsCloseButton)),
187 route.steps.forEach(function (step) {
190 instruction = step[2],
196 } else if (dist < 200) {
197 dist = String(Math.round(dist / 10) * 10) + "m";
198 } else if (dist < 1500) {
199 dist = String(Math.round(dist / 100) * 100) + "m";
200 } else if (dist < 5000) {
201 dist = String(Math.round(dist / 100) / 10) + "km";
203 dist = String(Math.round(dist / 1000)) + "km";
206 var row = $("<tr class='turn'/>");
207 row.append("<td class='border-0'><div class='direction i" + direction + "'/></td> ");
208 row.append("<td>" + instruction);
209 row.append("<td class='distance text-body-secondary text-end'>" + dist);
211 row.on("click", function () {
214 .setContent("<p>" + instruction + "</p>")
218 row.hover(function () {
223 map.removeLayer(highlight);
226 turnByTurnTable.append(row);
229 $("#sidebar_content").append("<p class=\"text-center\">" +
230 I18n.t("javascripts.directions.instructions.courtesy", { link: chosenEngine.creditline }) +
233 directionsCloseButton.on("click", function () {
234 map.removeLayer(polyline);
235 $("#sidebar_content").html("");
236 map.setSidebarOverlaid(true);
237 // TODO: collapse width of sidebar back to previous
242 var chosenEngineIndex = findEngine("fossgis_osrm_car");
243 if (Cookies.get("_osm_directions_engine")) {
244 chosenEngineIndex = findEngine(Cookies.get("_osm_directions_engine"));
246 setEngine(chosenEngineIndex);
248 select.on("change", function (e) {
249 chosenEngine = engines[e.target.selectedIndex];
250 Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
251 getRoute(true, true);
254 $(".directions_form").on("submit", function (e) {
256 getRoute(true, true);
259 $(".routing_marker_column img").on("dragstart", function (e) {
260 var dt = e.originalEvent.dataTransfer;
261 dt.effectAllowed = "move";
262 var dragData = { type: $(this).data("type") };
263 dt.setData("text", JSON.stringify(dragData));
264 if (dt.setDragImage) {
265 var img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
266 dt.setDragImage(img.get(0), 12, 21);
272 page.pushstate = page.popstate = function () {
273 $(".search_form").hide();
274 $(".directions_form").show();
276 $("#map").on("dragend dragover", function (e) {
280 $("#map").on("drop", function (e) {
282 var oe = e.originalEvent;
283 var dragData = JSON.parse(oe.dataTransfer.getData("text"));
284 var type = dragData.type;
285 var pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
287 var ll = map.containerPointToLatLng(pt);
288 var precision = OSM.zoomPrecision(map.getZoom());
289 var value = ll.lat.toFixed(precision) + ", " + ll.lng.toFixed(precision);
290 endpoints[type === "from" ? 0 : 1].setValue(value, ll);
293 var params = Qs.parse(location.search.substring(1)),
294 route = (params.route || "").split(";"),
295 from = route[0] && L.latLng(route[0].split(",")),
296 to = route[1] && L.latLng(route[1].split(","));
299 var engineIndex = findEngine(params.engine);
301 if (engineIndex >= 0) {
302 setEngine(engineIndex);
306 endpoints[0].setValue(params.from || "", from);
307 endpoints[1].setValue(params.to || "", to);
309 map.setSidebarOverlaid(!from || !to);
312 page.load = function () {
316 page.unload = function () {
317 $(".search_form").show();
318 $(".directions_form").hide();
319 $("#map").off("dragend dragover drop");
323 .removeLayer(polyline)
324 .removeLayer(endpoints[0].marker)
325 .removeLayer(endpoints[1].marker);
331 OSM.Directions.engines = [];
333 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
334 if (document.location.protocol === "http:" || supportsHTTPS) {
335 OSM.Directions.engines.push(engine);