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 $(".search_form input[name='query']").val(endpoints[0].value);
79 OSM.router.route("/" + OSM.formatHash(map));
82 function formatDistance(m) {
84 return I18n.t("javascripts.directions.distance_m", { distance: Math.round(m) });
85 } else if (m < 10000) {
86 return I18n.t("javascripts.directions.distance_km", { distance: (m / 1000.0).toFixed(1) });
88 return I18n.t("javascripts.directions.distance_km", { distance: Math.round(m / 1000) });
92 function formatHeight(m) {
93 return I18n.t("javascripts.directions.distance_m", { distance: Math.round(m) });
96 function formatTime(s) {
97 var m = Math.round(s / 60);
98 var h = Math.floor(m / 60);
100 return h + ":" + (m < 10 ? "0" : "") + m;
103 function findEngine(id) {
104 return engines.findIndex(function (engine) {
105 return engine.id === id;
109 function setEngine(index) {
110 chosenEngine = engines[index];
114 function getRoute(fitRoute, reportErrors) {
115 // Cancel any route that is already in progress
116 if (routeRequest) routeRequest.abort();
118 var o = endpoints[0].latlng,
119 d = endpoints[1].latlng;
121 if (!o || !d) return;
122 $("header").addClass("closed");
124 var precision = OSM.zoomPrecision(map.getZoom());
126 OSM.router.replace("/directions?" + Qs.stringify({
127 engine: chosenEngine.id,
128 route: o.lat.toFixed(precision) + "," + o.lng.toFixed(precision) + ";" +
129 d.lat.toFixed(precision) + "," + d.lng.toFixed(precision)
132 // copy loading item to sidebar and display it. we copy it, rather than
133 // just using it in-place and replacing it in case it has to be used
135 $("#sidebar_content").html($(".directions_form .loader_copy").html());
136 map.setSidebarOverlaid(false);
138 routeRequest = chosenEngine.getRoute([o, d], function (err, route) {
142 map.removeLayer(polyline);
145 $("#sidebar_content").html("<div class=\"alert alert-danger\">" + I18n.t("javascripts.directions.errors.no_route") + "</div>");
152 .setLatLngs(route.line)
156 map.fitBounds(polyline.getBounds().pad(0.05));
159 var distanceText = $("<p>").append(
160 I18n.t("javascripts.directions.distance") + ": " + formatDistance(route.distance) + ". " +
161 I18n.t("javascripts.directions.time") + ": " + formatTime(route.time) + ".");
162 if (typeof route.ascend !== "undefined" && typeof route.descend !== "undefined") {
165 I18n.t("javascripts.directions.ascend") + ": " + formatHeight(route.ascend) + ". " +
166 I18n.t("javascripts.directions.descend") + ": " + formatHeight(route.descend) + ".");
169 var turnByTurnTable = $("<table class='table table-hover table-sm mb-3'>")
170 .append($("<tbody>"));
171 var directionsCloseButton = $("<button type='button' class='btn-close'>")
172 .attr("aria-label", I18n.t("javascripts.close"));
174 $("#sidebar_content")
177 $("<div class='d-flex'>").append(
178 $("<h2 class='flex-grow-1 text-break'>")
179 .text(I18n.t("javascripts.directions.directions")),
180 $("<div>").append(directionsCloseButton)),
186 route.steps.forEach(function (step) {
189 instruction = step[2],
195 } else if (dist < 200) {
196 dist = String(Math.round(dist / 10) * 10) + "m";
197 } else if (dist < 1500) {
198 dist = String(Math.round(dist / 100) * 100) + "m";
199 } else if (dist < 5000) {
200 dist = String(Math.round(dist / 100) / 10) + "km";
202 dist = String(Math.round(dist / 1000)) + "km";
205 var row = $("<tr class='turn'/>");
206 row.append("<td class='border-0'><div class='direction i" + direction + "'/></td> ");
207 row.append("<td>" + instruction);
208 row.append("<td class='distance text-body-secondary text-end'>" + dist);
210 row.on("click", function () {
213 .setContent("<p>" + instruction + "</p>")
217 row.hover(function () {
222 map.removeLayer(highlight);
225 turnByTurnTable.append(row);
228 $("#sidebar_content").append("<p class=\"text-center\">" +
229 I18n.t("javascripts.directions.instructions.courtesy", { link: chosenEngine.creditline }) +
232 directionsCloseButton.on("click", function () {
233 map.removeLayer(polyline);
234 $("#sidebar_content").html("");
235 map.setSidebarOverlaid(true);
236 // TODO: collapse width of sidebar back to previous
241 var chosenEngineIndex = findEngine("fossgis_osrm_car");
242 if (Cookies.get("_osm_directions_engine")) {
243 chosenEngineIndex = findEngine(Cookies.get("_osm_directions_engine"));
245 setEngine(chosenEngineIndex);
247 select.on("change", function (e) {
248 chosenEngine = engines[e.target.selectedIndex];
249 Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
250 getRoute(true, true);
253 $(".directions_form").on("submit", function (e) {
255 getRoute(true, true);
258 $(".routing_marker_column img").on("dragstart", function (e) {
259 var dt = e.originalEvent.dataTransfer;
260 dt.effectAllowed = "move";
261 var dragData = { type: $(this).data("type") };
262 dt.setData("text", JSON.stringify(dragData));
263 if (dt.setDragImage) {
264 var img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
265 dt.setDragImage(img.get(0), 12, 21);
271 page.pushstate = page.popstate = function () {
272 $(".search_form").hide();
273 $(".directions_form").show();
275 $("#map").on("dragend dragover", function (e) {
279 $("#map").on("drop", function (e) {
281 var oe = e.originalEvent;
282 var dragData = JSON.parse(oe.dataTransfer.getData("text"));
283 var type = dragData.type;
284 var pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
286 var ll = map.containerPointToLatLng(pt);
287 var precision = OSM.zoomPrecision(map.getZoom());
288 var value = ll.lat.toFixed(precision) + ", " + ll.lng.toFixed(precision);
289 endpoints[type === "from" ? 0 : 1].setValue(value, ll);
292 var params = Qs.parse(location.search.substring(1)),
293 route = (params.route || "").split(";"),
294 from = route[0] && L.latLng(route[0].split(",")),
295 to = route[1] && L.latLng(route[1].split(","));
298 var engineIndex = findEngine(params.engine);
300 if (engineIndex >= 0) {
301 setEngine(engineIndex);
305 endpoints[0].setValue(params.from || "", from);
306 endpoints[1].setValue(params.to || "", to);
308 map.setSidebarOverlaid(!from || !to);
311 page.load = function () {
315 page.unload = function () {
316 $(".search_form").show();
317 $(".directions_form").hide();
318 $("#map").off("dragend dragover drop");
322 .removeLayer(polyline)
323 .removeLayer(endpoints[0].marker)
324 .removeLayer(endpoints[1].marker);
330 OSM.Directions.engines = [];
332 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
333 if (document.location.protocol === "http:" || supportsHTTPS) {
334 OSM.Directions.engines.push(engine);