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 // go fetch geocodes for any endpoints which have not already
120 for (var ep_i = 0; ep_i < 2; ++ep_i) {
121 var endpoint = endpoints[ep_i];
122 if (!endpoint.hasGeocode && !endpoint.awaitingGeocode) {
123 endpoint.getGeocode();
126 if (endpoints[0].awaitingGeocode || endpoints[1].awaitingGeocode) {
130 var o = endpoints[0].latlng,
131 d = endpoints[1].latlng;
133 if (!o || !d) return;
134 $("header").addClass("closed");
136 var precision = OSM.zoomPrecision(map.getZoom());
138 OSM.router.replace("/directions?" + Qs.stringify({
139 engine: chosenEngine.id,
140 route: o.lat.toFixed(precision) + "," + o.lng.toFixed(precision) + ";" +
141 d.lat.toFixed(precision) + "," + d.lng.toFixed(precision)
144 // copy loading item to sidebar and display it. we copy it, rather than
145 // just using it in-place and replacing it in case it has to be used
147 $("#sidebar_content").html($(".directions_form .loader_copy").html());
148 map.setSidebarOverlaid(false);
150 routeRequest = chosenEngine.getRoute([o, d], function (err, route) {
154 map.removeLayer(polyline);
157 $("#sidebar_content").html("<div class=\"alert alert-danger\">" + I18n.t("javascripts.directions.errors.no_route") + "</div>");
164 .setLatLngs(route.line)
168 map.fitBounds(polyline.getBounds().pad(0.05));
171 var distanceText = $("<p>").append(
172 I18n.t("javascripts.directions.distance") + ": " + formatDistance(route.distance) + ". " +
173 I18n.t("javascripts.directions.time") + ": " + formatTime(route.time) + ".");
174 if (typeof route.ascend !== "undefined" && typeof route.descend !== "undefined") {
177 I18n.t("javascripts.directions.ascend") + ": " + formatHeight(route.ascend) + ". " +
178 I18n.t("javascripts.directions.descend") + ": " + formatHeight(route.descend) + ".");
181 var turnByTurnTable = $("<table class='table table-hover table-sm mb-3'>")
182 .append($("<tbody>"));
183 var directionsCloseButton = $("<button type='button' class='btn-close'>")
184 .attr("aria-label", I18n.t("javascripts.close"));
186 $("#sidebar_content")
189 $("<div class='d-flex'>").append(
190 $("<h2 class='flex-grow-1 text-break'>")
191 .text(I18n.t("javascripts.directions.directions")),
192 $("<div>").append(directionsCloseButton)),
198 route.steps.forEach(function (step) {
201 instruction = step[2],
207 } else if (dist < 200) {
208 dist = String(Math.round(dist / 10) * 10) + "m";
209 } else if (dist < 1500) {
210 dist = String(Math.round(dist / 100) * 100) + "m";
211 } else if (dist < 5000) {
212 dist = String(Math.round(dist / 100) / 10) + "km";
214 dist = String(Math.round(dist / 1000)) + "km";
217 var row = $("<tr class='turn'/>");
218 row.append("<td class='border-0'><div class='direction i" + direction + "'/></td> ");
219 row.append("<td>" + instruction);
220 row.append("<td class='distance text-body-secondary text-end'>" + dist);
222 row.on("click", function () {
225 .setContent("<p>" + instruction + "</p>")
229 row.hover(function () {
234 map.removeLayer(highlight);
237 turnByTurnTable.append(row);
240 $("#sidebar_content").append("<p class=\"text-center\">" +
241 I18n.t("javascripts.directions.instructions.courtesy", { link: chosenEngine.creditline }) +
244 directionsCloseButton.on("click", function () {
245 map.removeLayer(polyline);
246 $("#sidebar_content").html("");
247 map.setSidebarOverlaid(true);
248 // TODO: collapse width of sidebar back to previous
253 var chosenEngineIndex = findEngine("fossgis_osrm_car");
254 if (Cookies.get("_osm_directions_engine")) {
255 chosenEngineIndex = findEngine(Cookies.get("_osm_directions_engine"));
257 setEngine(chosenEngineIndex);
259 select.on("change", function (e) {
260 chosenEngine = engines[e.target.selectedIndex];
261 Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
262 getRoute(true, true);
265 $(".directions_form").on("submit", function (e) {
267 getRoute(true, true);
270 $(".routing_marker_column img").on("dragstart", function (e) {
271 var dt = e.originalEvent.dataTransfer;
272 dt.effectAllowed = "move";
273 var dragData = { type: $(this).data("type") };
274 dt.setData("text", JSON.stringify(dragData));
275 if (dt.setDragImage) {
276 var img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
277 dt.setDragImage(img.get(0), 12, 21);
283 page.pushstate = page.popstate = function () {
284 $(".search_form").hide();
285 $(".directions_form").show();
287 $("#map").on("dragend dragover", function (e) {
291 $("#map").on("drop", function (e) {
293 var oe = e.originalEvent;
294 var dragData = JSON.parse(oe.dataTransfer.getData("text"));
295 var type = dragData.type;
296 var pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
298 var ll = map.containerPointToLatLng(pt);
299 var precision = OSM.zoomPrecision(map.getZoom());
300 var value = ll.lat.toFixed(precision) + ", " + ll.lng.toFixed(precision);
301 endpoints[type === "from" ? 0 : 1].setValue(value, ll);
304 var params = Qs.parse(location.search.substring(1)),
305 route = (params.route || "").split(";"),
306 from = route[0] && L.latLng(route[0].split(",")),
307 to = route[1] && L.latLng(route[1].split(","));
310 var engineIndex = findEngine(params.engine);
312 if (engineIndex >= 0) {
313 setEngine(engineIndex);
317 endpoints[0].setValue(params.from || "", from);
318 endpoints[1].setValue(params.to || "", to);
320 map.setSidebarOverlaid(!from || !to);
323 page.load = function () {
327 page.unload = function () {
328 $(".search_form").show();
329 $(".directions_form").hide();
330 $("#map").off("dragend dragover drop");
334 .removeLayer(polyline)
335 .removeLayer(endpoints[0].marker)
336 .removeLayer(endpoints[1].marker);
342 OSM.Directions.engines = [];
344 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
345 if (document.location.protocol === "http:" || supportsHTTPS) {
346 OSM.Directions.engines.push(engine);