2 //= require_tree ./directions
5 OSM.Directions = function (map) {
6 var awaitingRoute; // true if we've asked the engine for a route and are waiting to hear back
9 var popup = L.popup({ autoPanPadding: [100, 100] });
11 var polyline = L.polyline([], {
17 var highlight = L.polyline([], {
24 Endpoint($("input[name='route_from']"), OSM.MARKER_GREEN),
25 Endpoint($("input[name='route_to']"), OSM.MARKER_RED)
28 var expiry = new Date();
29 expiry.setYear(expiry.getFullYear() + 10);
31 var engines = OSM.Directions.engines;
33 engines.sort(function (a, b) {
34 var localised_a = I18n.t("javascripts.directions.engines." + a.id),
35 localised_b = I18n.t("javascripts.directions.engines." + b.id);
36 return localised_a.localeCompare(localised_b);
39 var select = $("select.routing_engines");
41 engines.forEach(function (engine, i) {
42 select.append("<option value='" + i + "'>" + I18n.t("javascripts.directions.engines." + engine.id) + "</option>");
45 function Endpoint(input, iconUrl) {
48 endpoint.marker = L.marker([0, 0], {
53 popupAnchor: [1, -34],
54 shadowUrl: OSM.MARKER_SHADOW,
61 endpoint.marker.on("drag dragend", function (e) {
62 var dragging = (e.type === "drag");
63 if (dragging && !chosenEngine.draggable) return;
64 if (dragging && awaitingRoute) return;
65 endpoint.setLatLng(e.target.getLatLng());
66 if (map.hasLayer(polyline)) {
67 getRoute(false, !dragging);
71 input.on("keydown", function () {
72 input.removeClass("is-invalid");
75 input.on("change", function (e) {
76 // make text the same in both text boxes
77 var value = e.target.value;
78 endpoint.setValue(value);
81 endpoint.setValue = function (value, latlng) {
82 endpoint.value = value;
83 delete endpoint.latlng;
84 input.removeClass("is-invalid");
88 endpoint.setLatLng(latlng);
90 endpoint.getGeocode();
94 endpoint.getGeocode = function () {
95 // if no one has entered a value yet, then we can't geocode, so don't
97 if (!endpoint.value) {
101 endpoint.awaitingGeocode = true;
103 var viewbox = map.getBounds().toBBoxString(); // <sw lon>,<sw lat>,<ne lon>,<ne lat>
105 $.getJSON(OSM.NOMINATIM_URL + "search?q=" + encodeURIComponent(endpoint.value) + "&format=json&viewbox=" + viewbox, function (json) {
106 endpoint.awaitingGeocode = false;
107 endpoint.hasGeocode = true;
108 if (json.length === 0) {
109 input.addClass("is-invalid");
110 alert(I18n.t("javascripts.directions.errors.no_place", { place: endpoint.value }));
114 endpoint.setLatLng(L.latLng(json[0]));
116 input.val(json[0].display_name);
118 getRoute(true, true);
122 endpoint.setLatLng = function (ll) {
123 var precision = OSM.zoomPrecision(map.getZoom());
124 input.val(ll.lat.toFixed(precision) + ", " + ll.lng.toFixed(precision));
125 endpoint.hasGeocode = true;
126 endpoint.latlng = ll;
135 $(".directions_form .reverse_directions").on("click", function () {
136 var coordFrom = endpoints[0].latlng,
137 coordTo = endpoints[1].latlng,
141 routeFrom = coordFrom.lat + "," + coordFrom.lng;
144 routeTo = coordTo.lat + "," + coordTo.lng;
147 OSM.router.route("/directions?" + Qs.stringify({
148 from: $("#route_to").val(),
149 to: $("#route_from").val(),
150 route: routeTo + ";" + routeFrom
154 $(".directions_form .btn-close").on("click", function (e) {
156 var route_from = endpoints[0].value;
158 OSM.router.route("/?query=" + encodeURIComponent(route_from) + OSM.formatHash(map));
160 OSM.router.route("/" + OSM.formatHash(map));
164 function formatDistance(m) {
166 return I18n.t("javascripts.directions.distance_m", { distance: Math.round(m) });
167 } else if (m < 10000) {
168 return I18n.t("javascripts.directions.distance_km", { distance: (m / 1000.0).toFixed(1) });
170 return I18n.t("javascripts.directions.distance_km", { distance: Math.round(m / 1000) });
174 function formatHeight(m) {
175 return I18n.t("javascripts.directions.distance_m", { distance: Math.round(m) });
178 function formatTime(s) {
179 var m = Math.round(s / 60);
180 var h = Math.floor(m / 60);
182 return h + ":" + (m < 10 ? "0" : "") + m;
185 function findEngine(id) {
186 return engines.findIndex(function (engine) {
187 return engine.id === id;
191 function setEngine(index) {
192 chosenEngine = engines[index];
196 function getRoute(fitRoute, reportErrors) {
197 // Cancel any route that is already in progress
198 if (awaitingRoute) awaitingRoute.abort();
200 // go fetch geocodes for any endpoints which have not already
202 for (var ep_i = 0; ep_i < 2; ++ep_i) {
203 var endpoint = endpoints[ep_i];
204 if (!endpoint.hasGeocode && !endpoint.awaitingGeocode) {
205 endpoint.getGeocode();
208 if (endpoints[0].awaitingGeocode || endpoints[1].awaitingGeocode) {
212 var o = endpoints[0].latlng,
213 d = endpoints[1].latlng;
215 if (!o || !d) return;
216 $("header").addClass("closed");
218 var precision = OSM.zoomPrecision(map.getZoom());
220 OSM.router.replace("/directions?" + Qs.stringify({
221 engine: chosenEngine.id,
222 route: o.lat.toFixed(precision) + "," + o.lng.toFixed(precision) + ";" +
223 d.lat.toFixed(precision) + "," + d.lng.toFixed(precision)
226 // copy loading item to sidebar and display it. we copy it, rather than
227 // just using it in-place and replacing it in case it has to be used
229 $("#sidebar_content").html($(".directions_form .loader_copy").html());
230 map.setSidebarOverlaid(false);
232 awaitingRoute = chosenEngine.getRoute([o, d], function (err, route) {
233 awaitingRoute = null;
236 map.removeLayer(polyline);
239 $("#sidebar_content").html("<div class=\"alert alert-danger\">" + I18n.t("javascripts.directions.errors.no_route") + "</div>");
246 .setLatLngs(route.line)
250 map.fitBounds(polyline.getBounds().pad(0.05));
253 var distanceText = $("<p>").append(
254 I18n.t("javascripts.directions.distance") + ": " + formatDistance(route.distance) + ". " +
255 I18n.t("javascripts.directions.time") + ": " + formatTime(route.time) + ".");
256 if (typeof route.ascend !== "undefined" && typeof route.descend !== "undefined") {
259 I18n.t("javascripts.directions.ascend") + ": " + formatHeight(route.ascend) + ". " +
260 I18n.t("javascripts.directions.descend") + ": " + formatHeight(route.descend) + ".");
263 var turnByTurnTable = $("<table class='table table-hover table-sm mb-3'>")
264 .append($("<tbody>"));
265 var directionsCloseButton = $("<button type='button' class='btn-close'>")
266 .attr("aria-label", I18n.t("javascripts.close"));
268 $("#sidebar_content")
271 $("<div class='d-flex'>").append(
272 $("<h2 class='flex-grow-1 text-break'>")
273 .text(I18n.t("javascripts.directions.directions")),
274 $("<div>").append(directionsCloseButton)),
280 route.steps.forEach(function (step) {
283 instruction = step[2],
289 } else if (dist < 200) {
290 dist = String(Math.round(dist / 10) * 10) + "m";
291 } else if (dist < 1500) {
292 dist = String(Math.round(dist / 100) * 100) + "m";
293 } else if (dist < 5000) {
294 dist = String(Math.round(dist / 100) / 10) + "km";
296 dist = String(Math.round(dist / 1000)) + "km";
299 var row = $("<tr class='turn'/>");
300 row.append("<td class='border-0'><div class='direction i" + direction + "'/></td> ");
301 row.append("<td>" + instruction);
302 row.append("<td class='distance text-body-secondary text-end'>" + dist);
304 row.on("click", function () {
307 .setContent("<p>" + instruction + "</p>")
311 row.hover(function () {
316 map.removeLayer(highlight);
319 turnByTurnTable.append(row);
322 $("#sidebar_content").append("<p class=\"text-center\">" +
323 I18n.t("javascripts.directions.instructions.courtesy", { link: chosenEngine.creditline }) +
326 directionsCloseButton.on("click", function () {
327 map.removeLayer(polyline);
328 $("#sidebar_content").html("");
329 map.setSidebarOverlaid(true);
330 // TODO: collapse width of sidebar back to previous
335 var chosenEngineIndex = findEngine("fossgis_osrm_car");
336 if (Cookies.get("_osm_directions_engine")) {
337 chosenEngineIndex = findEngine(Cookies.get("_osm_directions_engine"));
339 setEngine(chosenEngineIndex);
341 select.on("change", function (e) {
342 chosenEngine = engines[e.target.selectedIndex];
343 Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
344 getRoute(true, true);
347 $(".directions_form").on("submit", function (e) {
349 getRoute(true, true);
352 $(".routing_marker_column img").on("dragstart", function (e) {
353 var dt = e.originalEvent.dataTransfer;
354 dt.effectAllowed = "move";
355 var dragData = { type: $(this).data("type") };
356 dt.setData("text", JSON.stringify(dragData));
357 if (dt.setDragImage) {
358 var img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
359 dt.setDragImage(img.get(0), 12, 21);
365 page.pushstate = page.popstate = function () {
366 $(".search_form").hide();
367 $(".directions_form").show();
369 $("#map").on("dragend dragover", function (e) {
373 $("#map").on("drop", function (e) {
375 var oe = e.originalEvent;
376 var dragData = JSON.parse(oe.dataTransfer.getData("text"));
377 var type = dragData.type;
378 var pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
380 var ll = map.containerPointToLatLng(pt);
381 endpoints[type === "from" ? 0 : 1].setLatLng(ll);
382 getRoute(true, true);
385 var params = Qs.parse(location.search.substring(1)),
386 route = (params.route || "").split(";"),
387 from = route[0] && L.latLng(route[0].split(",")),
388 to = route[1] && L.latLng(route[1].split(","));
391 var engineIndex = findEngine(params.engine);
393 if (engineIndex >= 0) {
394 setEngine(engineIndex);
398 endpoints[0].setValue(params.from || "", from);
399 endpoints[1].setValue(params.to || "", to);
401 map.setSidebarOverlaid(!from || !to);
403 getRoute(true, true);
406 page.load = function () {
410 page.unload = function () {
411 $(".search_form").show();
412 $(".directions_form").hide();
413 $("#map").off("dragend dragover drop");
417 .removeLayer(polyline)
418 .removeLayer(endpoints[0].marker)
419 .removeLayer(endpoints[1].marker);
425 OSM.Directions.engines = [];
427 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
428 if (document.location.protocol === "http:" || supportsHTTPS) {
429 OSM.Directions.engines.push(engine);