2 //= require_tree ./directions
5 OSM.Directions = function (map) {
6 var routeRequest = null; // jqXHR object of an ongoing route request or null
9 var popup = L.popup({ autoPanPadding: [100, 100] });
11 var polyline = L.polyline([], {
17 var highlight = L.polyline([], {
23 var endpointDragCallback = function (dragging) {
24 if (!map.hasLayer(polyline)) return;
25 if (dragging && !chosenEngine.draggable) return;
26 if (dragging && routeRequest) return;
28 getRoute(false, !dragging);
30 var endpointGeocodeCallback = function () {
35 Endpoint($("input[name='route_from']"), OSM.MARKER_GREEN, endpointDragCallback, endpointGeocodeCallback),
36 Endpoint($("input[name='route_to']"), OSM.MARKER_RED, endpointDragCallback, endpointGeocodeCallback)
39 var expiry = new Date();
40 expiry.setYear(expiry.getFullYear() + 10);
42 var engines = OSM.Directions.engines;
44 engines.sort(function (a, b) {
45 var localised_a = I18n.t("javascripts.directions.engines." + a.id),
46 localised_b = I18n.t("javascripts.directions.engines." + b.id);
47 return localised_a.localeCompare(localised_b);
50 var select = $("select.routing_engines");
52 engines.forEach(function (engine, i) {
53 select.append("<option value='" + i + "'>" + I18n.t("javascripts.directions.engines." + engine.id) + "</option>");
56 function Endpoint(input, iconUrl, dragCallback, geocodeCallback) {
59 endpoint.marker = L.marker([0, 0], {
64 popupAnchor: [1, -34],
65 shadowUrl: OSM.MARKER_SHADOW,
72 endpoint.marker.on("drag dragend", function (e) {
73 endpoint.setLatLng(e.target.getLatLng());
74 dragCallback(e.type === "drag");
77 input.on("keydown", function () {
78 input.removeClass("is-invalid");
81 input.on("change", function (e) {
82 // make text the same in both text boxes
83 var value = e.target.value;
84 endpoint.setValue(value);
87 endpoint.setValue = function (value, latlng) {
88 endpoint.value = value;
89 delete endpoint.latlng;
90 input.removeClass("is-invalid");
94 endpoint.setLatLng(latlng);
96 endpoint.getGeocode();
100 endpoint.getGeocode = function () {
101 // if no one has entered a value yet, then we can't geocode, so don't
103 if (!endpoint.value) {
107 endpoint.awaitingGeocode = true;
109 var viewbox = map.getBounds().toBBoxString(); // <sw lon>,<sw lat>,<ne lon>,<ne lat>
111 $.getJSON(OSM.NOMINATIM_URL + "search?q=" + encodeURIComponent(endpoint.value) + "&format=json&viewbox=" + viewbox, function (json) {
112 endpoint.awaitingGeocode = false;
113 endpoint.hasGeocode = true;
114 if (json.length === 0) {
115 input.addClass("is-invalid");
116 alert(I18n.t("javascripts.directions.errors.no_place", { place: endpoint.value }));
120 endpoint.setLatLng(L.latLng(json[0]));
122 input.val(json[0].display_name);
128 endpoint.setLatLng = function (ll) {
129 var precision = OSM.zoomPrecision(map.getZoom());
130 input.val(ll.lat.toFixed(precision) + ", " + ll.lng.toFixed(precision));
131 endpoint.hasGeocode = true;
132 endpoint.latlng = ll;
141 $(".directions_form .reverse_directions").on("click", function () {
142 var coordFrom = endpoints[0].latlng,
143 coordTo = endpoints[1].latlng,
147 routeFrom = coordFrom.lat + "," + coordFrom.lng;
150 routeTo = coordTo.lat + "," + coordTo.lng;
153 OSM.router.route("/directions?" + Qs.stringify({
154 from: $("#route_to").val(),
155 to: $("#route_from").val(),
156 route: routeTo + ";" + routeFrom
160 $(".directions_form .btn-close").on("click", function (e) {
162 var route_from = endpoints[0].value;
164 OSM.router.route("/?query=" + encodeURIComponent(route_from) + OSM.formatHash(map));
166 OSM.router.route("/" + OSM.formatHash(map));
170 function formatDistance(m) {
172 return I18n.t("javascripts.directions.distance_m", { distance: Math.round(m) });
173 } else if (m < 10000) {
174 return I18n.t("javascripts.directions.distance_km", { distance: (m / 1000.0).toFixed(1) });
176 return I18n.t("javascripts.directions.distance_km", { distance: Math.round(m / 1000) });
180 function formatHeight(m) {
181 return I18n.t("javascripts.directions.distance_m", { distance: Math.round(m) });
184 function formatTime(s) {
185 var m = Math.round(s / 60);
186 var h = Math.floor(m / 60);
188 return h + ":" + (m < 10 ? "0" : "") + m;
191 function findEngine(id) {
192 return engines.findIndex(function (engine) {
193 return engine.id === id;
197 function setEngine(index) {
198 chosenEngine = engines[index];
202 function getRoute(fitRoute, reportErrors) {
203 // Cancel any route that is already in progress
204 if (routeRequest) routeRequest.abort();
206 // go fetch geocodes for any endpoints which have not already
208 for (var ep_i = 0; ep_i < 2; ++ep_i) {
209 var endpoint = endpoints[ep_i];
210 if (!endpoint.hasGeocode && !endpoint.awaitingGeocode) {
211 endpoint.getGeocode();
214 if (endpoints[0].awaitingGeocode || endpoints[1].awaitingGeocode) {
218 var o = endpoints[0].latlng,
219 d = endpoints[1].latlng;
221 if (!o || !d) return;
222 $("header").addClass("closed");
224 var precision = OSM.zoomPrecision(map.getZoom());
226 OSM.router.replace("/directions?" + Qs.stringify({
227 engine: chosenEngine.id,
228 route: o.lat.toFixed(precision) + "," + o.lng.toFixed(precision) + ";" +
229 d.lat.toFixed(precision) + "," + d.lng.toFixed(precision)
232 // copy loading item to sidebar and display it. we copy it, rather than
233 // just using it in-place and replacing it in case it has to be used
235 $("#sidebar_content").html($(".directions_form .loader_copy").html());
236 map.setSidebarOverlaid(false);
238 routeRequest = chosenEngine.getRoute([o, d], function (err, route) {
242 map.removeLayer(polyline);
245 $("#sidebar_content").html("<div class=\"alert alert-danger\">" + I18n.t("javascripts.directions.errors.no_route") + "</div>");
252 .setLatLngs(route.line)
256 map.fitBounds(polyline.getBounds().pad(0.05));
259 var distanceText = $("<p>").append(
260 I18n.t("javascripts.directions.distance") + ": " + formatDistance(route.distance) + ". " +
261 I18n.t("javascripts.directions.time") + ": " + formatTime(route.time) + ".");
262 if (typeof route.ascend !== "undefined" && typeof route.descend !== "undefined") {
265 I18n.t("javascripts.directions.ascend") + ": " + formatHeight(route.ascend) + ". " +
266 I18n.t("javascripts.directions.descend") + ": " + formatHeight(route.descend) + ".");
269 var turnByTurnTable = $("<table class='table table-hover table-sm mb-3'>")
270 .append($("<tbody>"));
271 var directionsCloseButton = $("<button type='button' class='btn-close'>")
272 .attr("aria-label", I18n.t("javascripts.close"));
274 $("#sidebar_content")
277 $("<div class='d-flex'>").append(
278 $("<h2 class='flex-grow-1 text-break'>")
279 .text(I18n.t("javascripts.directions.directions")),
280 $("<div>").append(directionsCloseButton)),
286 route.steps.forEach(function (step) {
289 instruction = step[2],
295 } else if (dist < 200) {
296 dist = String(Math.round(dist / 10) * 10) + "m";
297 } else if (dist < 1500) {
298 dist = String(Math.round(dist / 100) * 100) + "m";
299 } else if (dist < 5000) {
300 dist = String(Math.round(dist / 100) / 10) + "km";
302 dist = String(Math.round(dist / 1000)) + "km";
305 var row = $("<tr class='turn'/>");
306 row.append("<td class='border-0'><div class='direction i" + direction + "'/></td> ");
307 row.append("<td>" + instruction);
308 row.append("<td class='distance text-body-secondary text-end'>" + dist);
310 row.on("click", function () {
313 .setContent("<p>" + instruction + "</p>")
317 row.hover(function () {
322 map.removeLayer(highlight);
325 turnByTurnTable.append(row);
328 $("#sidebar_content").append("<p class=\"text-center\">" +
329 I18n.t("javascripts.directions.instructions.courtesy", { link: chosenEngine.creditline }) +
332 directionsCloseButton.on("click", function () {
333 map.removeLayer(polyline);
334 $("#sidebar_content").html("");
335 map.setSidebarOverlaid(true);
336 // TODO: collapse width of sidebar back to previous
341 var chosenEngineIndex = findEngine("fossgis_osrm_car");
342 if (Cookies.get("_osm_directions_engine")) {
343 chosenEngineIndex = findEngine(Cookies.get("_osm_directions_engine"));
345 setEngine(chosenEngineIndex);
347 select.on("change", function (e) {
348 chosenEngine = engines[e.target.selectedIndex];
349 Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
350 getRoute(true, true);
353 $(".directions_form").on("submit", function (e) {
355 getRoute(true, true);
358 $(".routing_marker_column img").on("dragstart", function (e) {
359 var dt = e.originalEvent.dataTransfer;
360 dt.effectAllowed = "move";
361 var dragData = { type: $(this).data("type") };
362 dt.setData("text", JSON.stringify(dragData));
363 if (dt.setDragImage) {
364 var img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
365 dt.setDragImage(img.get(0), 12, 21);
371 page.pushstate = page.popstate = function () {
372 $(".search_form").hide();
373 $(".directions_form").show();
375 $("#map").on("dragend dragover", function (e) {
379 $("#map").on("drop", function (e) {
381 var oe = e.originalEvent;
382 var dragData = JSON.parse(oe.dataTransfer.getData("text"));
383 var type = dragData.type;
384 var pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
386 var ll = map.containerPointToLatLng(pt);
387 endpoints[type === "from" ? 0 : 1].setLatLng(ll);
388 getRoute(true, true);
391 var params = Qs.parse(location.search.substring(1)),
392 route = (params.route || "").split(";"),
393 from = route[0] && L.latLng(route[0].split(",")),
394 to = route[1] && L.latLng(route[1].split(","));
397 var engineIndex = findEngine(params.engine);
399 if (engineIndex >= 0) {
400 setEngine(engineIndex);
404 endpoints[0].setValue(params.from || "", from);
405 endpoints[1].setValue(params.to || "", to);
407 map.setSidebarOverlaid(!from || !to);
409 getRoute(true, true);
412 page.load = function () {
416 page.unload = function () {
417 $(".search_form").show();
418 $(".directions_form").hide();
419 $("#map").off("dragend dragover drop");
423 .removeLayer(polyline)
424 .removeLayer(endpoints[0].marker)
425 .removeLayer(endpoints[1].marker);
431 OSM.Directions.engines = [];
433 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
434 if (document.location.protocol === "http:" || supportsHTTPS) {
435 OSM.Directions.engines.push(engine);