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,
47 endpoint.marker.on('drag dragend', function (e) {
48 var 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)) {
53 getRoute(false, !dragging);
57 input.on("keydown", function() {
58 input.removeClass("error");
61 input.on("change", function (e) {
62 awaitingGeocode = true;
64 // make text the same in both text boxes
65 var value = e.target.value;
66 endpoint.setValue(value);
69 endpoint.setValue = function(value, latlng) {
70 endpoint.value = value;
71 delete endpoint.latlng;
72 input.removeClass("error");
76 endpoint.setLatLng(latlng);
78 endpoint.getGeocode();
82 endpoint.getGeocode = function() {
83 // if no one has entered a value yet, then we can't geocode, so don't
85 if (!endpoint.value) {
89 endpoint.awaitingGeocode = true;
91 $.getJSON(OSM.NOMINATIM_URL + 'search?q=' + encodeURIComponent(endpoint.value) + '&format=json', function (json) {
92 endpoint.awaitingGeocode = false;
93 endpoint.hasGeocode = true;
94 if (json.length === 0) {
95 input.addClass("error");
96 alert(I18n.t('javascripts.directions.errors.no_place', {place: endpoint.value}));
100 endpoint.setLatLng(L.latLng(json[0]));
102 input.val(json[0].display_name);
104 if (awaitingGeocode) {
105 awaitingGeocode = false;
106 getRoute(true, true);
111 endpoint.setLatLng = function (ll) {
112 var precision = OSM.zoomPrecision(map.getZoom());
113 input.val(ll.lat.toFixed(precision) + ", " + ll.lng.toFixed(precision));
114 endpoint.hasGeocode = true;
115 endpoint.latlng = ll;
124 $(".directions_form .reverse_directions").on("click", function() {
125 var from = endpoints[0].latlng,
126 to = endpoints[1].latlng;
128 OSM.router.route("/directions?" + querystring.stringify({
129 from: $("#route_to").val(),
130 to: $("#route_from").val(),
131 route: to.lat + "," + to.lng + ";" + from.lat + "," + from.lng
135 $(".directions_form .close").on("click", function(e) {
137 var route_from = endpoints[0].value;
139 OSM.router.route("/?query=" + encodeURIComponent(route_from) + OSM.formatHash(map));
141 OSM.router.route("/" + OSM.formatHash(map));
145 function formatDistance(m) {
147 return Math.round(m) + "m";
148 } else if (m < 10000) {
149 return (m / 1000.0).toFixed(1) + "km";
151 return Math.round(m / 1000) + "km";
155 function formatTime(s) {
156 var m = Math.round(s / 60);
157 var h = Math.floor(m / 60);
159 return h + ":" + (m < 10 ? '0' : '') + m;
162 function findEngine(id) {
163 return engines.findIndex(function(engine) {
164 return engine.id === id;
168 function setEngine(index) {
169 chosenEngine = engines[index];
173 function getRoute(fitRoute, reportErrors) {
174 // Cancel any route that is already in progress
175 if (awaitingRoute) awaitingRoute.abort();
177 // go fetch geocodes for any endpoints which have not already
179 for (var ep_i = 0; ep_i < 2; ++ep_i) {
180 var endpoint = endpoints[ep_i];
181 if (!endpoint.hasGeocode && !endpoint.awaitingGeocode) {
182 endpoint.getGeocode();
183 awaitingGeocode = true;
186 if (endpoints[0].awaitingGeocode || endpoints[1].awaitingGeocode) {
187 awaitingGeocode = true;
191 var o = endpoints[0].latlng,
192 d = endpoints[1].latlng;
194 if (!o || !d) return;
195 $("header").addClass("closed");
197 var precision = OSM.zoomPrecision(map.getZoom());
199 OSM.router.replace("/directions?" + querystring.stringify({
200 engine: chosenEngine.id,
201 route: o.lat.toFixed(precision) + ',' + o.lng.toFixed(precision) + ';' +
202 d.lat.toFixed(precision) + ',' + d.lng.toFixed(precision)
205 // copy loading item to sidebar and display it. we copy it, rather than
206 // just using it in-place and replacing it in case it has to be used
208 $('#sidebar_content').html($('.directions_form .loader_copy').html());
209 map.setSidebarOverlaid(false);
211 awaitingRoute = chosenEngine.getRoute([o, d], function (err, route) {
212 awaitingRoute = null;
215 map.removeLayer(polyline);
218 $('#sidebar_content').html('<p class="search_results_error">' + I18n.t('javascripts.directions.errors.no_route') + '</p>');
225 .setLatLngs(route.line)
229 map.fitBounds(polyline.getBounds().pad(0.05));
232 var html = '<h2><a class="geolink" href="#">' +
233 '<span class="icon close"></span></a>' + I18n.t('javascripts.directions.directions') +
234 '</h2><p id="routing_summary">' +
235 I18n.t('javascripts.directions.distance') + ': ' + formatDistance(route.distance) + '. ' +
236 I18n.t('javascripts.directions.time') + ': ' + formatTime(route.time) + '.';
237 if (typeof route.ascend !== 'undefined' && typeof route.descend !== 'undefined') {
239 I18n.t('javascripts.directions.ascend') + ': ' + Math.round(route.ascend) + 'm. ' +
240 I18n.t('javascripts.directions.descend') + ': ' + Math.round(route.descend) +'m.';
242 html += '</p><table id="turnbyturn" />';
244 $('#sidebar_content')
249 route.steps.forEach(function (step) {
252 instruction = step[2],
260 } else if (dist < 200) {
261 dist = Math.round(dist / 10) * 10 + "m";
262 } else if (dist < 1500) {
263 dist = Math.round(dist / 100) * 100 + "m";
264 } else if (dist < 5000) {
265 dist = Math.round(dist / 100) / 10 + "km";
267 dist = Math.round(dist / 1000) + "km";
270 var row = $("<tr class='turn'/>");
271 row.append("<td><div class='direction i" + direction + "'/></td> ");
272 row.append("<td class='instruction'>" + instruction);
273 row.append("<td class='distance'>" + dist);
275 row.on('click', function () {
278 .setContent("<p>" + instruction + "</p>")
282 row.hover(function () {
287 map.removeLayer(highlight);
290 $('#turnbyturn').append(row);
293 $('#sidebar_content').append('<p id="routing_credit">' +
294 I18n.t('javascripts.directions.instructions.courtesy', {link: chosenEngine.creditline}) +
297 $('#sidebar_content a.geolink').on('click', function(e) {
299 map.removeLayer(polyline);
300 $('#sidebar_content').html('');
301 map.setSidebarOverlaid(true);
302 // TODO: collapse width of sidebar back to previous
307 var engines = OSM.Directions.engines;
309 engines.sort(function (a, b) {
310 a = I18n.t('javascripts.directions.engines.' + a.id);
311 b = I18n.t('javascripts.directions.engines.' + b.id);
312 return a.localeCompare(b);
315 var select = $('select.routing_engines');
317 engines.forEach(function(engine, i) {
318 select.append("<option value='" + i + "'>" + I18n.t('javascripts.directions.engines.' + engine.id) + "</option>");
321 var chosenEngineIndex = findEngine('fossgis_osrm_car');
322 if ($.cookie('_osm_directions_engine')) {
323 chosenEngineIndex = findEngine($.cookie('_osm_directions_engine'));
325 setEngine(chosenEngineIndex);
327 select.on("change", function (e) {
328 chosenEngine = engines[e.target.selectedIndex];
329 $.cookie('_osm_directions_engine', chosenEngine.id, { expires: expiry, path: '/' });
330 if (map.hasLayer(polyline)) {
331 getRoute(true, true);
335 $(".directions_form").on("submit", function(e) {
337 getRoute(true, true);
340 $(".routing_marker").on('dragstart', function (e) {
341 var dt = e.originalEvent.dataTransfer;
342 dt.effectAllowed = 'move';
343 var dragData = { type: $(this).data('type') };
344 dt.setData('text', JSON.stringify(dragData));
345 if (dt.setDragImage) {
346 var img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
347 dt.setDragImage(img.get(0), 12, 21);
353 page.pushstate = page.popstate = function() {
354 $(".search_form").hide();
355 $(".directions_form").show();
357 $("#map").on('dragend dragover', function (e) {
361 $("#map").on('drop', function (e) {
363 var oe = e.originalEvent;
364 var dragData = JSON.parse(oe.dataTransfer.getData('text'));
365 var type = dragData.type;
366 var pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
368 var ll = map.containerPointToLatLng(pt);
369 endpoints[type === 'from' ? 0 : 1].setLatLng(ll);
370 getRoute(true, true);
373 var params = querystring.parse(location.search.substring(1)),
374 route = (params.route || '').split(';'),
375 from = route[0] && L.latLng(route[0].split(',')),
376 to = route[1] && L.latLng(route[1].split(','));
379 var engineIndex = findEngine(params.engine);
381 if (engineIndex >= 0) {
382 setEngine(engineIndex);
386 endpoints[0].setValue(params.from || "", from);
387 endpoints[1].setValue(params.to || "", to);
389 map.setSidebarOverlaid(!from || !to);
391 getRoute(true, true);
394 page.load = function() {
398 page.unload = function() {
399 $(".search_form").show();
400 $(".directions_form").hide();
401 $("#map").off('dragend dragover drop');
405 .removeLayer(polyline)
406 .removeLayer(endpoints[0].marker)
407 .removeLayer(endpoints[1].marker);
413 OSM.Directions.engines = [];
415 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
416 if (document.location.protocol === "http:" || supportsHTTPS) {
417 OSM.Directions.engines.push(engine);