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   function Endpoint(input, iconUrl) {
 
  34     endpoint.marker = L.marker([0, 0], {
 
  39         popupAnchor: [1, -34],
 
  40         shadowUrl: OSM.MARKER_SHADOW,
 
  46     endpoint.marker.on('drag dragend', function (e) {
 
  47       var dragging = (e.type === 'drag');
 
  48       if (dragging && !chosenEngine.draggable) return;
 
  49       if (dragging && awaitingRoute) return;
 
  50       endpoint.setLatLng(e.target.getLatLng());
 
  51       if (map.hasLayer(polyline)) {
 
  52         getRoute(false, !dragging);
 
  56     input.on("change", function (e) {
 
  57       awaitingGeocode = true;
 
  59       // make text the same in both text boxes
 
  60       var value = e.target.value;
 
  61       endpoint.setValue(value);
 
  64     endpoint.setValue = function(value, latlng) {
 
  65       endpoint.value = value;
 
  66       delete endpoint.latlng;
 
  70         endpoint.setLatLng(latlng);
 
  72         endpoint.getGeocode();
 
  76     endpoint.getGeocode = function() {
 
  77       // if no one has entered a value yet, then we can't geocode, so don't
 
  79       if (!endpoint.value) {
 
  83       endpoint.awaitingGeocode = true;
 
  85       $.getJSON(OSM.NOMINATIM_URL + 'search?q=' + encodeURIComponent(endpoint.value) + '&format=json', function (json) {
 
  86         endpoint.awaitingGeocode = false;
 
  87         endpoint.hasGeocode = true;
 
  88         if (json.length === 0) {
 
  89           alert(I18n.t('javascripts.directions.errors.no_place'));
 
  93         endpoint.setLatLng(L.latLng(json[0]));
 
  95         input.val(json[0].display_name);
 
  97         if (awaitingGeocode) {
 
  98           awaitingGeocode = false;
 
 104     endpoint.setLatLng = function (ll) {
 
 105       var precision = OSM.zoomPrecision(map.getZoom());
 
 106       input.val(ll.lat.toFixed(precision) + ", " + ll.lng.toFixed(precision));
 
 107       endpoint.hasGeocode = true;
 
 108       endpoint.latlng = ll;
 
 117   $(".directions_form .reverse_directions").on("click", function() {
 
 118     var from = endpoints[0].latlng,
 
 119         to = endpoints[1].latlng;
 
 121     OSM.router.route("/directions?" + querystring.stringify({
 
 122       from: $("#route_to").val(),
 
 123       to: $("#route_from").val(),
 
 124       route: to.lat + "," + to.lng + ";" + from.lat + "," + from.lng
 
 128   $(".directions_form .close").on("click", function(e) {
 
 130     var route_from = endpoints[0].value;
 
 132       OSM.router.route("/?query=" + encodeURIComponent(route_from) + OSM.formatHash(map));
 
 134       OSM.router.route("/" + OSM.formatHash(map));
 
 138   function formatDistance(m) {
 
 140       return Math.round(m) + "m";
 
 141     } else if (m < 10000) {
 
 142       return (m / 1000.0).toFixed(1) + "km";
 
 144       return Math.round(m / 1000) + "km";
 
 148   function formatTime(s) {
 
 149     var m = Math.round(s / 60);
 
 150     var h = Math.floor(m / 60);
 
 152     return h + ":" + (m < 10 ? '0' : '') + m;
 
 155   function setEngine(id) {
 
 156     engines.forEach(function(engine, i) {
 
 157       if (engine.id === id) {
 
 158         chosenEngine = engine;
 
 164   function getRoute(fitRoute, reportErrors) {
 
 165     // Cancel any route that is already in progress
 
 166     if (awaitingRoute) awaitingRoute.abort();
 
 168     // go fetch geocodes for any endpoints which have not already
 
 170     for (var ep_i = 0; ep_i < 2; ++ep_i) {
 
 171       var endpoint = endpoints[ep_i];
 
 172       if (!endpoint.hasGeocode && !endpoint.awaitingGeocode) {
 
 173         endpoint.getGeocode();
 
 174         awaitingGeocode = true;
 
 177     if (endpoints[0].awaitingGeocode || endpoints[1].awaitingGeocode) {
 
 178       awaitingGeocode = true;
 
 182     var o = endpoints[0].latlng,
 
 183         d = endpoints[1].latlng;
 
 185     if (!o || !d) return;
 
 186     $("header").addClass("closed");
 
 188     var precision = OSM.zoomPrecision(map.getZoom());
 
 190     OSM.router.replace("/directions?" + querystring.stringify({
 
 191       engine: chosenEngine.id,
 
 192       route: o.lat.toFixed(precision) + ',' + o.lng.toFixed(precision) + ';' +
 
 193              d.lat.toFixed(precision) + ',' + d.lng.toFixed(precision)
 
 196     // copy loading item to sidebar and display it. we copy it, rather than
 
 197     // just using it in-place and replacing it in case it has to be used
 
 199     $('#sidebar_content').html($('.directions_form .loader_copy').html());
 
 200     map.setSidebarOverlaid(false);
 
 202     awaitingRoute = chosenEngine.getRoute([o, d], function (err, route) {
 
 203       awaitingRoute = null;
 
 206         map.removeLayer(polyline);
 
 209           $('#sidebar_content').html('<p class="search_results_error">' + I18n.t('javascripts.directions.errors.no_route') + '</p>');
 
 216         .setLatLngs(route.line)
 
 220         map.fitBounds(polyline.getBounds().pad(0.05));
 
 223       var html = '<h2><a class="geolink" href="#">' +
 
 224         '<span class="icon close"></span></a>' + I18n.t('javascripts.directions.directions') +
 
 225         '</h2><p id="routing_summary">' +
 
 226         I18n.t('javascripts.directions.distance') + ': ' + formatDistance(route.distance) + '. ' +
 
 227         I18n.t('javascripts.directions.time') + ': ' + formatTime(route.time) + '.';
 
 228       if (typeof route.ascend !== 'undefined' && typeof route.descend !== 'undefined') {
 
 230           I18n.t('javascripts.directions.ascend') + ': ' + Math.round(route.ascend) + 'm. ' +
 
 231           I18n.t('javascripts.directions.descend') + ': ' + Math.round(route.descend) +'m.';
 
 233       html += '</p><table id="turnbyturn" />';
 
 235       $('#sidebar_content')
 
 240       route.steps.forEach(function (step) {
 
 243           instruction = step[2],
 
 251         } else if (dist < 200) {
 
 252           dist = Math.round(dist / 10) * 10 + "m";
 
 253         } else if (dist < 1500) {
 
 254           dist = Math.round(dist / 100) * 100 + "m";
 
 255         } else if (dist < 5000) {
 
 256           dist = Math.round(dist / 100) / 10 + "km";
 
 258           dist = Math.round(dist / 1000) + "km";
 
 261         var row = $("<tr class='turn'/>");
 
 262         row.append("<td><div class='direction i" + direction + "'/></td> ");
 
 263         row.append("<td class='instruction'>" + instruction);
 
 264         row.append("<td class='distance'>" + dist);
 
 266         row.on('click', function () {
 
 269             .setContent("<p>" + instruction + "</p>")
 
 273         row.hover(function () {
 
 278           map.removeLayer(highlight);
 
 281         $('#turnbyturn').append(row);
 
 284       $('#sidebar_content').append('<p id="routing_credit">' +
 
 285         I18n.t('javascripts.directions.instructions.courtesy', {link: chosenEngine.creditline}) +
 
 288       $('#sidebar_content a.geolink').on('click', function(e) {
 
 290         map.removeLayer(polyline);
 
 291         $('#sidebar_content').html('');
 
 292         map.setSidebarOverlaid(true);
 
 293         // TODO: collapse width of sidebar back to previous
 
 298   var engines = OSM.Directions.engines;
 
 300   engines.sort(function (a, b) {
 
 301     a = I18n.t('javascripts.directions.engines.' + a.id);
 
 302     b = I18n.t('javascripts.directions.engines.' + b.id);
 
 303     return a.localeCompare(b);
 
 306   var select = $('select.routing_engines');
 
 308   engines.forEach(function(engine, i) {
 
 309     select.append("<option value='" + i + "'>" + I18n.t('javascripts.directions.engines.' + engine.id) + "</option>");
 
 312   var chosenEngineId = $.cookie('_osm_directions_engine');
 
 313   if(!chosenEngineId) {
 
 314     chosenEngineId = 'osrm_car';
 
 316   setEngine(chosenEngineId);
 
 318   select.on("change", function (e) {
 
 319     chosenEngine = engines[e.target.selectedIndex];
 
 320     $.cookie('_osm_directions_engine', chosenEngine.id, { expires: expiry, path: '/' });
 
 321     if (map.hasLayer(polyline)) {
 
 322       getRoute(true, true);
 
 326   $(".directions_form").on("submit", function(e) {
 
 328     getRoute(true, true);
 
 331   $(".routing_marker").on('dragstart', function (e) {
 
 332     var dt = e.originalEvent.dataTransfer;
 
 333     dt.effectAllowed = 'move';
 
 334     var dragData = { type: $(this).data('type') };
 
 335     dt.setData('text', JSON.stringify(dragData));
 
 336     if (dt.setDragImage) {
 
 337       var img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
 
 338       dt.setDragImage(img.get(0), 12, 21);
 
 344   page.pushstate = page.popstate = function() {
 
 345     $(".search_form").hide();
 
 346     $(".directions_form").show();
 
 348     $("#map").on('dragend dragover', function (e) {
 
 352     $("#map").on('drop', function (e) {
 
 354       var oe = e.originalEvent;
 
 355       var dragData = JSON.parse(oe.dataTransfer.getData('text'));
 
 356       var type = dragData.type;
 
 357       var pt = L.DomEvent.getMousePosition(oe, map.getContainer());  // co-ordinates of the mouse pointer at present
 
 359       var ll = map.containerPointToLatLng(pt);
 
 360       endpoints[type === 'from' ? 0 : 1].setLatLng(ll);
 
 361       getRoute(true, true);
 
 364     var params = querystring.parse(location.search.substring(1)),
 
 365         route = (params.route || '').split(';'),
 
 366         from = route[0] && L.latLng(route[0].split(',')),
 
 367         to = route[1] && L.latLng(route[1].split(','));
 
 370       setEngine(params.engine);
 
 373     endpoints[0].setValue(params.from || "", from);
 
 374     endpoints[1].setValue(params.to || "", to);
 
 376     map.setSidebarOverlaid(!from || !to);
 
 378     getRoute(true, true);
 
 381   page.load = function() {
 
 385   page.unload = function() {
 
 386     $(".search_form").show();
 
 387     $(".directions_form").hide();
 
 388     $("#map").off('dragend dragover drop');
 
 392       .removeLayer(polyline)
 
 393       .removeLayer(endpoints[0].marker)
 
 394       .removeLayer(endpoints[1].marker);
 
 400 OSM.Directions.engines = [];
 
 402 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
 
 403   if (document.location.protocol === "http:" || supportsHTTPS) {
 
 404     OSM.Directions.engines.push(engine);