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
7 var dragging; // true if the user is dragging a start/end point
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 function Endpoint(input, iconUrl) {
35 endpoint.marker = L.marker([0, 0], {
40 popupAnchor: [1, -34],
41 shadowUrl: OSM.MARKER_SHADOW,
47 endpoint.marker.on('drag dragend', function (e) {
48 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)) {
57 input.on("change", function (e) {
58 // make text the same in both text boxes
59 var value = e.target.value;
60 endpoint.setValue(value);
63 endpoint.setValue = function(value, latlng) {
64 endpoint.value = value;
65 delete endpoint.latlng;
69 endpoint.setLatLng(latlng);
71 endpoint.getGeocode();
75 endpoint.getGeocode = function() {
76 // if no one has entered a value yet, then we can't geocode, so don't
78 if (!endpoint.value) {
82 endpoint.awaitingGeocode = true;
84 $.getJSON(OSM.NOMINATIM_URL + 'search?q=' + encodeURIComponent(endpoint.value) + '&format=json', function (json) {
85 endpoint.awaitingGeocode = false;
86 endpoint.hasGeocode = true;
87 if (json.length === 0) {
88 alert(I18n.t('javascripts.directions.errors.no_place'));
92 input.val(json[0].display_name);
94 endpoint.latlng = L.latLng(json[0]);
96 .setLatLng(endpoint.latlng)
99 if (awaitingGeocode) {
100 awaitingGeocode = false;
106 endpoint.setLatLng = function (ll) {
107 var precision = OSM.zoomPrecision(map.getZoom());
108 input.val(ll.lat.toFixed(precision) + ", " + ll.lng.toFixed(precision));
109 endpoint.hasGeocode = true;
110 endpoint.latlng = ll;
119 $(".directions_form .reverse_directions").on("click", function() {
120 var from = endpoints[0].latlng,
121 to = endpoints[1].latlng;
123 OSM.router.route("/directions?" + querystring.stringify({
124 from: $("#route_to").val(),
125 to: $("#route_from").val(),
126 route: from.lat + "," + from.lng + ";" + to.lat + "," + to.lng
130 $(".directions_form .close").on("click", function(e) {
132 var route_from = endpoints[0].value;
134 OSM.router.route("/?query=" + encodeURIComponent(route_from) + OSM.formatHash(map));
136 OSM.router.route("/" + OSM.formatHash(map));
140 function formatDistance(m) {
142 return Math.round(m) + "m";
143 } else if (m < 10000) {
144 return (m / 1000.0).toFixed(1) + "km";
146 return Math.round(m / 1000) + "km";
150 function formatTime(s) {
151 var m = Math.round(s / 60);
152 var h = Math.floor(m / 60);
154 return h + ":" + (m < 10 ? '0' : '') + m;
157 function setEngine(id) {
158 engines.forEach(function(engine, i) {
159 if (engine.id === id) {
160 chosenEngine = engine;
166 function getRoute() {
167 // Cancel any route that is already in progress
168 if (awaitingRoute) awaitingRoute.abort();
170 // go fetch geocodes for any endpoints which have not already
172 for (var ep_i = 0; ep_i < 2; ++ep_i) {
173 var endpoint = endpoints[ep_i];
174 if (!endpoint.hasGeocode && !endpoint.awaitingGeocode) {
175 endpoint.getGeocode();
176 awaitingGeocode = true;
179 if (endpoints[0].awaitingGeocode || endpoints[1].awaitingGeocode) {
180 awaitingGeocode = true;
184 var o = endpoints[0].latlng,
185 d = endpoints[1].latlng;
187 if (!o || !d) return;
188 $("header").addClass("closed");
190 var precision = OSM.zoomPrecision(map.getZoom());
192 OSM.router.replace("/directions?" + querystring.stringify({
193 engine: chosenEngine.id,
194 route: o.lat.toFixed(precision) + ',' + o.lng.toFixed(precision) + ';' +
195 d.lat.toFixed(precision) + ',' + d.lng.toFixed(precision)
198 // copy loading item to sidebar and display it. we copy it, rather than
199 // just using it in-place and replacing it in case it has to be used
201 $('#sidebar_content').html($('.directions_form .loader_copy').html());
202 map.setSidebarOverlaid(false);
204 awaitingRoute = chosenEngine.getRoute([o, d], function (err, route) {
205 awaitingRoute = null;
208 map.removeLayer(polyline);
211 $('#sidebar_content').html('<p class="search_results_error">' + I18n.t('javascripts.directions.errors.no_route') + '</p>');
218 .setLatLngs(route.line)
222 map.fitBounds(polyline.getBounds().pad(0.05));
225 var html = '<h2><a class="geolink" href="#">' +
226 '<span class="icon close"></span></a>' + I18n.t('javascripts.directions.directions') +
227 '</h2><p id="routing_summary">' +
228 I18n.t('javascripts.directions.distance') + ': ' + formatDistance(route.distance) + '. ' +
229 I18n.t('javascripts.directions.time') + ': ' + formatTime(route.time) + '.';
230 if (typeof route.ascend !== 'undefined' && typeof route.descend !== 'undefined') {
232 I18n.t('javascripts.directions.ascend') + ': ' + Math.round(route.ascend) + 'm. ' +
233 I18n.t('javascripts.directions.descend') + ': ' + Math.round(route.descend) +'m.';
235 html += '</p><table id="turnbyturn" />';
237 $('#sidebar_content')
242 route.steps.forEach(function (step) {
245 instruction = step[2],
253 } else if (dist < 200) {
254 dist = Math.round(dist / 10) * 10 + "m";
255 } else if (dist < 1500) {
256 dist = Math.round(dist / 100) * 100 + "m";
257 } else if (dist < 5000) {
258 dist = Math.round(dist / 100) / 10 + "km";
260 dist = Math.round(dist / 1000) + "km";
263 var row = $("<tr class='turn'/>");
264 row.append("<td><div class='direction i" + direction + "'/></td> ");
265 row.append("<td class='instruction'>" + instruction);
266 row.append("<td class='distance'>" + dist);
268 row.on('click', function () {
271 .setContent("<p>" + instruction + "</p>")
275 row.hover(function () {
280 map.removeLayer(highlight);
283 $('#turnbyturn').append(row);
286 $('#sidebar_content').append('<p id="routing_credit">' +
287 I18n.t('javascripts.directions.instructions.courtesy', {link: chosenEngine.creditline}) +
290 $('#sidebar_content a.geolink').on('click', function(e) {
292 map.removeLayer(polyline);
293 $('#sidebar_content').html('');
294 map.setSidebarOverlaid(true);
295 // TODO: collapse width of sidebar back to previous
300 var engines = OSM.Directions.engines;
302 engines.sort(function (a, b) {
303 a = I18n.t('javascripts.directions.engines.' + a.id);
304 b = I18n.t('javascripts.directions.engines.' + b.id);
305 return a.localeCompare(b);
308 var select = $('select.routing_engines');
310 engines.forEach(function(engine, i) {
311 select.append("<option value='" + i + "'>" + I18n.t('javascripts.directions.engines.' + engine.id) + "</option>");
314 var chosenEngineId = $.cookie('_osm_directions_engine');
315 if(!chosenEngineId) {
316 chosenEngineId = 'osrm_car';
318 setEngine(chosenEngineId);
320 select.on("change", function (e) {
321 chosenEngine = engines[e.target.selectedIndex];
322 $.cookie('_osm_directions_engine', chosenEngine.id, { expires: expiry, path: '/' });
323 if (map.hasLayer(polyline)) {
328 $(".directions_form").on("submit", function(e) {
333 $(".routing_marker").on('dragstart', function (e) {
334 var dt = e.originalEvent.dataTransfer;
335 dt.effectAllowed = 'move';
336 var dragData = { type: $(this).data('type') };
337 dt.setData('text', JSON.stringify(dragData));
338 if (dt.setDragImage) {
339 var img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
340 dt.setDragImage(img.get(0), 12, 21);
346 page.pushstate = page.popstate = function() {
347 $(".search_form").hide();
348 $(".directions_form").show();
350 $("#map").on('dragend dragover', function (e) {
354 $("#map").on('drop', function (e) {
356 var oe = e.originalEvent;
357 var dragData = JSON.parse(oe.dataTransfer.getData('text'));
358 var type = dragData.type;
359 var pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
361 var ll = map.containerPointToLatLng(pt);
362 endpoints[type === 'from' ? 0 : 1].setLatLng(ll);
366 var params = querystring.parse(location.search.substring(1)),
367 route = (params.route || '').split(';'),
368 from = route[0] && L.latLng(route[0].split(',')),
369 to = route[1] && L.latLng(route[1].split(','));
372 setEngine(params.engine);
375 endpoints[0].setValue(params.from || "", from);
376 endpoints[1].setValue(params.to || "", to);
378 map.setSidebarOverlaid(!from || !to);
383 page.load = function() {
387 page.unload = function() {
388 $(".search_form").show();
389 $(".directions_form").hide();
390 $("#map").off('dragend dragover drop');
394 .removeLayer(polyline)
395 .removeLayer(endpoints[0].marker)
396 .removeLayer(endpoints[1].marker);
402 OSM.Directions.engines = [];
404 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
405 if (document.location.protocol === "http:" || supportsHTTPS) {
406 OSM.Directions.engines.push(engine);