2 //= require_tree ./directions
4 OSM.Directions = function (map) {
5 var awaitingGeocode; // true if the user has requested a route, but we're waiting on a geocode result
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 a = I18n.t("javascripts.directions.engines." + a.id);
35 b = I18n.t("javascripts.directions.engines." + b.id);
36 return a.localeCompare(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("error");
75 input.on("change", function (e) {
76 awaitingGeocode = true;
78 // make text the same in both text boxes
79 var value = e.target.value;
80 endpoint.setValue(value);
83 endpoint.setValue = function (value, latlng) {
84 endpoint.value = value;
85 delete endpoint.latlng;
86 input.removeClass("error");
90 endpoint.setLatLng(latlng);
92 endpoint.getGeocode();
96 endpoint.getGeocode = function () {
97 // if no one has entered a value yet, then we can't geocode, so don't
99 if (!endpoint.value) {
103 endpoint.awaitingGeocode = true;
105 $.getJSON(OSM.NOMINATIM_URL + "search?q=" + encodeURIComponent(endpoint.value) + "&format=json", function (json) {
106 endpoint.awaitingGeocode = false;
107 endpoint.hasGeocode = true;
108 if (json.length === 0) {
109 input.addClass("error");
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 if (awaitingGeocode) {
119 awaitingGeocode = false;
120 getRoute(true, true);
125 endpoint.setLatLng = function (ll) {
126 var precision = OSM.zoomPrecision(map.getZoom());
127 input.val(ll.lat.toFixed(precision) + ", " + ll.lng.toFixed(precision));
128 endpoint.hasGeocode = true;
129 endpoint.latlng = ll;
138 $(".directions_form .reverse_directions").on("click", function () {
139 var from = endpoints[0].latlng,
140 to = endpoints[1].latlng;
142 OSM.router.route("/directions?" + querystring.stringify({
143 from: $("#route_to").val(),
144 to: $("#route_from").val(),
145 route: to.lat + "," + to.lng + ";" + from.lat + "," + from.lng
149 $(".directions_form .close").on("click", function (e) {
151 var route_from = endpoints[0].value;
153 OSM.router.route("/?query=" + encodeURIComponent(route_from) + OSM.formatHash(map));
155 OSM.router.route("/" + OSM.formatHash(map));
159 function formatDistance(m) {
161 return Math.round(m) + "m";
162 } else if (m < 10000) {
163 return (m / 1000.0).toFixed(1) + "km";
165 return Math.round(m / 1000) + "km";
169 function formatTime(s) {
170 var m = Math.round(s / 60);
171 var h = Math.floor(m / 60);
173 return h + ":" + (m < 10 ? "0" : "") + m;
176 function findEngine(id) {
177 return engines.findIndex(function (engine) {
178 return engine.id === id;
182 function setEngine(index) {
183 chosenEngine = engines[index];
187 function getRoute(fitRoute, reportErrors) {
188 // Cancel any route that is already in progress
189 if (awaitingRoute) awaitingRoute.abort();
191 // go fetch geocodes for any endpoints which have not already
193 for (var ep_i = 0; ep_i < 2; ++ep_i) {
194 var endpoint = endpoints[ep_i];
195 if (!endpoint.hasGeocode && !endpoint.awaitingGeocode) {
196 endpoint.getGeocode();
197 awaitingGeocode = true;
200 if (endpoints[0].awaitingGeocode || endpoints[1].awaitingGeocode) {
201 awaitingGeocode = true;
205 var o = endpoints[0].latlng,
206 d = endpoints[1].latlng;
208 if (!o || !d) return;
209 $("header").addClass("closed");
211 var precision = OSM.zoomPrecision(map.getZoom());
213 OSM.router.replace("/directions?" + querystring.stringify({
214 engine: chosenEngine.id,
215 route: o.lat.toFixed(precision) + "," + o.lng.toFixed(precision) + ";" +
216 d.lat.toFixed(precision) + "," + d.lng.toFixed(precision)
219 // copy loading item to sidebar and display it. we copy it, rather than
220 // just using it in-place and replacing it in case it has to be used
222 $("#sidebar_content").html($(".directions_form .loader_copy").html());
223 map.setSidebarOverlaid(false);
225 awaitingRoute = chosenEngine.getRoute([o, d], function (err, route) {
226 awaitingRoute = null;
229 map.removeLayer(polyline);
232 $("#sidebar_content").html("<p class=\"search_results_error\">" + I18n.t("javascripts.directions.errors.no_route") + "</p>");
239 .setLatLngs(route.line)
243 map.fitBounds(polyline.getBounds().pad(0.05));
246 var html = "<h2><a class=\"geolink\" href=\"#\">" +
247 "<span class=\"icon close\"></span></a>" + I18n.t("javascripts.directions.directions") +
248 "</h2><p id=\"routing_summary\">" +
249 I18n.t("javascripts.directions.distance") + ": " + formatDistance(route.distance) + ". " +
250 I18n.t("javascripts.directions.time") + ": " + formatTime(route.time) + ".";
251 if (typeof route.ascend !== "undefined" && typeof route.descend !== "undefined") {
253 I18n.t("javascripts.directions.ascend") + ": " + Math.round(route.ascend) + "m. " +
254 I18n.t("javascripts.directions.descend") + ": " + Math.round(route.descend) + "m.";
256 html += "</p><table id=\"turnbyturn\" />";
258 $("#sidebar_content")
262 route.steps.forEach(function (step) {
265 instruction = step[2],
271 } else if (dist < 200) {
272 dist = String(Math.round(dist / 10) * 10) + "m";
273 } else if (dist < 1500) {
274 dist = String(Math.round(dist / 100) * 100) + "m";
275 } else if (dist < 5000) {
276 dist = String(Math.round(dist / 100) / 10) + "km";
278 dist = String(Math.round(dist / 1000)) + "km";
281 var row = $("<tr class='turn'/>");
282 row.append("<td><div class='direction i" + direction + "'/></td> ");
283 row.append("<td class='instruction'>" + instruction);
284 row.append("<td class='distance'>" + dist);
286 row.on("click", function () {
289 .setContent("<p>" + instruction + "</p>")
293 row.hover(function () {
298 map.removeLayer(highlight);
301 $("#turnbyturn").append(row);
304 $("#sidebar_content").append("<p id=\"routing_credit\">" +
305 I18n.t("javascripts.directions.instructions.courtesy", { link: chosenEngine.creditline }) +
308 $("#sidebar_content a.geolink").on("click", function (e) {
310 map.removeLayer(polyline);
311 $("#sidebar_content").html("");
312 map.setSidebarOverlaid(true);
313 // TODO: collapse width of sidebar back to previous
318 var chosenEngineIndex = findEngine("fossgis_osrm_car");
319 if ($.cookie("_osm_directions_engine")) {
320 chosenEngineIndex = findEngine($.cookie("_osm_directions_engine"));
322 setEngine(chosenEngineIndex);
324 select.on("change", function (e) {
325 chosenEngine = engines[e.target.selectedIndex];
326 $.cookie("_osm_directions_engine", chosenEngine.id, { expires: expiry, path: "/" });
327 if (map.hasLayer(polyline)) {
328 getRoute(true, true);
332 $(".directions_form").on("submit", function (e) {
334 getRoute(true, true);
337 $(".routing_marker").on("dragstart", function (e) {
338 var dt = e.originalEvent.dataTransfer;
339 dt.effectAllowed = "move";
340 var dragData = { type: $(this).data("type") };
341 dt.setData("text", JSON.stringify(dragData));
342 if (dt.setDragImage) {
343 var img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
344 dt.setDragImage(img.get(0), 12, 21);
350 page.pushstate = page.popstate = function () {
351 $(".search_form").hide();
352 $(".directions_form").show();
354 $("#map").on("dragend dragover", function (e) {
358 $("#map").on("drop", function (e) {
360 var oe = e.originalEvent;
361 var dragData = JSON.parse(oe.dataTransfer.getData("text"));
362 var type = dragData.type;
363 var pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
365 var ll = map.containerPointToLatLng(pt);
366 endpoints[type === "from" ? 0 : 1].setLatLng(ll);
367 getRoute(true, true);
370 var params = querystring.parse(location.search.substring(1)),
371 route = (params.route || "").split(";"),
372 from = route[0] && L.latLng(route[0].split(",")),
373 to = route[1] && L.latLng(route[1].split(","));
376 var engineIndex = findEngine(params.engine);
378 if (engineIndex >= 0) {
379 setEngine(engineIndex);
383 endpoints[0].setValue(params.from || "", from);
384 endpoints[1].setValue(params.to || "", to);
386 map.setSidebarOverlaid(!from || !to);
388 getRoute(true, true);
391 page.load = function () {
395 page.unload = function () {
396 $(".search_form").show();
397 $(".directions_form").hide();
398 $("#map").off("dragend dragover drop");
402 .removeLayer(polyline)
403 .removeLayer(endpoints[0].marker)
404 .removeLayer(endpoints[1].marker);
410 OSM.Directions.engines = [];
412 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
413 if (document.location.protocol === "http:" || supportsHTTPS) {
414 OSM.Directions.engines.push(engine);