2 //= require_tree ./directions
5 OSM.Directions = function (map) {
6 var awaitingGeocode; // true if the user has requested a route, but we're waiting on a geocode result
7 var awaitingRoute; // true if we've asked the engine for a route and are waiting to hear back
10 var popup = L.popup({ autoPanPadding: [100, 100] });
12 var polyline = L.polyline([], {
18 var highlight = L.polyline([], {
25 Endpoint($("input[name='route_from']"), OSM.MARKER_GREEN),
26 Endpoint($("input[name='route_to']"), OSM.MARKER_RED)
29 var expiry = new Date();
30 expiry.setYear(expiry.getFullYear() + 10);
32 var engines = OSM.Directions.engines;
34 engines.sort(function (a, b) {
35 var localised_a = I18n.t("javascripts.directions.engines." + a.id),
36 localised_b = I18n.t("javascripts.directions.engines." + b.id);
37 return localised_a.localeCompare(localised_b);
40 var select = $("select.routing_engines");
42 engines.forEach(function (engine, i) {
43 select.append("<option value='" + i + "'>" + I18n.t("javascripts.directions.engines." + engine.id) + "</option>");
46 function Endpoint(input, iconUrl) {
49 endpoint.marker = L.marker([0, 0], {
54 popupAnchor: [1, -34],
55 shadowUrl: OSM.MARKER_SHADOW,
62 endpoint.marker.on("drag dragend", function (e) {
63 var dragging = (e.type === "drag");
64 if (dragging && !chosenEngine.draggable) return;
65 if (dragging && awaitingRoute) return;
66 endpoint.setLatLng(e.target.getLatLng());
67 if (map.hasLayer(polyline)) {
68 getRoute(false, !dragging);
72 input.on("keydown", function () {
73 input.removeClass("error");
76 input.on("change", function (e) {
77 awaitingGeocode = true;
79 // make text the same in both text boxes
80 var value = e.target.value;
81 endpoint.setValue(value);
84 endpoint.setValue = function (value, latlng) {
85 endpoint.value = value;
86 delete endpoint.latlng;
87 input.removeClass("error");
91 endpoint.setLatLng(latlng);
93 endpoint.getGeocode();
97 endpoint.getGeocode = function () {
98 // if no one has entered a value yet, then we can't geocode, so don't
100 if (!endpoint.value) {
104 endpoint.awaitingGeocode = true;
106 var viewbox = map.getBounds().toBBoxString(); // <sw lon>,<sw lat>,<ne lon>,<ne lat>
108 $.getJSON(OSM.NOMINATIM_URL + "search?q=" + encodeURIComponent(endpoint.value) + "&format=json&viewbox=" + viewbox, function (json) {
109 endpoint.awaitingGeocode = false;
110 endpoint.hasGeocode = true;
111 if (json.length === 0) {
112 input.addClass("error");
113 alert(I18n.t("javascripts.directions.errors.no_place", { place: endpoint.value }));
117 endpoint.setLatLng(L.latLng(json[0]));
119 input.val(json[0].display_name);
121 if (awaitingGeocode) {
122 awaitingGeocode = false;
123 getRoute(true, true);
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 Math.round(m) + "m";
173 } else if (m < 10000) {
174 return (m / 1000.0).toFixed(1) + "km";
176 return Math.round(m / 1000) + "km";
180 function formatTime(s) {
181 var m = Math.round(s / 60);
182 var h = Math.floor(m / 60);
184 return h + ":" + (m < 10 ? "0" : "") + m;
187 function findEngine(id) {
188 return engines.findIndex(function (engine) {
189 return engine.id === id;
193 function setEngine(index) {
194 chosenEngine = engines[index];
198 function getRoute(fitRoute, reportErrors) {
199 // Cancel any route that is already in progress
200 if (awaitingRoute) awaitingRoute.abort();
202 // go fetch geocodes for any endpoints which have not already
204 for (var ep_i = 0; ep_i < 2; ++ep_i) {
205 var endpoint = endpoints[ep_i];
206 if (!endpoint.hasGeocode && !endpoint.awaitingGeocode) {
207 endpoint.getGeocode();
208 awaitingGeocode = true;
211 if (endpoints[0].awaitingGeocode || endpoints[1].awaitingGeocode) {
212 awaitingGeocode = true;
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("<p class=\"search_results_error\">" + I18n.t("javascripts.directions.errors.no_route") + "</p>");
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") + ": " + Math.round(route.ascend) + "m. " +
264 I18n.t("javascripts.directions.descend") + ": " + Math.round(route.descend) + "m.");
267 var turnByTurnTable = $("<table class='mb-3'>");
269 $("#sidebar_content")
272 $("<div class='d-flex'>").append(
273 $("<div class='flex-grow-1 text-break'>").append(
275 .text(I18n.t("javascripts.directions.directions"))),
277 $("<a class='geolink' href='#'>").append(
278 $("<button type='button' class='btn-close mt-1'>")))),
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><div class='direction i" + direction + "'/></td> ");
305 row.append("<td class='instruction'>" + instruction);
306 row.append("<td class='distance'>" + 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 $("#sidebar_content a.geolink").on("click", function (e) {
332 map.removeLayer(polyline);
333 $("#sidebar_content").html("");
334 map.setSidebarOverlaid(true);
335 // TODO: collapse width of sidebar back to previous
340 var chosenEngineIndex = findEngine("fossgis_osrm_car");
341 if (Cookies.get("_osm_directions_engine")) {
342 chosenEngineIndex = findEngine(Cookies.get("_osm_directions_engine"));
344 setEngine(chosenEngineIndex);
346 select.on("change", function (e) {
347 chosenEngine = engines[e.target.selectedIndex];
348 Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
349 getRoute(true, true);
352 $(".directions_form").on("submit", function (e) {
354 getRoute(true, true);
357 $(".routing_marker").on("dragstart", function (e) {
358 var dt = e.originalEvent.dataTransfer;
359 dt.effectAllowed = "move";
360 var dragData = { type: $(this).data("type") };
361 dt.setData("text", JSON.stringify(dragData));
362 if (dt.setDragImage) {
363 var img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
364 dt.setDragImage(img.get(0), 12, 21);
370 page.pushstate = page.popstate = function () {
371 $(".search_form").hide();
372 $(".directions_form").show();
374 $("#map").on("dragend dragover", function (e) {
378 $("#map").on("drop", function (e) {
380 var oe = e.originalEvent;
381 var dragData = JSON.parse(oe.dataTransfer.getData("text"));
382 var type = dragData.type;
383 var pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
385 var ll = map.containerPointToLatLng(pt);
386 endpoints[type === "from" ? 0 : 1].setLatLng(ll);
387 getRoute(true, true);
390 var params = Qs.parse(location.search.substring(1)),
391 route = (params.route || "").split(";"),
392 from = route[0] && L.latLng(route[0].split(",")),
393 to = route[1] && L.latLng(route[1].split(","));
396 var engineIndex = findEngine(params.engine);
398 if (engineIndex >= 0) {
399 setEngine(engineIndex);
403 endpoints[0].setValue(params.from || "", from);
404 endpoints[1].setValue(params.to || "", to);
406 map.setSidebarOverlaid(!from || !to);
408 getRoute(true, true);
411 page.load = function () {
415 page.unload = function () {
416 $(".search_form").show();
417 $(".directions_form").hide();
418 $("#map").off("dragend dragover drop");
422 .removeLayer(polyline)
423 .removeLayer(endpoints[0].marker)
424 .removeLayer(endpoints[1].marker);
430 OSM.Directions.engines = [];
432 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
433 if (document.location.protocol === "http:" || supportsHTTPS) {
434 OSM.Directions.engines.push(engine);