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,
47 endpoint.marker.on('drag dragend', function (e) {
48 var dragging = (e.type === 'drag');
49 if (dragging && !chosenEngine.draggable) return;
50 if (dragging && awaitingRoute) return;
51 endpoint.setLatLng(e.target.getLatLng());
52 if (map.hasLayer(polyline)) {
53 getRoute(false, !dragging);
57 input.on("keydown", function() {
58 input.removeClass("error");
61 input.on("change", function (e) {
62 awaitingGeocode = true;
64 // make text the same in both text boxes
65 var value = e.target.value;
66 endpoint.setValue(value);
69 endpoint.setValue = function(value, latlng) {
70 endpoint.value = value;
71 delete endpoint.latlng;
72 input.removeClass("error");
76 endpoint.setLatLng(latlng);
78 endpoint.getGeocode();
82 endpoint.getGeocode = function() {
83 // if no one has entered a value yet, then we can't geocode, so don't
85 if (!endpoint.value) {
89 endpoint.awaitingGeocode = true;
91 $.getJSON(OSM.NOMINATIM_URL + 'search?q=' + encodeURIComponent(endpoint.value) + '&format=json', function (json) {
92 endpoint.awaitingGeocode = false;
93 endpoint.hasGeocode = true;
94 if (json.length === 0) {
95 input.addClass("error");
96 alert(I18n.t('javascripts.directions.errors.no_place', {place: endpoint.value}));
100 endpoint.setLatLng(L.latLng(json[0]));
102 input.val(json[0].display_name);
104 if (awaitingGeocode) {
105 awaitingGeocode = false;
106 getRoute(true, true);
111 endpoint.setLatLng = function (ll) {
112 var precision = OSM.zoomPrecision(map.getZoom());
113 input.val(ll.lat.toFixed(precision) + ", " + ll.lng.toFixed(precision));
114 endpoint.hasGeocode = true;
115 endpoint.latlng = ll;
124 $(".directions_form .reverse_directions").on("click", function() {
125 var from = endpoints[0].latlng,
126 to = endpoints[1].latlng;
128 OSM.router.route("/directions?" + querystring.stringify({
129 from: $("#route_to").val(),
130 to: $("#route_from").val(),
131 route: to.lat + "," + to.lng + ";" + from.lat + "," + from.lng
135 $(".directions_form .close").on("click", function(e) {
137 var route_from = endpoints[0].value;
139 OSM.router.route("/?query=" + encodeURIComponent(route_from) + OSM.formatHash(map));
141 OSM.router.route("/" + OSM.formatHash(map));
145 function formatDistance(m) {
147 return Math.round(m) + "m";
148 } else if (m < 10000) {
149 return (m / 1000.0).toFixed(1) + "km";
151 return Math.round(m / 1000) + "km";
155 function formatTime(s) {
156 var m = Math.round(s / 60);
157 var h = Math.floor(m / 60);
159 return h + ":" + (m < 10 ? '0' : '') + m;
162 function setEngine(id) {
163 engines.forEach(function(engine, i) {
164 if (engine.id === id) {
165 chosenEngine = engine;
171 function getRoute(fitRoute, reportErrors) {
172 // Cancel any route that is already in progress
173 if (awaitingRoute) awaitingRoute.abort();
175 // go fetch geocodes for any endpoints which have not already
177 for (var ep_i = 0; ep_i < 2; ++ep_i) {
178 var endpoint = endpoints[ep_i];
179 if (!endpoint.hasGeocode && !endpoint.awaitingGeocode) {
180 endpoint.getGeocode();
181 awaitingGeocode = true;
184 if (endpoints[0].awaitingGeocode || endpoints[1].awaitingGeocode) {
185 awaitingGeocode = true;
189 var o = endpoints[0].latlng,
190 d = endpoints[1].latlng;
192 if (!o || !d) return;
193 $("header").addClass("closed");
195 var precision = OSM.zoomPrecision(map.getZoom());
197 OSM.router.replace("/directions?" + querystring.stringify({
198 engine: chosenEngine.id,
199 route: o.lat.toFixed(precision) + ',' + o.lng.toFixed(precision) + ';' +
200 d.lat.toFixed(precision) + ',' + d.lng.toFixed(precision)
203 // copy loading item to sidebar and display it. we copy it, rather than
204 // just using it in-place and replacing it in case it has to be used
206 $('#sidebar_content').html($('.directions_form .loader_copy').html());
207 map.setSidebarOverlaid(false);
209 awaitingRoute = chosenEngine.getRoute([o, d], function (err, route) {
210 awaitingRoute = null;
213 map.removeLayer(polyline);
216 $('#sidebar_content').html('<p class="search_results_error">' + I18n.t('javascripts.directions.errors.no_route') + '</p>');
223 .setLatLngs(route.line)
227 map.fitBounds(polyline.getBounds().pad(0.05));
230 var html = '<h2><a class="geolink" href="#">' +
231 '<span class="icon close"></span></a>' + I18n.t('javascripts.directions.directions') +
232 '</h2><p id="routing_summary">' +
233 I18n.t('javascripts.directions.distance') + ': ' + formatDistance(route.distance) + '. ' +
234 I18n.t('javascripts.directions.time') + ': ' + formatTime(route.time) + '.';
235 if (typeof route.ascend !== 'undefined' && typeof route.descend !== 'undefined') {
237 I18n.t('javascripts.directions.ascend') + ': ' + Math.round(route.ascend) + 'm. ' +
238 I18n.t('javascripts.directions.descend') + ': ' + Math.round(route.descend) +'m.';
240 html += '</p><table id="turnbyturn" />';
242 $('#sidebar_content')
247 route.steps.forEach(function (step) {
250 instruction = step[2],
258 } else if (dist < 200) {
259 dist = Math.round(dist / 10) * 10 + "m";
260 } else if (dist < 1500) {
261 dist = Math.round(dist / 100) * 100 + "m";
262 } else if (dist < 5000) {
263 dist = Math.round(dist / 100) / 10 + "km";
265 dist = Math.round(dist / 1000) + "km";
268 var row = $("<tr class='turn'/>");
269 row.append("<td><div class='direction i" + direction + "'/></td> ");
270 row.append("<td class='instruction'>" + instruction);
271 row.append("<td class='distance'>" + dist);
273 row.on('click', function () {
276 .setContent("<p>" + instruction + "</p>")
280 row.hover(function () {
285 map.removeLayer(highlight);
288 $('#turnbyturn').append(row);
291 $('#sidebar_content').append('<p id="routing_credit">' +
292 I18n.t('javascripts.directions.instructions.courtesy', {link: chosenEngine.creditline}) +
295 $('#sidebar_content a.geolink').on('click', function(e) {
297 map.removeLayer(polyline);
298 $('#sidebar_content').html('');
299 map.setSidebarOverlaid(true);
300 // TODO: collapse width of sidebar back to previous
305 var engines = OSM.Directions.engines;
307 engines.sort(function (a, b) {
308 a = I18n.t('javascripts.directions.engines.' + a.id);
309 b = I18n.t('javascripts.directions.engines.' + b.id);
310 return a.localeCompare(b);
313 var select = $('select.routing_engines');
315 engines.forEach(function(engine, i) {
316 select.append("<option value='" + i + "'>" + I18n.t('javascripts.directions.engines.' + engine.id) + "</option>");
319 var chosenEngineId = $.cookie('_osm_directions_engine');
320 if(!chosenEngineId) {
321 chosenEngineId = 'osrm_car';
323 setEngine(chosenEngineId);
325 select.on("change", function (e) {
326 chosenEngine = engines[e.target.selectedIndex];
327 $.cookie('_osm_directions_engine', chosenEngine.id, { expires: expiry, path: '/' });
328 if (map.hasLayer(polyline)) {
329 getRoute(true, true);
333 $(".directions_form").on("submit", function(e) {
335 getRoute(true, true);
338 $(".routing_marker").on('dragstart', function (e) {
339 var dt = e.originalEvent.dataTransfer;
340 dt.effectAllowed = 'move';
341 var dragData = { type: $(this).data('type') };
342 dt.setData('text', JSON.stringify(dragData));
343 if (dt.setDragImage) {
344 var img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
345 dt.setDragImage(img.get(0), 12, 21);
351 page.pushstate = page.popstate = function() {
352 $(".search_form").hide();
353 $(".directions_form").show();
355 $("#map").on('dragend dragover', function (e) {
359 $("#map").on('drop', function (e) {
361 var oe = e.originalEvent;
362 var dragData = JSON.parse(oe.dataTransfer.getData('text'));
363 var type = dragData.type;
364 var pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
366 var ll = map.containerPointToLatLng(pt);
367 endpoints[type === 'from' ? 0 : 1].setLatLng(ll);
368 getRoute(true, true);
371 var params = querystring.parse(location.search.substring(1)),
372 route = (params.route || '').split(';'),
373 from = route[0] && L.latLng(route[0].split(',')),
374 to = route[1] && L.latLng(route[1].split(','));
377 setEngine(params.engine);
380 endpoints[0].setValue(params.from || "", from);
381 endpoints[1].setValue(params.to || "", to);
383 map.setSidebarOverlaid(!from || !to);
385 getRoute(true, true);
388 page.load = function() {
392 page.unload = function() {
393 $(".search_form").show();
394 $(".directions_form").hide();
395 $("#map").off('dragend dragover drop');
399 .removeLayer(polyline)
400 .removeLayer(endpoints[0].marker)
401 .removeLayer(endpoints[1].marker);
407 OSM.Directions.engines = [];
409 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
410 if (document.location.protocol === "http:" || supportsHTTPS) {
411 OSM.Directions.engines.push(engine);