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 endpointGeocodeCallback = function () {
36 OSM.DirectionsEndpoint(map, $("input[name='route_from']"), OSM.MARKER_GREEN, endpointDragCallback, endpointGeocodeCallback),
37 OSM.DirectionsEndpoint(map, $("input[name='route_to']"), OSM.MARKER_RED, endpointDragCallback, endpointGeocodeCallback)
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 // go fetch geocodes for any endpoints which have not already
124 for (var ep_i = 0; ep_i < 2; ++ep_i) {
125 var endpoint = endpoints[ep_i];
126 if (!endpoint.hasGeocode && !endpoint.awaitingGeocode) {
127 endpoint.getGeocode();
130 if (endpoints[0].awaitingGeocode || endpoints[1].awaitingGeocode) {
134 var o = endpoints[0].latlng,
135 d = endpoints[1].latlng;
137 if (!o || !d) return;
138 $("header").addClass("closed");
140 var precision = OSM.zoomPrecision(map.getZoom());
142 OSM.router.replace("/directions?" + Qs.stringify({
143 engine: chosenEngine.id,
144 route: o.lat.toFixed(precision) + "," + o.lng.toFixed(precision) + ";" +
145 d.lat.toFixed(precision) + "," + d.lng.toFixed(precision)
148 // copy loading item to sidebar and display it. we copy it, rather than
149 // just using it in-place and replacing it in case it has to be used
151 $("#sidebar_content").html($(".directions_form .loader_copy").html());
152 map.setSidebarOverlaid(false);
154 routeRequest = chosenEngine.getRoute([o, d], function (err, route) {
158 map.removeLayer(polyline);
161 $("#sidebar_content").html("<div class=\"alert alert-danger\">" + I18n.t("javascripts.directions.errors.no_route") + "</div>");
168 .setLatLngs(route.line)
172 map.fitBounds(polyline.getBounds().pad(0.05));
175 var distanceText = $("<p>").append(
176 I18n.t("javascripts.directions.distance") + ": " + formatDistance(route.distance) + ". " +
177 I18n.t("javascripts.directions.time") + ": " + formatTime(route.time) + ".");
178 if (typeof route.ascend !== "undefined" && typeof route.descend !== "undefined") {
181 I18n.t("javascripts.directions.ascend") + ": " + formatHeight(route.ascend) + ". " +
182 I18n.t("javascripts.directions.descend") + ": " + formatHeight(route.descend) + ".");
185 var turnByTurnTable = $("<table class='table table-hover table-sm mb-3'>")
186 .append($("<tbody>"));
187 var directionsCloseButton = $("<button type='button' class='btn-close'>")
188 .attr("aria-label", I18n.t("javascripts.close"));
190 $("#sidebar_content")
193 $("<div class='d-flex'>").append(
194 $("<h2 class='flex-grow-1 text-break'>")
195 .text(I18n.t("javascripts.directions.directions")),
196 $("<div>").append(directionsCloseButton)),
202 route.steps.forEach(function (step) {
205 instruction = step[2],
211 } else if (dist < 200) {
212 dist = String(Math.round(dist / 10) * 10) + "m";
213 } else if (dist < 1500) {
214 dist = String(Math.round(dist / 100) * 100) + "m";
215 } else if (dist < 5000) {
216 dist = String(Math.round(dist / 100) / 10) + "km";
218 dist = String(Math.round(dist / 1000)) + "km";
221 var row = $("<tr class='turn'/>");
222 row.append("<td class='border-0'><div class='direction i" + direction + "'/></td> ");
223 row.append("<td>" + instruction);
224 row.append("<td class='distance text-body-secondary text-end'>" + dist);
226 row.on("click", function () {
229 .setContent("<p>" + instruction + "</p>")
233 row.hover(function () {
238 map.removeLayer(highlight);
241 turnByTurnTable.append(row);
244 $("#sidebar_content").append("<p class=\"text-center\">" +
245 I18n.t("javascripts.directions.instructions.courtesy", { link: chosenEngine.creditline }) +
248 directionsCloseButton.on("click", function () {
249 map.removeLayer(polyline);
250 $("#sidebar_content").html("");
251 map.setSidebarOverlaid(true);
252 // TODO: collapse width of sidebar back to previous
257 var chosenEngineIndex = findEngine("fossgis_osrm_car");
258 if (Cookies.get("_osm_directions_engine")) {
259 chosenEngineIndex = findEngine(Cookies.get("_osm_directions_engine"));
261 setEngine(chosenEngineIndex);
263 select.on("change", function (e) {
264 chosenEngine = engines[e.target.selectedIndex];
265 Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
266 getRoute(true, true);
269 $(".directions_form").on("submit", function (e) {
271 getRoute(true, true);
274 $(".routing_marker_column img").on("dragstart", function (e) {
275 var dt = e.originalEvent.dataTransfer;
276 dt.effectAllowed = "move";
277 var dragData = { type: $(this).data("type") };
278 dt.setData("text", JSON.stringify(dragData));
279 if (dt.setDragImage) {
280 var img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
281 dt.setDragImage(img.get(0), 12, 21);
287 page.pushstate = page.popstate = function () {
288 $(".search_form").hide();
289 $(".directions_form").show();
291 $("#map").on("dragend dragover", function (e) {
295 $("#map").on("drop", function (e) {
297 var oe = e.originalEvent;
298 var dragData = JSON.parse(oe.dataTransfer.getData("text"));
299 var type = dragData.type;
300 var pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
302 var ll = map.containerPointToLatLng(pt);
303 var precision = OSM.zoomPrecision(map.getZoom());
304 var value = ll.lat.toFixed(precision) + ", " + ll.lng.toFixed(precision);
305 endpoints[type === "from" ? 0 : 1].setValue(value, ll);
306 getRoute(true, true);
309 var params = Qs.parse(location.search.substring(1)),
310 route = (params.route || "").split(";"),
311 from = route[0] && L.latLng(route[0].split(",")),
312 to = route[1] && L.latLng(route[1].split(","));
315 var engineIndex = findEngine(params.engine);
317 if (engineIndex >= 0) {
318 setEngine(engineIndex);
322 endpoints[0].setValue(params.from || "", from);
323 endpoints[1].setValue(params.to || "", to);
325 map.setSidebarOverlaid(!from || !to);
327 getRoute(true, true);
330 page.load = function () {
334 page.unload = function () {
335 $(".search_form").show();
336 $(".directions_form").hide();
337 $("#map").off("dragend dragover drop");
341 .removeLayer(polyline)
342 .removeLayer(endpoints[0].marker)
343 .removeLayer(endpoints[1].marker);
349 OSM.Directions.engines = [];
351 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
352 if (document.location.protocol === "http:" || supportsHTTPS) {
353 OSM.Directions.engines.push(engine);