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 var route_from = endpoints[0].value;
80 OSM.router.route("/?query=" + encodeURIComponent(route_from) + OSM.formatHash(map));
82 OSM.router.route("/" + OSM.formatHash(map));
86 function formatDistance(m) {
88 return I18n.t("javascripts.directions.distance_m", { distance: Math.round(m) });
89 } else if (m < 10000) {
90 return I18n.t("javascripts.directions.distance_km", { distance: (m / 1000.0).toFixed(1) });
92 return I18n.t("javascripts.directions.distance_km", { distance: Math.round(m / 1000) });
96 function formatHeight(m) {
97 return I18n.t("javascripts.directions.distance_m", { distance: Math.round(m) });
100 function formatTime(s) {
101 var m = Math.round(s / 60);
102 var h = Math.floor(m / 60);
104 return h + ":" + (m < 10 ? "0" : "") + m;
107 function findEngine(id) {
108 return engines.findIndex(function (engine) {
109 return engine.id === id;
113 function setEngine(index) {
114 chosenEngine = engines[index];
118 function getRoute(fitRoute, reportErrors) {
119 // Cancel any route that is already in progress
120 if (routeRequest) routeRequest.abort();
122 var o = endpoints[0].latlng,
123 d = endpoints[1].latlng;
125 if (!o || !d) return;
126 $("header").addClass("closed");
128 var precision = OSM.zoomPrecision(map.getZoom());
130 OSM.router.replace("/directions?" + Qs.stringify({
131 engine: chosenEngine.id,
132 route: o.lat.toFixed(precision) + "," + o.lng.toFixed(precision) + ";" +
133 d.lat.toFixed(precision) + "," + d.lng.toFixed(precision)
136 // copy loading item to sidebar and display it. we copy it, rather than
137 // just using it in-place and replacing it in case it has to be used
139 $("#sidebar_content").html($(".directions_form .loader_copy").html());
140 map.setSidebarOverlaid(false);
142 routeRequest = chosenEngine.getRoute([o, d], function (err, route) {
146 map.removeLayer(polyline);
149 $("#sidebar_content").html("<div class=\"alert alert-danger\">" + I18n.t("javascripts.directions.errors.no_route") + "</div>");
156 .setLatLngs(route.line)
160 map.fitBounds(polyline.getBounds().pad(0.05));
163 var distanceText = $("<p>").append(
164 I18n.t("javascripts.directions.distance") + ": " + formatDistance(route.distance) + ". " +
165 I18n.t("javascripts.directions.time") + ": " + formatTime(route.time) + ".");
166 if (typeof route.ascend !== "undefined" && typeof route.descend !== "undefined") {
169 I18n.t("javascripts.directions.ascend") + ": " + formatHeight(route.ascend) + ". " +
170 I18n.t("javascripts.directions.descend") + ": " + formatHeight(route.descend) + ".");
173 var turnByTurnTable = $("<table class='table table-hover table-sm mb-3'>")
174 .append($("<tbody>"));
175 var directionsCloseButton = $("<button type='button' class='btn-close'>")
176 .attr("aria-label", I18n.t("javascripts.close"));
178 $("#sidebar_content")
181 $("<div class='d-flex'>").append(
182 $("<h2 class='flex-grow-1 text-break'>")
183 .text(I18n.t("javascripts.directions.directions")),
184 $("<div>").append(directionsCloseButton)),
190 route.steps.forEach(function (step) {
193 instruction = step[2],
199 } else if (dist < 200) {
200 dist = String(Math.round(dist / 10) * 10) + "m";
201 } else if (dist < 1500) {
202 dist = String(Math.round(dist / 100) * 100) + "m";
203 } else if (dist < 5000) {
204 dist = String(Math.round(dist / 100) / 10) + "km";
206 dist = String(Math.round(dist / 1000)) + "km";
209 var row = $("<tr class='turn'/>");
210 row.append("<td class='border-0'><div class='direction i" + direction + "'/></td> ");
211 row.append("<td>" + instruction);
212 row.append("<td class='distance text-body-secondary text-end'>" + dist);
214 row.on("click", function () {
217 .setContent("<p>" + instruction + "</p>")
221 row.hover(function () {
226 map.removeLayer(highlight);
229 turnByTurnTable.append(row);
232 $("#sidebar_content").append("<p class=\"text-center\">" +
233 I18n.t("javascripts.directions.instructions.courtesy", { link: chosenEngine.creditline }) +
236 directionsCloseButton.on("click", function () {
237 map.removeLayer(polyline);
238 $("#sidebar_content").html("");
239 map.setSidebarOverlaid(true);
240 // TODO: collapse width of sidebar back to previous
245 var chosenEngineIndex = findEngine("fossgis_osrm_car");
246 if (Cookies.get("_osm_directions_engine")) {
247 chosenEngineIndex = findEngine(Cookies.get("_osm_directions_engine"));
249 setEngine(chosenEngineIndex);
251 select.on("change", function (e) {
252 chosenEngine = engines[e.target.selectedIndex];
253 Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
254 getRoute(true, true);
257 $(".directions_form").on("submit", function (e) {
259 getRoute(true, true);
262 $(".routing_marker_column img").on("dragstart", function (e) {
263 var dt = e.originalEvent.dataTransfer;
264 dt.effectAllowed = "move";
265 var dragData = { type: $(this).data("type") };
266 dt.setData("text", JSON.stringify(dragData));
267 if (dt.setDragImage) {
268 var img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
269 dt.setDragImage(img.get(0), 12, 21);
275 page.pushstate = page.popstate = function () {
276 $(".search_form").hide();
277 $(".directions_form").show();
279 $("#map").on("dragend dragover", function (e) {
283 $("#map").on("drop", function (e) {
285 var oe = e.originalEvent;
286 var dragData = JSON.parse(oe.dataTransfer.getData("text"));
287 var type = dragData.type;
288 var pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
290 var ll = map.containerPointToLatLng(pt);
291 var precision = OSM.zoomPrecision(map.getZoom());
292 var value = ll.lat.toFixed(precision) + ", " + ll.lng.toFixed(precision);
293 endpoints[type === "from" ? 0 : 1].setValue(value, ll);
296 var params = Qs.parse(location.search.substring(1)),
297 route = (params.route || "").split(";"),
298 from = route[0] && L.latLng(route[0].split(",")),
299 to = route[1] && L.latLng(route[1].split(","));
302 var engineIndex = findEngine(params.engine);
304 if (engineIndex >= 0) {
305 setEngine(engineIndex);
309 endpoints[0].setValue(params.from || "", from);
310 endpoints[1].setValue(params.to || "", to);
312 map.setSidebarOverlaid(!from || !to);
315 page.load = function () {
319 page.unload = function () {
320 $(".search_form").show();
321 $(".directions_form").hide();
322 $("#map").off("dragend dragover drop");
326 .removeLayer(polyline)
327 .removeLayer(endpoints[0].marker)
328 .removeLayer(endpoints[1].marker);
334 OSM.Directions.engines = [];
336 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
337 if (document.location.protocol === "http:" || supportsHTTPS) {
338 OSM.Directions.engines.push(engine);