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(document.location.protocol + 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 .close").on("click", function(e) {
116 var route_from = endpoints[0].value;
118 OSM.router.route("/?query=" + encodeURIComponent(route_from) + OSM.formatHash(map));
120 OSM.router.route("/" + OSM.formatHash(map));
124 function formatDistance(m) {
126 return Math.round(m) + "m";
127 } else if (m < 10000) {
128 return (m / 1000.0).toFixed(1) + "km";
130 return Math.round(m / 1000) + "km";
134 function formatTime(s) {
135 var m = Math.round(s / 60);
136 var h = Math.floor(m / 60);
138 return h + ":" + (m < 10 ? '0' : '') + m;
141 function setEngine(id) {
142 engines.forEach(function(engine, i) {
143 if (engine.id === id) {
144 chosenEngine = engine;
150 function getRoute() {
151 // Cancel any route that is already in progress
152 if (awaitingRoute) awaitingRoute.abort();
154 // go fetch geocodes for any endpoints which have not already
156 for (var ep_i = 0; ep_i < 2; ++ep_i) {
157 var endpoint = endpoints[ep_i];
158 if (!endpoint.hasGeocode && !endpoint.awaitingGeocode) {
159 endpoint.getGeocode();
160 awaitingGeocode = true;
163 if (endpoints[0].awaitingGeocode || endpoints[1].awaitingGeocode) {
164 awaitingGeocode = true;
168 var o = endpoints[0].latlng,
169 d = endpoints[1].latlng;
171 if (!o || !d) return;
172 $("header").addClass("closed");
174 var precision = OSM.zoomPrecision(map.getZoom());
176 OSM.router.replace("/directions?" + querystring.stringify({
177 engine: chosenEngine.id,
178 route: o.lat.toFixed(precision) + ',' + o.lng.toFixed(precision) + ';' +
179 d.lat.toFixed(precision) + ',' + d.lng.toFixed(precision)
182 // copy loading item to sidebar and display it. we copy it, rather than
183 // just using it in-place and replacing it in case it has to be used
185 $('#sidebar_content').html($('.directions_form .loader_copy').html());
186 map.setSidebarOverlaid(false);
188 awaitingRoute = chosenEngine.getRoute([o, d], function (err, route) {
189 awaitingRoute = null;
192 map.removeLayer(polyline);
195 $('#sidebar_content').html('<p class="search_results_error">' + I18n.t('javascripts.directions.errors.no_route') + '</p>');
202 .setLatLngs(route.line)
206 map.fitBounds(polyline.getBounds().pad(0.05));
209 var html = '<h2><a class="geolink" href="#">' +
210 '<span class="icon close"></span></a>' + I18n.t('javascripts.directions.directions') +
211 '</h2><p id="routing_summary">' +
212 I18n.t('javascripts.directions.distance') + ': ' + formatDistance(route.distance) + '. ' +
213 I18n.t('javascripts.directions.time') + ': ' + formatTime(route.time) + '.';
214 if (typeof route.ascend !== 'undefined' && typeof route.descend !== 'undefined') {
216 I18n.t('javascripts.directions.ascend') + ': ' + Math.round(route.ascend) + 'm. ' +
217 I18n.t('javascripts.directions.descend') + ': ' + Math.round(route.descend) +'m.';
219 html += '</p><table id="turnbyturn" />';
221 $('#sidebar_content')
226 route.steps.forEach(function (step) {
229 instruction = step[2],
237 } else if (dist < 200) {
238 dist = Math.round(dist / 10) * 10 + "m";
239 } else if (dist < 1500) {
240 dist = Math.round(dist / 100) * 100 + "m";
241 } else if (dist < 5000) {
242 dist = Math.round(dist / 100) / 10 + "km";
244 dist = Math.round(dist / 1000) + "km";
247 var row = $("<tr class='turn'/>");
248 row.append("<td><div class='direction i" + direction + "'/></td> ");
249 row.append("<td class='instruction'>" + instruction);
250 row.append("<td class='distance'>" + dist);
252 row.on('click', function () {
255 .setContent("<p>" + instruction + "</p>")
259 row.hover(function () {
264 map.removeLayer(highlight);
267 $('#turnbyturn').append(row);
270 $('#sidebar_content').append('<p id="routing_credit">' +
271 I18n.t('javascripts.directions.instructions.courtesy', {link: chosenEngine.creditline}) +
274 $('#sidebar_content a.geolink').on('click', function(e) {
276 map.removeLayer(polyline);
277 $('#sidebar_content').html('');
278 map.setSidebarOverlaid(true);
279 // TODO: collapse width of sidebar back to previous
284 var engines = OSM.Directions.engines;
286 engines.sort(function (a, b) {
287 a = I18n.t('javascripts.directions.engines.' + a.id);
288 b = I18n.t('javascripts.directions.engines.' + b.id);
289 return a.localeCompare(b);
292 var select = $('select.routing_engines');
294 engines.forEach(function(engine, i) {
295 select.append("<option value='" + i + "'>" + I18n.t('javascripts.directions.engines.' + engine.id) + "</option>");
298 var chosenEngineId = $.cookie('_osm_directions_engine');
299 if(!chosenEngineId) {
300 chosenEngineId = 'osrm_car';
302 setEngine(chosenEngineId);
304 select.on("change", function (e) {
305 chosenEngine = engines[e.target.selectedIndex];
306 $.cookie('_osm_directions_engine', chosenEngine.id, { expires: expiry, path: '/' });
307 if (map.hasLayer(polyline)) {
312 $(".directions_form").on("submit", function(e) {
317 $(".routing_marker").on('dragstart', function (e) {
318 var dt = e.originalEvent.dataTransfer;
319 dt.effectAllowed = 'move';
320 var dragData = { type: $(this).data('type') };
321 dt.setData('text', JSON.stringify(dragData));
322 if (dt.setDragImage) {
323 var img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
324 dt.setDragImage(img.get(0), 12, 21);
330 page.pushstate = page.popstate = function() {
331 $(".search_form").hide();
332 $(".directions_form").show();
334 $("#map").on('dragend dragover', function (e) {
338 $("#map").on('drop', function (e) {
340 var oe = e.originalEvent;
341 var dragData = JSON.parse(oe.dataTransfer.getData('text'));
342 var type = dragData.type;
343 var pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
345 var ll = map.containerPointToLatLng(pt);
346 endpoints[type === 'from' ? 0 : 1].setLatLng(ll);
350 var params = querystring.parse(location.search.substring(1)),
351 route = (params.route || '').split(';');
354 setEngine(params.engine);
357 endpoints[0].setValue(params.from || "");
358 endpoints[1].setValue(params.to || "");
360 var o = route[0] && L.latLng(route[0].split(',')),
361 d = route[1] && L.latLng(route[1].split(','));
363 if (o) endpoints[0].setLatLng(o);
364 if (d) endpoints[1].setLatLng(d);
366 map.setSidebarOverlaid(!o || !d);
371 page.load = function() {
375 page.unload = function() {
376 $(".search_form").show();
377 $(".directions_form").hide();
378 $("#map").off('dragend dragover drop');
382 .removeLayer(polyline)
383 .removeLayer(endpoints[0].marker)
384 .removeLayer(endpoints[1].marker);
390 OSM.Directions.engines = [];
392 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
393 if (document.location.protocol === "http:" || supportsHTTPS) {
394 OSM.Directions.engines.push(engine);