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("keydown", function() {
57 input.removeClass("highlight_error");
60 input.on("change", function (e) {
61 awaitingGeocode = true;
63 // make text the same in both text boxes
64 var value = e.target.value;
65 endpoint.setValue(value);
68 endpoint.setValue = function(value, latlng) {
69 endpoint.value = value;
70 delete endpoint.latlng;
74 endpoint.setLatLng(latlng);
76 endpoint.getGeocode();
80 endpoint.getGeocode = function() {
81 // if no one has entered a value yet, then we can't geocode, so don't
83 if (!endpoint.value) {
87 endpoint.awaitingGeocode = true;
89 $.getJSON(OSM.NOMINATIM_URL + 'search?q=' + encodeURIComponent(endpoint.value) + '&format=json', function (json) {
90 endpoint.awaitingGeocode = false;
91 endpoint.hasGeocode = true;
92 if (json.length === 0) {
93 alert(I18n.t('javascripts.directions.errors.no_place', {place: endpoint.value}));
94 input.addClass("highlight_error");
98 endpoint.setLatLng(L.latLng(json[0]));
100 input.val(json[0].display_name);
102 if (awaitingGeocode) {
103 awaitingGeocode = false;
104 getRoute(true, true);
109 endpoint.setLatLng = function (ll) {
110 var precision = OSM.zoomPrecision(map.getZoom());
111 input.val(ll.lat.toFixed(precision) + ", " + ll.lng.toFixed(precision));
112 endpoint.hasGeocode = true;
113 endpoint.latlng = ll;
122 $(".directions_form .reverse_directions").on("click", function() {
123 var from = endpoints[0].latlng,
124 to = endpoints[1].latlng;
126 OSM.router.route("/directions?" + querystring.stringify({
127 from: $("#route_to").val(),
128 to: $("#route_from").val(),
129 route: to.lat + "," + to.lng + ";" + from.lat + "," + from.lng
133 $(".directions_form .close").on("click", function(e) {
135 var route_from = endpoints[0].value;
137 OSM.router.route("/?query=" + encodeURIComponent(route_from) + OSM.formatHash(map));
139 OSM.router.route("/" + OSM.formatHash(map));
143 function formatDistance(m) {
145 return Math.round(m) + "m";
146 } else if (m < 10000) {
147 return (m / 1000.0).toFixed(1) + "km";
149 return Math.round(m / 1000) + "km";
153 function formatTime(s) {
154 var m = Math.round(s / 60);
155 var h = Math.floor(m / 60);
157 return h + ":" + (m < 10 ? '0' : '') + m;
160 function setEngine(id) {
161 engines.forEach(function(engine, i) {
162 if (engine.id === id) {
163 chosenEngine = engine;
169 function getRoute(fitRoute, reportErrors) {
170 // Cancel any route that is already in progress
171 if (awaitingRoute) awaitingRoute.abort();
173 // go fetch geocodes for any endpoints which have not already
175 for (var ep_i = 0; ep_i < 2; ++ep_i) {
176 var endpoint = endpoints[ep_i];
177 if (!endpoint.hasGeocode && !endpoint.awaitingGeocode) {
178 endpoint.getGeocode();
179 awaitingGeocode = true;
182 if (endpoints[0].awaitingGeocode || endpoints[1].awaitingGeocode) {
183 awaitingGeocode = true;
187 var o = endpoints[0].latlng,
188 d = endpoints[1].latlng;
190 if (!o || !d) return;
191 $("header").addClass("closed");
193 var precision = OSM.zoomPrecision(map.getZoom());
195 OSM.router.replace("/directions?" + querystring.stringify({
196 engine: chosenEngine.id,
197 route: o.lat.toFixed(precision) + ',' + o.lng.toFixed(precision) + ';' +
198 d.lat.toFixed(precision) + ',' + d.lng.toFixed(precision)
201 // copy loading item to sidebar and display it. we copy it, rather than
202 // just using it in-place and replacing it in case it has to be used
204 $('#sidebar_content').html($('.directions_form .loader_copy').html());
205 map.setSidebarOverlaid(false);
207 awaitingRoute = chosenEngine.getRoute([o, d], function (err, route) {
208 awaitingRoute = null;
211 map.removeLayer(polyline);
214 $('#sidebar_content').html('<p class="search_results_error">' + I18n.t('javascripts.directions.errors.no_route') + '</p>');
221 .setLatLngs(route.line)
225 map.fitBounds(polyline.getBounds().pad(0.05));
228 var html = '<h2><a class="geolink" href="#">' +
229 '<span class="icon close"></span></a>' + I18n.t('javascripts.directions.directions') +
230 '</h2><p id="routing_summary">' +
231 I18n.t('javascripts.directions.distance') + ': ' + formatDistance(route.distance) + '. ' +
232 I18n.t('javascripts.directions.time') + ': ' + formatTime(route.time) + '.';
233 if (typeof route.ascend !== 'undefined' && typeof route.descend !== 'undefined') {
235 I18n.t('javascripts.directions.ascend') + ': ' + Math.round(route.ascend) + 'm. ' +
236 I18n.t('javascripts.directions.descend') + ': ' + Math.round(route.descend) +'m.';
238 html += '</p><table id="turnbyturn" />';
240 $('#sidebar_content')
245 route.steps.forEach(function (step) {
248 instruction = step[2],
256 } else if (dist < 200) {
257 dist = Math.round(dist / 10) * 10 + "m";
258 } else if (dist < 1500) {
259 dist = Math.round(dist / 100) * 100 + "m";
260 } else if (dist < 5000) {
261 dist = Math.round(dist / 100) / 10 + "km";
263 dist = Math.round(dist / 1000) + "km";
266 var row = $("<tr class='turn'/>");
267 row.append("<td><div class='direction i" + direction + "'/></td> ");
268 row.append("<td class='instruction'>" + instruction);
269 row.append("<td class='distance'>" + dist);
271 row.on('click', function () {
274 .setContent("<p>" + instruction + "</p>")
278 row.hover(function () {
283 map.removeLayer(highlight);
286 $('#turnbyturn').append(row);
289 $('#sidebar_content').append('<p id="routing_credit">' +
290 I18n.t('javascripts.directions.instructions.courtesy', {link: chosenEngine.creditline}) +
293 $('#sidebar_content a.geolink').on('click', function(e) {
295 map.removeLayer(polyline);
296 $('#sidebar_content').html('');
297 map.setSidebarOverlaid(true);
298 // TODO: collapse width of sidebar back to previous
303 var engines = OSM.Directions.engines;
305 engines.sort(function (a, b) {
306 a = I18n.t('javascripts.directions.engines.' + a.id);
307 b = I18n.t('javascripts.directions.engines.' + b.id);
308 return a.localeCompare(b);
311 var select = $('select.routing_engines');
313 engines.forEach(function(engine, i) {
314 select.append("<option value='" + i + "'>" + I18n.t('javascripts.directions.engines.' + engine.id) + "</option>");
317 var chosenEngineId = $.cookie('_osm_directions_engine');
318 if(!chosenEngineId) {
319 chosenEngineId = 'osrm_car';
321 setEngine(chosenEngineId);
323 select.on("change", function (e) {
324 chosenEngine = engines[e.target.selectedIndex];
325 $.cookie('_osm_directions_engine', chosenEngine.id, { expires: expiry, path: '/' });
326 if (map.hasLayer(polyline)) {
327 getRoute(true, true);
331 $(".directions_form").on("submit", function(e) {
333 getRoute(true, true);
336 $(".routing_marker").on('dragstart', function (e) {
337 var dt = e.originalEvent.dataTransfer;
338 dt.effectAllowed = 'move';
339 var dragData = { type: $(this).data('type') };
340 dt.setData('text', JSON.stringify(dragData));
341 if (dt.setDragImage) {
342 var img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
343 dt.setDragImage(img.get(0), 12, 21);
349 page.pushstate = page.popstate = function() {
350 $(".search_form").hide();
351 $(".directions_form").show();
353 $("#map").on('dragend dragover', function (e) {
357 $("#map").on('drop', function (e) {
359 var oe = e.originalEvent;
360 var dragData = JSON.parse(oe.dataTransfer.getData('text'));
361 var type = dragData.type;
362 var pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
364 var ll = map.containerPointToLatLng(pt);
365 endpoints[type === 'from' ? 0 : 1].setLatLng(ll);
366 getRoute(true, true);
369 var params = querystring.parse(location.search.substring(1)),
370 route = (params.route || '').split(';'),
371 from = route[0] && L.latLng(route[0].split(',')),
372 to = route[1] && L.latLng(route[1].split(','));
375 setEngine(params.engine);
378 endpoints[0].setValue(params.from || "", from);
379 endpoints[1].setValue(params.to || "", to);
381 map.setSidebarOverlaid(!from || !to);
383 getRoute(true, true);
386 page.load = function() {
390 page.unload = function() {
391 $(".search_form").show();
392 $(".directions_form").hide();
393 $("#map").off('dragend dragover drop');
397 .removeLayer(polyline)
398 .removeLayer(endpoints[0].marker)
399 .removeLayer(endpoints[1].marker);
405 OSM.Directions.engines = [];
407 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
408 if (document.location.protocol === "http:" || supportsHTTPS) {
409 OSM.Directions.engines.push(engine);