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;
75 endpoint.setLatLng(latlng);
77 endpoint.getGeocode();
81 endpoint.getGeocode = function() {
82 // if no one has entered a value yet, then we can't geocode, so don't
84 if (!endpoint.value) {
88 endpoint.awaitingGeocode = true;
90 $.getJSON(OSM.NOMINATIM_URL + 'search?q=' + encodeURIComponent(endpoint.value) + '&format=json', function (json) {
91 endpoint.awaitingGeocode = false;
92 endpoint.hasGeocode = true;
93 if (json.length === 0) {
94 input.addClass("error");
95 alert(I18n.t('javascripts.directions.errors.no_place', {place: endpoint.value}));
99 endpoint.setLatLng(L.latLng(json[0]));
101 input.val(json[0].display_name);
103 if (awaitingGeocode) {
104 awaitingGeocode = false;
105 getRoute(true, true);
110 endpoint.setLatLng = function (ll) {
111 var precision = OSM.zoomPrecision(map.getZoom());
112 input.val(ll.lat.toFixed(precision) + ", " + ll.lng.toFixed(precision));
113 endpoint.hasGeocode = true;
114 endpoint.latlng = ll;
123 $(".directions_form .reverse_directions").on("click", function() {
124 var from = endpoints[0].latlng,
125 to = endpoints[1].latlng;
127 OSM.router.route("/directions?" + querystring.stringify({
128 from: $("#route_to").val(),
129 to: $("#route_from").val(),
130 route: to.lat + "," + to.lng + ";" + from.lat + "," + from.lng
134 $(".directions_form .close").on("click", function(e) {
136 var route_from = endpoints[0].value;
138 OSM.router.route("/?query=" + encodeURIComponent(route_from) + OSM.formatHash(map));
140 OSM.router.route("/" + OSM.formatHash(map));
144 function formatDistance(m) {
146 return Math.round(m) + "m";
147 } else if (m < 10000) {
148 return (m / 1000.0).toFixed(1) + "km";
150 return Math.round(m / 1000) + "km";
154 function formatTime(s) {
155 var m = Math.round(s / 60);
156 var h = Math.floor(m / 60);
158 return h + ":" + (m < 10 ? '0' : '') + m;
161 function setEngine(id) {
162 engines.forEach(function(engine, i) {
163 if (engine.id === id) {
164 chosenEngine = engine;
170 function getRoute(fitRoute, reportErrors) {
171 // Cancel any route that is already in progress
172 if (awaitingRoute) awaitingRoute.abort();
174 // go fetch geocodes for any endpoints which have not already
176 for (var ep_i = 0; ep_i < 2; ++ep_i) {
177 var endpoint = endpoints[ep_i];
178 if (!endpoint.hasGeocode && !endpoint.awaitingGeocode) {
179 endpoint.getGeocode();
180 awaitingGeocode = true;
183 if (endpoints[0].awaitingGeocode || endpoints[1].awaitingGeocode) {
184 awaitingGeocode = true;
188 var o = endpoints[0].latlng,
189 d = endpoints[1].latlng;
191 if (!o || !d) return;
192 $("header").addClass("closed");
194 var precision = OSM.zoomPrecision(map.getZoom());
196 OSM.router.replace("/directions?" + querystring.stringify({
197 engine: chosenEngine.id,
198 route: o.lat.toFixed(precision) + ',' + o.lng.toFixed(precision) + ';' +
199 d.lat.toFixed(precision) + ',' + d.lng.toFixed(precision)
202 // copy loading item to sidebar and display it. we copy it, rather than
203 // just using it in-place and replacing it in case it has to be used
205 $('#sidebar_content').html($('.directions_form .loader_copy').html());
206 map.setSidebarOverlaid(false);
208 awaitingRoute = chosenEngine.getRoute([o, d], function (err, route) {
209 awaitingRoute = null;
212 map.removeLayer(polyline);
215 $('#sidebar_content').html('<p class="search_results_error">' + I18n.t('javascripts.directions.errors.no_route') + '</p>');
222 .setLatLngs(route.line)
226 map.fitBounds(polyline.getBounds().pad(0.05));
229 var html = '<h2><a class="geolink" href="#">' +
230 '<span class="icon close"></span></a>' + I18n.t('javascripts.directions.directions') +
231 '</h2><p id="routing_summary">' +
232 I18n.t('javascripts.directions.distance') + ': ' + formatDistance(route.distance) + '. ' +
233 I18n.t('javascripts.directions.time') + ': ' + formatTime(route.time) + '.';
234 if (typeof route.ascend !== 'undefined' && typeof route.descend !== 'undefined') {
236 I18n.t('javascripts.directions.ascend') + ': ' + Math.round(route.ascend) + 'm. ' +
237 I18n.t('javascripts.directions.descend') + ': ' + Math.round(route.descend) +'m.';
239 html += '</p><table id="turnbyturn" />';
241 $('#sidebar_content')
246 route.steps.forEach(function (step) {
249 instruction = step[2],
257 } else if (dist < 200) {
258 dist = Math.round(dist / 10) * 10 + "m";
259 } else if (dist < 1500) {
260 dist = Math.round(dist / 100) * 100 + "m";
261 } else if (dist < 5000) {
262 dist = Math.round(dist / 100) / 10 + "km";
264 dist = Math.round(dist / 1000) + "km";
267 var row = $("<tr class='turn'/>");
268 row.append("<td><div class='direction i" + direction + "'/></td> ");
269 row.append("<td class='instruction'>" + instruction);
270 row.append("<td class='distance'>" + dist);
272 row.on('click', function () {
275 .setContent("<p>" + instruction + "</p>")
279 row.hover(function () {
284 map.removeLayer(highlight);
287 $('#turnbyturn').append(row);
290 $('#sidebar_content').append('<p id="routing_credit">' +
291 I18n.t('javascripts.directions.instructions.courtesy', {link: chosenEngine.creditline}) +
294 $('#sidebar_content a.geolink').on('click', function(e) {
296 map.removeLayer(polyline);
297 $('#sidebar_content').html('');
298 map.setSidebarOverlaid(true);
299 // TODO: collapse width of sidebar back to previous
304 var engines = OSM.Directions.engines;
306 engines.sort(function (a, b) {
307 a = I18n.t('javascripts.directions.engines.' + a.id);
308 b = I18n.t('javascripts.directions.engines.' + b.id);
309 return a.localeCompare(b);
312 var select = $('select.routing_engines');
314 engines.forEach(function(engine, i) {
315 select.append("<option value='" + i + "'>" + I18n.t('javascripts.directions.engines.' + engine.id) + "</option>");
318 var chosenEngineId = $.cookie('_osm_directions_engine');
319 if(!chosenEngineId) {
320 chosenEngineId = 'osrm_car';
322 setEngine(chosenEngineId);
324 select.on("change", function (e) {
325 chosenEngine = engines[e.target.selectedIndex];
326 $.cookie('_osm_directions_engine', chosenEngine.id, { expires: expiry, path: '/' });
327 if (map.hasLayer(polyline)) {
328 getRoute(true, true);
332 $(".directions_form").on("submit", function(e) {
334 getRoute(true, true);
337 $(".routing_marker").on('dragstart', function (e) {
338 var dt = e.originalEvent.dataTransfer;
339 dt.effectAllowed = 'move';
340 var dragData = { type: $(this).data('type') };
341 dt.setData('text', JSON.stringify(dragData));
342 if (dt.setDragImage) {
343 var img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
344 dt.setDragImage(img.get(0), 12, 21);
350 page.pushstate = page.popstate = function() {
351 $(".search_form").hide();
352 $(".directions_form").show();
354 $("#map").on('dragend dragover', function (e) {
358 $("#map").on('drop', function (e) {
360 var oe = e.originalEvent;
361 var dragData = JSON.parse(oe.dataTransfer.getData('text'));
362 var type = dragData.type;
363 var pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
365 var ll = map.containerPointToLatLng(pt);
366 endpoints[type === 'from' ? 0 : 1].setLatLng(ll);
367 getRoute(true, true);
370 var params = querystring.parse(location.search.substring(1)),
371 route = (params.route || '').split(';'),
372 from = route[0] && L.latLng(route[0].split(',')),
373 to = route[1] && L.latLng(route[1].split(','));
376 setEngine(params.engine);
379 endpoints[0].setValue(params.from || "", from);
380 endpoints[1].setValue(params.to || "", to);
382 map.setSidebarOverlaid(!from || !to);
384 getRoute(true, true);
387 page.load = function() {
391 page.unload = function() {
392 $(".search_form").show();
393 $(".directions_form").hide();
394 $("#map").off('dragend dragover drop');
398 .removeLayer(polyline)
399 .removeLayer(endpoints[0].marker)
400 .removeLayer(endpoints[1].marker);
406 OSM.Directions.engines = [];
408 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
409 if (document.location.protocol === "http:" || supportsHTTPS) {
410 OSM.Directions.engines.push(engine);