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.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) {
64 endpoint.value = value;
65 delete endpoint.latlng;
67 endpoint.getGeocode();
70 endpoint.getGeocode = function() {
71 // if no one has entered a value yet, then we can't geocode, so don't
73 if (!endpoint.value) {
77 endpoint.awaitingGeocode = true;
79 $.getJSON(OSM.NOMINATIM_URL + 'search?q=' + encodeURIComponent(endpoint.value) + '&format=json', function (json) {
80 endpoint.awaitingGeocode = false;
81 endpoint.hasGeocode = true;
82 if (json.length === 0) {
83 alert(I18n.t('javascripts.directions.errors.no_place'));
87 input.val(json[0].display_name);
89 endpoint.latlng = L.latLng(json[0]);
91 .setLatLng(endpoint.latlng)
94 if (awaitingGeocode) {
95 awaitingGeocode = false;
101 endpoint.setLatLng = function (ll) {
102 var precision = OSM.zoomPrecision(map.getZoom());
103 input.val(ll.lat.toFixed(precision) + ", " + ll.lng.toFixed(precision));
104 endpoint.hasGeocode = true;
105 endpoint.latlng = ll;
114 $(".directions_form .reverse_directions").on("click", function() {
115 var from = endpoints[0].latlng,
116 to = endpoints[1].latlng;
118 OSM.router.route("/directions?" + querystring.stringify({
119 from: $("#route_to").val(),
120 to: $("#route_from").val(),
121 route: from.lat + "," + from.lng + ";" + to.lat + "," + to.lng
125 $(".directions_form .close").on("click", function(e) {
127 var route_from = endpoints[0].value;
129 OSM.router.route("/?query=" + encodeURIComponent(route_from) + OSM.formatHash(map));
131 OSM.router.route("/" + OSM.formatHash(map));
135 function formatDistance(m) {
137 return Math.round(m) + "m";
138 } else if (m < 10000) {
139 return (m / 1000.0).toFixed(1) + "km";
141 return Math.round(m / 1000) + "km";
145 function formatTime(s) {
146 var m = Math.round(s / 60);
147 var h = Math.floor(m / 60);
149 return h + ":" + (m < 10 ? '0' : '') + m;
152 function setEngine(id) {
153 engines.forEach(function(engine, i) {
154 if (engine.id === id) {
155 chosenEngine = engine;
161 function getRoute() {
162 // Cancel any route that is already in progress
163 if (awaitingRoute) awaitingRoute.abort();
165 // go fetch geocodes for any endpoints which have not already
167 for (var ep_i = 0; ep_i < 2; ++ep_i) {
168 var endpoint = endpoints[ep_i];
169 if (!endpoint.hasGeocode && !endpoint.awaitingGeocode) {
170 endpoint.getGeocode();
171 awaitingGeocode = true;
174 if (endpoints[0].awaitingGeocode || endpoints[1].awaitingGeocode) {
175 awaitingGeocode = true;
179 var o = endpoints[0].latlng,
180 d = endpoints[1].latlng;
182 if (!o || !d) return;
183 $("header").addClass("closed");
185 var precision = OSM.zoomPrecision(map.getZoom());
187 OSM.router.replace("/directions?" + querystring.stringify({
188 engine: chosenEngine.id,
189 route: o.lat.toFixed(precision) + ',' + o.lng.toFixed(precision) + ';' +
190 d.lat.toFixed(precision) + ',' + d.lng.toFixed(precision)
193 // copy loading item to sidebar and display it. we copy it, rather than
194 // just using it in-place and replacing it in case it has to be used
196 $('#sidebar_content').html($('.directions_form .loader_copy').html());
197 map.setSidebarOverlaid(false);
199 awaitingRoute = chosenEngine.getRoute([o, d], function (err, route) {
200 awaitingRoute = null;
203 map.removeLayer(polyline);
206 $('#sidebar_content').html('<p class="search_results_error">' + I18n.t('javascripts.directions.errors.no_route') + '</p>');
213 .setLatLngs(route.line)
217 map.fitBounds(polyline.getBounds().pad(0.05));
220 var html = '<h2><a class="geolink" href="#">' +
221 '<span class="icon close"></span></a>' + I18n.t('javascripts.directions.directions') +
222 '</h2><p id="routing_summary">' +
223 I18n.t('javascripts.directions.distance') + ': ' + formatDistance(route.distance) + '. ' +
224 I18n.t('javascripts.directions.time') + ': ' + formatTime(route.time) + '.';
225 if (typeof route.ascend !== 'undefined' && typeof route.descend !== 'undefined') {
227 I18n.t('javascripts.directions.ascend') + ': ' + Math.round(route.ascend) + 'm. ' +
228 I18n.t('javascripts.directions.descend') + ': ' + Math.round(route.descend) +'m.';
230 html += '</p><table id="turnbyturn" />';
232 $('#sidebar_content')
237 route.steps.forEach(function (step) {
240 instruction = step[2],
248 } else if (dist < 200) {
249 dist = Math.round(dist / 10) * 10 + "m";
250 } else if (dist < 1500) {
251 dist = Math.round(dist / 100) * 100 + "m";
252 } else if (dist < 5000) {
253 dist = Math.round(dist / 100) / 10 + "km";
255 dist = Math.round(dist / 1000) + "km";
258 var row = $("<tr class='turn'/>");
259 row.append("<td><div class='direction i" + direction + "'/></td> ");
260 row.append("<td class='instruction'>" + instruction);
261 row.append("<td class='distance'>" + dist);
263 row.on('click', function () {
266 .setContent("<p>" + instruction + "</p>")
270 row.hover(function () {
275 map.removeLayer(highlight);
278 $('#turnbyturn').append(row);
281 $('#sidebar_content').append('<p id="routing_credit">' +
282 I18n.t('javascripts.directions.instructions.courtesy', {link: chosenEngine.creditline}) +
285 $('#sidebar_content a.geolink').on('click', function(e) {
287 map.removeLayer(polyline);
288 $('#sidebar_content').html('');
289 map.setSidebarOverlaid(true);
290 // TODO: collapse width of sidebar back to previous
295 var engines = OSM.Directions.engines;
297 engines.sort(function (a, b) {
298 a = I18n.t('javascripts.directions.engines.' + a.id);
299 b = I18n.t('javascripts.directions.engines.' + b.id);
300 return a.localeCompare(b);
303 var select = $('select.routing_engines');
305 engines.forEach(function(engine, i) {
306 select.append("<option value='" + i + "'>" + I18n.t('javascripts.directions.engines.' + engine.id) + "</option>");
309 var chosenEngineId = $.cookie('_osm_directions_engine');
310 if(!chosenEngineId) {
311 chosenEngineId = 'osrm_car';
313 setEngine(chosenEngineId);
315 select.on("change", function (e) {
316 chosenEngine = engines[e.target.selectedIndex];
317 $.cookie('_osm_directions_engine', chosenEngine.id, { expires: expiry, path: '/' });
318 if (map.hasLayer(polyline)) {
323 $(".directions_form").on("submit", function(e) {
328 $(".routing_marker").on('dragstart', function (e) {
329 var dt = e.originalEvent.dataTransfer;
330 dt.effectAllowed = 'move';
331 var dragData = { type: $(this).data('type') };
332 dt.setData('text', JSON.stringify(dragData));
333 if (dt.setDragImage) {
334 var img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
335 dt.setDragImage(img.get(0), 12, 21);
341 page.pushstate = page.popstate = function() {
342 $(".search_form").hide();
343 $(".directions_form").show();
345 $("#map").on('dragend dragover', function (e) {
349 $("#map").on('drop', function (e) {
351 var oe = e.originalEvent;
352 var dragData = JSON.parse(oe.dataTransfer.getData('text'));
353 var type = dragData.type;
354 var pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
356 var ll = map.containerPointToLatLng(pt);
357 endpoints[type === 'from' ? 0 : 1].setLatLng(ll);
361 var params = querystring.parse(location.search.substring(1)),
362 route = (params.route || '').split(';');
365 setEngine(params.engine);
368 endpoints[0].setValue(params.from || "");
369 endpoints[1].setValue(params.to || "");
371 var o = route[0] && L.latLng(route[0].split(',')),
372 d = route[1] && L.latLng(route[1].split(','));
374 if (o) endpoints[0].setLatLng(o);
375 if (d) endpoints[1].setLatLng(d);
377 map.setSidebarOverlaid(!o || !d);
382 page.load = function() {
386 page.unload = function() {
387 $(".search_form").show();
388 $(".directions_form").hide();
389 $("#map").off('dragend dragover drop');
393 .removeLayer(polyline)
394 .removeLayer(endpoints[0].marker)
395 .removeLayer(endpoints[1].marker);
401 OSM.Directions.engines = [];
403 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
404 if (document.location.protocol === "http:" || supportsHTTPS) {
405 OSM.Directions.engines.push(engine);