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();
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.input = input;
37 endpoint.marker = L.marker([0, 0], {
42 popupAnchor: [1, -34],
43 shadowUrl: OSM.MARKER_SHADOW,
49 endpoint.marker.on('drag dragend', function (e) {
50 dragging = (e.type === 'drag');
51 if (dragging && !chosenEngine.draggable) return;
52 if (dragging && awaitingRoute) return;
53 endpoint.setLatLng(e.target.getLatLng());
54 if (map.hasLayer(polyline)) {
59 input.on("change", function (e) {
60 // make text the same in both text boxes
61 var value = e.target.value;
62 endpoint.setValue(value);
65 endpoint.setValue = function(value) {
66 endpoint.value = value;
67 delete endpoint.latlng;
69 endpoint.getGeocode();
72 endpoint.getGeocode = function() {
73 // if no one has entered a value yet, then we can't geocode, so don't
75 if (!endpoint.value) {
79 endpoint.awaitingGeocode = true;
81 $.getJSON(document.location.protocol + OSM.NOMINATIM_URL + 'search?q=' + encodeURIComponent(endpoint.value) + '&format=json', function (json) {
82 endpoint.awaitingGeocode = false;
83 endpoint.hasGeocode = true;
84 if (json.length === 0) {
85 alert(I18n.t('javascripts.directions.errors.no_place'));
89 input.val(json[0].display_name);
91 endpoint.latlng = L.latLng(json[0]);
93 .setLatLng(endpoint.latlng)
96 if (awaitingGeocode) {
97 awaitingGeocode = false;
103 endpoint.setLatLng = function (ll) {
104 var precision = OSM.zoomPrecision(map.getZoom());
105 input.val(ll.lat.toFixed(precision) + ", " + ll.lng.toFixed(precision));
106 endpoint.hasGeocode = true;
107 endpoint.latlng = ll;
116 $(".directions_form .reverse_directions").on("click", function() {
117 var input_from = endpoints[0].input.val();
118 var input_to = endpoints[1].input.val();
119 var latlng_from = endpoints[0].latlng;
120 var latlng_to = endpoints[1].latlng;
122 endpoints[0].setLatLng(latlng_to);
123 endpoints[1].setLatLng(latlng_from);
124 endpoints[0].input.val(input_to);
125 endpoints[1].input.val(input_from);
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(';');
370 setEngine(params.engine);
373 endpoints[0].setValue(params.from || "");
374 endpoints[1].setValue(params.to || "");
376 var o = route[0] && L.latLng(route[0].split(',')),
377 d = route[1] && L.latLng(route[1].split(','));
379 if (o) endpoints[0].setLatLng(o);
380 if (d) endpoints[1].setLatLng(d);
382 map.setSidebarOverlaid(!o || !d);
387 page.load = function() {
391 page.unload = function() {
392 $(".search_form").show();
393 $(".directions_form").hide();
394 $("#map").off('dragend dragover drop');
398 .removeLayer(polyline)
399 .removeLayer(endpoints[0].marker)
400 .removeLayer(endpoints[1].marker);
406 OSM.Directions.engines = [];
408 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
409 if (document.location.protocol === "http:" || supportsHTTPS) {
410 OSM.Directions.engines.push(engine);