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("change", function (e) {
57 // make text the same in both text boxes
58 var value = e.target.value;
59 endpoint.setValue(value);
62 endpoint.setValue = function(value, latlng) {
63 endpoint.value = value;
64 delete endpoint.latlng;
68 endpoint.setLatLng(latlng);
70 endpoint.getGeocode();
74 endpoint.getGeocode = function() {
75 // if no one has entered a value yet, then we can't geocode, so don't
77 if (!endpoint.value) {
81 endpoint.awaitingGeocode = true;
83 $.getJSON(OSM.NOMINATIM_URL + 'search?q=' + encodeURIComponent(endpoint.value) + '&format=json', function (json) {
84 endpoint.awaitingGeocode = false;
85 endpoint.hasGeocode = true;
86 if (json.length === 0) {
87 alert(I18n.t('javascripts.directions.errors.no_place'));
91 input.val(json[0].display_name);
93 endpoint.latlng = L.latLng(json[0]);
95 .setLatLng(endpoint.latlng)
98 if (awaitingGeocode) {
99 awaitingGeocode = false;
100 getRoute(true, true);
105 endpoint.setLatLng = function (ll) {
106 var precision = OSM.zoomPrecision(map.getZoom());
107 input.val(ll.lat.toFixed(precision) + ", " + ll.lng.toFixed(precision));
108 endpoint.hasGeocode = true;
109 endpoint.latlng = ll;
118 $(".directions_form .reverse_directions").on("click", function() {
119 var from = endpoints[0].latlng,
120 to = endpoints[1].latlng;
122 OSM.router.route("/directions?" + querystring.stringify({
123 from: $("#route_to").val(),
124 to: $("#route_from").val(),
125 route: to.lat + "," + to.lng + ";" + from.lat + "," + from.lng
129 $(".directions_form .close").on("click", function(e) {
131 var route_from = endpoints[0].value;
133 OSM.router.route("/?query=" + encodeURIComponent(route_from) + OSM.formatHash(map));
135 OSM.router.route("/" + OSM.formatHash(map));
139 function formatDistance(m) {
141 return Math.round(m) + "m";
142 } else if (m < 10000) {
143 return (m / 1000.0).toFixed(1) + "km";
145 return Math.round(m / 1000) + "km";
149 function formatTime(s) {
150 var m = Math.round(s / 60);
151 var h = Math.floor(m / 60);
153 return h + ":" + (m < 10 ? '0' : '') + m;
156 function setEngine(id) {
157 engines.forEach(function(engine, i) {
158 if (engine.id === id) {
159 chosenEngine = engine;
165 function getRoute(fitRoute, reportErrors) {
166 // Cancel any route that is already in progress
167 if (awaitingRoute) awaitingRoute.abort();
169 // go fetch geocodes for any endpoints which have not already
171 for (var ep_i = 0; ep_i < 2; ++ep_i) {
172 var endpoint = endpoints[ep_i];
173 if (!endpoint.hasGeocode && !endpoint.awaitingGeocode) {
174 endpoint.getGeocode();
175 awaitingGeocode = true;
178 if (endpoints[0].awaitingGeocode || endpoints[1].awaitingGeocode) {
179 awaitingGeocode = true;
183 var o = endpoints[0].latlng,
184 d = endpoints[1].latlng;
186 if (!o || !d) return;
187 $("header").addClass("closed");
189 var precision = OSM.zoomPrecision(map.getZoom());
191 OSM.router.replace("/directions?" + querystring.stringify({
192 engine: chosenEngine.id,
193 route: o.lat.toFixed(precision) + ',' + o.lng.toFixed(precision) + ';' +
194 d.lat.toFixed(precision) + ',' + d.lng.toFixed(precision)
197 // copy loading item to sidebar and display it. we copy it, rather than
198 // just using it in-place and replacing it in case it has to be used
200 $('#sidebar_content').html($('.directions_form .loader_copy').html());
201 map.setSidebarOverlaid(false);
203 awaitingRoute = chosenEngine.getRoute([o, d], function (err, route) {
204 awaitingRoute = null;
207 map.removeLayer(polyline);
210 $('#sidebar_content').html('<p class="search_results_error">' + I18n.t('javascripts.directions.errors.no_route') + '</p>');
217 .setLatLngs(route.line)
221 map.fitBounds(polyline.getBounds().pad(0.05));
224 var html = '<h2><a class="geolink" href="#">' +
225 '<span class="icon close"></span></a>' + I18n.t('javascripts.directions.directions') +
226 '</h2><p id="routing_summary">' +
227 I18n.t('javascripts.directions.distance') + ': ' + formatDistance(route.distance) + '. ' +
228 I18n.t('javascripts.directions.time') + ': ' + formatTime(route.time) + '.';
229 if (typeof route.ascend !== 'undefined' && typeof route.descend !== 'undefined') {
231 I18n.t('javascripts.directions.ascend') + ': ' + Math.round(route.ascend) + 'm. ' +
232 I18n.t('javascripts.directions.descend') + ': ' + Math.round(route.descend) +'m.';
234 html += '</p><table id="turnbyturn" />';
236 $('#sidebar_content')
241 route.steps.forEach(function (step) {
244 instruction = step[2],
252 } else if (dist < 200) {
253 dist = Math.round(dist / 10) * 10 + "m";
254 } else if (dist < 1500) {
255 dist = Math.round(dist / 100) * 100 + "m";
256 } else if (dist < 5000) {
257 dist = Math.round(dist / 100) / 10 + "km";
259 dist = Math.round(dist / 1000) + "km";
262 var row = $("<tr class='turn'/>");
263 row.append("<td><div class='direction i" + direction + "'/></td> ");
264 row.append("<td class='instruction'>" + instruction);
265 row.append("<td class='distance'>" + dist);
267 row.on('click', function () {
270 .setContent("<p>" + instruction + "</p>")
274 row.hover(function () {
279 map.removeLayer(highlight);
282 $('#turnbyturn').append(row);
285 $('#sidebar_content').append('<p id="routing_credit">' +
286 I18n.t('javascripts.directions.instructions.courtesy', {link: chosenEngine.creditline}) +
289 $('#sidebar_content a.geolink').on('click', function(e) {
291 map.removeLayer(polyline);
292 $('#sidebar_content').html('');
293 map.setSidebarOverlaid(true);
294 // TODO: collapse width of sidebar back to previous
299 var engines = OSM.Directions.engines;
301 engines.sort(function (a, b) {
302 a = I18n.t('javascripts.directions.engines.' + a.id);
303 b = I18n.t('javascripts.directions.engines.' + b.id);
304 return a.localeCompare(b);
307 var select = $('select.routing_engines');
309 engines.forEach(function(engine, i) {
310 select.append("<option value='" + i + "'>" + I18n.t('javascripts.directions.engines.' + engine.id) + "</option>");
313 var chosenEngineId = $.cookie('_osm_directions_engine');
314 if(!chosenEngineId) {
315 chosenEngineId = 'osrm_car';
317 setEngine(chosenEngineId);
319 select.on("change", function (e) {
320 chosenEngine = engines[e.target.selectedIndex];
321 $.cookie('_osm_directions_engine', chosenEngine.id, { expires: expiry, path: '/' });
322 if (map.hasLayer(polyline)) {
323 getRoute(true, true);
327 $(".directions_form").on("submit", function(e) {
329 getRoute(true, true);
332 $(".routing_marker").on('dragstart', function (e) {
333 var dt = e.originalEvent.dataTransfer;
334 dt.effectAllowed = 'move';
335 var dragData = { type: $(this).data('type') };
336 dt.setData('text', JSON.stringify(dragData));
337 if (dt.setDragImage) {
338 var img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
339 dt.setDragImage(img.get(0), 12, 21);
345 page.pushstate = page.popstate = function() {
346 $(".search_form").hide();
347 $(".directions_form").show();
349 $("#map").on('dragend dragover', function (e) {
353 $("#map").on('drop', function (e) {
355 var oe = e.originalEvent;
356 var dragData = JSON.parse(oe.dataTransfer.getData('text'));
357 var type = dragData.type;
358 var pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
360 var ll = map.containerPointToLatLng(pt);
361 endpoints[type === 'from' ? 0 : 1].setLatLng(ll);
362 getRoute(true, true);
365 var params = querystring.parse(location.search.substring(1)),
366 route = (params.route || '').split(';'),
367 from = route[0] && L.latLng(route[0].split(',')),
368 to = route[1] && L.latLng(route[1].split(','));
371 setEngine(params.engine);
374 endpoints[0].setValue(params.from || "", from);
375 endpoints[1].setValue(params.to || "", to);
377 map.setSidebarOverlaid(!from || !to);
379 getRoute(true, true);
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);