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([], {
23 var endpointDragCallback = function (dragging) {
24 if (map.hasLayer(polyline)) {
25 getRoute(false, !dragging);
30 Endpoint($("input[name='route_from']"), OSM.MARKER_GREEN, endpointDragCallback),
31 Endpoint($("input[name='route_to']"), OSM.MARKER_RED, endpointDragCallback)
34 var expiry = new Date();
35 expiry.setYear(expiry.getFullYear() + 10);
37 var engines = OSM.Directions.engines;
39 engines.sort(function (a, b) {
40 var localised_a = I18n.t("javascripts.directions.engines." + a.id),
41 localised_b = I18n.t("javascripts.directions.engines." + b.id);
42 return localised_a.localeCompare(localised_b);
45 var select = $("select.routing_engines");
47 engines.forEach(function (engine, i) {
48 select.append("<option value='" + i + "'>" + I18n.t("javascripts.directions.engines." + engine.id) + "</option>");
51 function Endpoint(input, iconUrl, dragCallback) {
54 endpoint.marker = L.marker([0, 0], {
59 popupAnchor: [1, -34],
60 shadowUrl: OSM.MARKER_SHADOW,
67 endpoint.marker.on("drag dragend", function (e) {
68 var dragging = (e.type === "drag");
69 if (dragging && !chosenEngine.draggable) return;
70 if (dragging && awaitingRoute) return;
71 endpoint.setLatLng(e.target.getLatLng());
72 dragCallback(dragging);
75 input.on("keydown", function () {
76 input.removeClass("is-invalid");
79 input.on("change", function (e) {
80 // make text the same in both text boxes
81 var value = e.target.value;
82 endpoint.setValue(value);
85 endpoint.setValue = function (value, latlng) {
86 endpoint.value = value;
87 delete endpoint.latlng;
88 input.removeClass("is-invalid");
92 endpoint.setLatLng(latlng);
94 endpoint.getGeocode();
98 endpoint.getGeocode = function () {
99 // if no one has entered a value yet, then we can't geocode, so don't
101 if (!endpoint.value) {
105 endpoint.awaitingGeocode = true;
107 var viewbox = map.getBounds().toBBoxString(); // <sw lon>,<sw lat>,<ne lon>,<ne lat>
109 $.getJSON(OSM.NOMINATIM_URL + "search?q=" + encodeURIComponent(endpoint.value) + "&format=json&viewbox=" + viewbox, function (json) {
110 endpoint.awaitingGeocode = false;
111 endpoint.hasGeocode = true;
112 if (json.length === 0) {
113 input.addClass("is-invalid");
114 alert(I18n.t("javascripts.directions.errors.no_place", { place: endpoint.value }));
118 endpoint.setLatLng(L.latLng(json[0]));
120 input.val(json[0].display_name);
122 getRoute(true, true);
126 endpoint.setLatLng = function (ll) {
127 var precision = OSM.zoomPrecision(map.getZoom());
128 input.val(ll.lat.toFixed(precision) + ", " + ll.lng.toFixed(precision));
129 endpoint.hasGeocode = true;
130 endpoint.latlng = ll;
139 $(".directions_form .reverse_directions").on("click", function () {
140 var coordFrom = endpoints[0].latlng,
141 coordTo = endpoints[1].latlng,
145 routeFrom = coordFrom.lat + "," + coordFrom.lng;
148 routeTo = coordTo.lat + "," + coordTo.lng;
151 OSM.router.route("/directions?" + Qs.stringify({
152 from: $("#route_to").val(),
153 to: $("#route_from").val(),
154 route: routeTo + ";" + routeFrom
158 $(".directions_form .btn-close").on("click", function (e) {
160 var route_from = endpoints[0].value;
162 OSM.router.route("/?query=" + encodeURIComponent(route_from) + OSM.formatHash(map));
164 OSM.router.route("/" + OSM.formatHash(map));
168 function formatDistance(m) {
170 return I18n.t("javascripts.directions.distance_m", { distance: Math.round(m) });
171 } else if (m < 10000) {
172 return I18n.t("javascripts.directions.distance_km", { distance: (m / 1000.0).toFixed(1) });
174 return I18n.t("javascripts.directions.distance_km", { distance: Math.round(m / 1000) });
178 function formatHeight(m) {
179 return I18n.t("javascripts.directions.distance_m", { distance: Math.round(m) });
182 function formatTime(s) {
183 var m = Math.round(s / 60);
184 var h = Math.floor(m / 60);
186 return h + ":" + (m < 10 ? "0" : "") + m;
189 function findEngine(id) {
190 return engines.findIndex(function (engine) {
191 return engine.id === id;
195 function setEngine(index) {
196 chosenEngine = engines[index];
200 function getRoute(fitRoute, reportErrors) {
201 // Cancel any route that is already in progress
202 if (awaitingRoute) awaitingRoute.abort();
204 // go fetch geocodes for any endpoints which have not already
206 for (var ep_i = 0; ep_i < 2; ++ep_i) {
207 var endpoint = endpoints[ep_i];
208 if (!endpoint.hasGeocode && !endpoint.awaitingGeocode) {
209 endpoint.getGeocode();
212 if (endpoints[0].awaitingGeocode || endpoints[1].awaitingGeocode) {
216 var o = endpoints[0].latlng,
217 d = endpoints[1].latlng;
219 if (!o || !d) return;
220 $("header").addClass("closed");
222 var precision = OSM.zoomPrecision(map.getZoom());
224 OSM.router.replace("/directions?" + Qs.stringify({
225 engine: chosenEngine.id,
226 route: o.lat.toFixed(precision) + "," + o.lng.toFixed(precision) + ";" +
227 d.lat.toFixed(precision) + "," + d.lng.toFixed(precision)
230 // copy loading item to sidebar and display it. we copy it, rather than
231 // just using it in-place and replacing it in case it has to be used
233 $("#sidebar_content").html($(".directions_form .loader_copy").html());
234 map.setSidebarOverlaid(false);
236 awaitingRoute = chosenEngine.getRoute([o, d], function (err, route) {
237 awaitingRoute = null;
240 map.removeLayer(polyline);
243 $("#sidebar_content").html("<div class=\"alert alert-danger\">" + I18n.t("javascripts.directions.errors.no_route") + "</div>");
250 .setLatLngs(route.line)
254 map.fitBounds(polyline.getBounds().pad(0.05));
257 var distanceText = $("<p>").append(
258 I18n.t("javascripts.directions.distance") + ": " + formatDistance(route.distance) + ". " +
259 I18n.t("javascripts.directions.time") + ": " + formatTime(route.time) + ".");
260 if (typeof route.ascend !== "undefined" && typeof route.descend !== "undefined") {
263 I18n.t("javascripts.directions.ascend") + ": " + formatHeight(route.ascend) + ". " +
264 I18n.t("javascripts.directions.descend") + ": " + formatHeight(route.descend) + ".");
267 var turnByTurnTable = $("<table class='table table-hover table-sm mb-3'>")
268 .append($("<tbody>"));
269 var directionsCloseButton = $("<button type='button' class='btn-close'>")
270 .attr("aria-label", I18n.t("javascripts.close"));
272 $("#sidebar_content")
275 $("<div class='d-flex'>").append(
276 $("<h2 class='flex-grow-1 text-break'>")
277 .text(I18n.t("javascripts.directions.directions")),
278 $("<div>").append(directionsCloseButton)),
284 route.steps.forEach(function (step) {
287 instruction = step[2],
293 } else if (dist < 200) {
294 dist = String(Math.round(dist / 10) * 10) + "m";
295 } else if (dist < 1500) {
296 dist = String(Math.round(dist / 100) * 100) + "m";
297 } else if (dist < 5000) {
298 dist = String(Math.round(dist / 100) / 10) + "km";
300 dist = String(Math.round(dist / 1000)) + "km";
303 var row = $("<tr class='turn'/>");
304 row.append("<td class='border-0'><div class='direction i" + direction + "'/></td> ");
305 row.append("<td>" + instruction);
306 row.append("<td class='distance text-body-secondary text-end'>" + dist);
308 row.on("click", function () {
311 .setContent("<p>" + instruction + "</p>")
315 row.hover(function () {
320 map.removeLayer(highlight);
323 turnByTurnTable.append(row);
326 $("#sidebar_content").append("<p class=\"text-center\">" +
327 I18n.t("javascripts.directions.instructions.courtesy", { link: chosenEngine.creditline }) +
330 directionsCloseButton.on("click", function () {
331 map.removeLayer(polyline);
332 $("#sidebar_content").html("");
333 map.setSidebarOverlaid(true);
334 // TODO: collapse width of sidebar back to previous
339 var chosenEngineIndex = findEngine("fossgis_osrm_car");
340 if (Cookies.get("_osm_directions_engine")) {
341 chosenEngineIndex = findEngine(Cookies.get("_osm_directions_engine"));
343 setEngine(chosenEngineIndex);
345 select.on("change", function (e) {
346 chosenEngine = engines[e.target.selectedIndex];
347 Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
348 getRoute(true, true);
351 $(".directions_form").on("submit", function (e) {
353 getRoute(true, true);
356 $(".routing_marker_column img").on("dragstart", function (e) {
357 var dt = e.originalEvent.dataTransfer;
358 dt.effectAllowed = "move";
359 var dragData = { type: $(this).data("type") };
360 dt.setData("text", JSON.stringify(dragData));
361 if (dt.setDragImage) {
362 var img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
363 dt.setDragImage(img.get(0), 12, 21);
369 page.pushstate = page.popstate = function () {
370 $(".search_form").hide();
371 $(".directions_form").show();
373 $("#map").on("dragend dragover", function (e) {
377 $("#map").on("drop", function (e) {
379 var oe = e.originalEvent;
380 var dragData = JSON.parse(oe.dataTransfer.getData("text"));
381 var type = dragData.type;
382 var pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
384 var ll = map.containerPointToLatLng(pt);
385 endpoints[type === "from" ? 0 : 1].setLatLng(ll);
386 getRoute(true, true);
389 var params = Qs.parse(location.search.substring(1)),
390 route = (params.route || "").split(";"),
391 from = route[0] && L.latLng(route[0].split(",")),
392 to = route[1] && L.latLng(route[1].split(","));
395 var engineIndex = findEngine(params.engine);
397 if (engineIndex >= 0) {
398 setEngine(engineIndex);
402 endpoints[0].setValue(params.from || "", from);
403 endpoints[1].setValue(params.to || "", to);
405 map.setSidebarOverlaid(!from || !to);
407 getRoute(true, true);
410 page.load = function () {
414 page.unload = function () {
415 $(".search_form").show();
416 $(".directions_form").hide();
417 $("#map").off("dragend dragover drop");
421 .removeLayer(polyline)
422 .removeLayer(endpoints[0].marker)
423 .removeLayer(endpoints[1].marker);
429 OSM.Directions.engines = [];
431 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
432 if (document.location.protocol === "http:" || supportsHTTPS) {
433 OSM.Directions.engines.push(engine);