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);
28 var endpointGeocodeCallback = function () {
33 Endpoint($("input[name='route_from']"), OSM.MARKER_GREEN, endpointDragCallback, endpointGeocodeCallback),
34 Endpoint($("input[name='route_to']"), OSM.MARKER_RED, endpointDragCallback, endpointGeocodeCallback)
37 var expiry = new Date();
38 expiry.setYear(expiry.getFullYear() + 10);
40 var engines = OSM.Directions.engines;
42 engines.sort(function (a, b) {
43 var localised_a = I18n.t("javascripts.directions.engines." + a.id),
44 localised_b = I18n.t("javascripts.directions.engines." + b.id);
45 return localised_a.localeCompare(localised_b);
48 var select = $("select.routing_engines");
50 engines.forEach(function (engine, i) {
51 select.append("<option value='" + i + "'>" + I18n.t("javascripts.directions.engines." + engine.id) + "</option>");
54 function Endpoint(input, iconUrl, dragCallback, geocodeCallback) {
57 endpoint.marker = L.marker([0, 0], {
62 popupAnchor: [1, -34],
63 shadowUrl: OSM.MARKER_SHADOW,
70 endpoint.marker.on("drag dragend", function (e) {
71 var dragging = (e.type === "drag");
72 if (dragging && !chosenEngine.draggable) return;
73 if (dragging && awaitingRoute) return;
74 endpoint.setLatLng(e.target.getLatLng());
75 dragCallback(dragging);
78 input.on("keydown", function () {
79 input.removeClass("is-invalid");
82 input.on("change", function (e) {
83 // make text the same in both text boxes
84 var value = e.target.value;
85 endpoint.setValue(value);
88 endpoint.setValue = function (value, latlng) {
89 endpoint.value = value;
90 delete endpoint.latlng;
91 input.removeClass("is-invalid");
95 endpoint.setLatLng(latlng);
97 endpoint.getGeocode();
101 endpoint.getGeocode = function () {
102 // if no one has entered a value yet, then we can't geocode, so don't
104 if (!endpoint.value) {
108 endpoint.awaitingGeocode = true;
110 var viewbox = map.getBounds().toBBoxString(); // <sw lon>,<sw lat>,<ne lon>,<ne lat>
112 $.getJSON(OSM.NOMINATIM_URL + "search?q=" + encodeURIComponent(endpoint.value) + "&format=json&viewbox=" + viewbox, function (json) {
113 endpoint.awaitingGeocode = false;
114 endpoint.hasGeocode = true;
115 if (json.length === 0) {
116 input.addClass("is-invalid");
117 alert(I18n.t("javascripts.directions.errors.no_place", { place: endpoint.value }));
121 endpoint.setLatLng(L.latLng(json[0]));
123 input.val(json[0].display_name);
129 endpoint.setLatLng = function (ll) {
130 var precision = OSM.zoomPrecision(map.getZoom());
131 input.val(ll.lat.toFixed(precision) + ", " + ll.lng.toFixed(precision));
132 endpoint.hasGeocode = true;
133 endpoint.latlng = ll;
142 $(".directions_form .reverse_directions").on("click", function () {
143 var coordFrom = endpoints[0].latlng,
144 coordTo = endpoints[1].latlng,
148 routeFrom = coordFrom.lat + "," + coordFrom.lng;
151 routeTo = coordTo.lat + "," + coordTo.lng;
154 OSM.router.route("/directions?" + Qs.stringify({
155 from: $("#route_to").val(),
156 to: $("#route_from").val(),
157 route: routeTo + ";" + routeFrom
161 $(".directions_form .btn-close").on("click", function (e) {
163 var route_from = endpoints[0].value;
165 OSM.router.route("/?query=" + encodeURIComponent(route_from) + OSM.formatHash(map));
167 OSM.router.route("/" + OSM.formatHash(map));
171 function formatDistance(m) {
173 return I18n.t("javascripts.directions.distance_m", { distance: Math.round(m) });
174 } else if (m < 10000) {
175 return I18n.t("javascripts.directions.distance_km", { distance: (m / 1000.0).toFixed(1) });
177 return I18n.t("javascripts.directions.distance_km", { distance: Math.round(m / 1000) });
181 function formatHeight(m) {
182 return I18n.t("javascripts.directions.distance_m", { distance: Math.round(m) });
185 function formatTime(s) {
186 var m = Math.round(s / 60);
187 var h = Math.floor(m / 60);
189 return h + ":" + (m < 10 ? "0" : "") + m;
192 function findEngine(id) {
193 return engines.findIndex(function (engine) {
194 return engine.id === id;
198 function setEngine(index) {
199 chosenEngine = engines[index];
203 function getRoute(fitRoute, reportErrors) {
204 // Cancel any route that is already in progress
205 if (awaitingRoute) awaitingRoute.abort();
207 // go fetch geocodes for any endpoints which have not already
209 for (var ep_i = 0; ep_i < 2; ++ep_i) {
210 var endpoint = endpoints[ep_i];
211 if (!endpoint.hasGeocode && !endpoint.awaitingGeocode) {
212 endpoint.getGeocode();
215 if (endpoints[0].awaitingGeocode || endpoints[1].awaitingGeocode) {
219 var o = endpoints[0].latlng,
220 d = endpoints[1].latlng;
222 if (!o || !d) return;
223 $("header").addClass("closed");
225 var precision = OSM.zoomPrecision(map.getZoom());
227 OSM.router.replace("/directions?" + Qs.stringify({
228 engine: chosenEngine.id,
229 route: o.lat.toFixed(precision) + "," + o.lng.toFixed(precision) + ";" +
230 d.lat.toFixed(precision) + "," + d.lng.toFixed(precision)
233 // copy loading item to sidebar and display it. we copy it, rather than
234 // just using it in-place and replacing it in case it has to be used
236 $("#sidebar_content").html($(".directions_form .loader_copy").html());
237 map.setSidebarOverlaid(false);
239 awaitingRoute = chosenEngine.getRoute([o, d], function (err, route) {
240 awaitingRoute = null;
243 map.removeLayer(polyline);
246 $("#sidebar_content").html("<div class=\"alert alert-danger\">" + I18n.t("javascripts.directions.errors.no_route") + "</div>");
253 .setLatLngs(route.line)
257 map.fitBounds(polyline.getBounds().pad(0.05));
260 var distanceText = $("<p>").append(
261 I18n.t("javascripts.directions.distance") + ": " + formatDistance(route.distance) + ". " +
262 I18n.t("javascripts.directions.time") + ": " + formatTime(route.time) + ".");
263 if (typeof route.ascend !== "undefined" && typeof route.descend !== "undefined") {
266 I18n.t("javascripts.directions.ascend") + ": " + formatHeight(route.ascend) + ". " +
267 I18n.t("javascripts.directions.descend") + ": " + formatHeight(route.descend) + ".");
270 var turnByTurnTable = $("<table class='table table-hover table-sm mb-3'>")
271 .append($("<tbody>"));
272 var directionsCloseButton = $("<button type='button' class='btn-close'>")
273 .attr("aria-label", I18n.t("javascripts.close"));
275 $("#sidebar_content")
278 $("<div class='d-flex'>").append(
279 $("<h2 class='flex-grow-1 text-break'>")
280 .text(I18n.t("javascripts.directions.directions")),
281 $("<div>").append(directionsCloseButton)),
287 route.steps.forEach(function (step) {
290 instruction = step[2],
296 } else if (dist < 200) {
297 dist = String(Math.round(dist / 10) * 10) + "m";
298 } else if (dist < 1500) {
299 dist = String(Math.round(dist / 100) * 100) + "m";
300 } else if (dist < 5000) {
301 dist = String(Math.round(dist / 100) / 10) + "km";
303 dist = String(Math.round(dist / 1000)) + "km";
306 var row = $("<tr class='turn'/>");
307 row.append("<td class='border-0'><div class='direction i" + direction + "'/></td> ");
308 row.append("<td>" + instruction);
309 row.append("<td class='distance text-body-secondary text-end'>" + dist);
311 row.on("click", function () {
314 .setContent("<p>" + instruction + "</p>")
318 row.hover(function () {
323 map.removeLayer(highlight);
326 turnByTurnTable.append(row);
329 $("#sidebar_content").append("<p class=\"text-center\">" +
330 I18n.t("javascripts.directions.instructions.courtesy", { link: chosenEngine.creditline }) +
333 directionsCloseButton.on("click", function () {
334 map.removeLayer(polyline);
335 $("#sidebar_content").html("");
336 map.setSidebarOverlaid(true);
337 // TODO: collapse width of sidebar back to previous
342 var chosenEngineIndex = findEngine("fossgis_osrm_car");
343 if (Cookies.get("_osm_directions_engine")) {
344 chosenEngineIndex = findEngine(Cookies.get("_osm_directions_engine"));
346 setEngine(chosenEngineIndex);
348 select.on("change", function (e) {
349 chosenEngine = engines[e.target.selectedIndex];
350 Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
351 getRoute(true, true);
354 $(".directions_form").on("submit", function (e) {
356 getRoute(true, true);
359 $(".routing_marker_column img").on("dragstart", function (e) {
360 var dt = e.originalEvent.dataTransfer;
361 dt.effectAllowed = "move";
362 var dragData = { type: $(this).data("type") };
363 dt.setData("text", JSON.stringify(dragData));
364 if (dt.setDragImage) {
365 var img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
366 dt.setDragImage(img.get(0), 12, 21);
372 page.pushstate = page.popstate = function () {
373 $(".search_form").hide();
374 $(".directions_form").show();
376 $("#map").on("dragend dragover", function (e) {
380 $("#map").on("drop", function (e) {
382 var oe = e.originalEvent;
383 var dragData = JSON.parse(oe.dataTransfer.getData("text"));
384 var type = dragData.type;
385 var pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
387 var ll = map.containerPointToLatLng(pt);
388 endpoints[type === "from" ? 0 : 1].setLatLng(ll);
389 getRoute(true, true);
392 var params = Qs.parse(location.search.substring(1)),
393 route = (params.route || "").split(";"),
394 from = route[0] && L.latLng(route[0].split(",")),
395 to = route[1] && L.latLng(route[1].split(","));
398 var engineIndex = findEngine(params.engine);
400 if (engineIndex >= 0) {
401 setEngine(engineIndex);
405 endpoints[0].setValue(params.from || "", from);
406 endpoints[1].setValue(params.to || "", to);
408 map.setSidebarOverlaid(!from || !to);
410 getRoute(true, true);
413 page.load = function () {
417 page.unload = function () {
418 $(".search_form").show();
419 $(".directions_form").hide();
420 $("#map").off("dragend dragover drop");
424 .removeLayer(polyline)
425 .removeLayer(endpoints[0].marker)
426 .removeLayer(endpoints[1].marker);
432 OSM.Directions.engines = [];
434 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
435 if (document.location.protocol === "http:" || supportsHTTPS) {
436 OSM.Directions.engines.push(engine);