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 function Endpoint(input, iconUrl) {
32 endpoint.marker = L.marker([0, 0], {
37 popupAnchor: [1, -34],
38 shadowUrl: OSM.MARKER_SHADOW,
44 endpoint.marker.on('drag dragend', function (e) {
45 dragging = (e.type === 'drag');
46 if (dragging && !chosenEngine.draggable) return;
47 if (dragging && awaitingRoute) return;
48 endpoint.setLatLng(e.target.getLatLng());
49 if (map.hasLayer(polyline)) {
54 input.on("change", function (e) {
55 // make text the same in both text boxes
56 var value = e.target.value;
57 endpoint.setValue(value);
60 endpoint.setValue = function(value) {
61 endpoint.value = value;
62 delete endpoint.latlng;
64 endpoint.getGeocode();
67 endpoint.getGeocode = function() {
68 // if no one has entered a value yet, then we can't geocode, so don't
70 if (!endpoint.value) {
74 endpoint.awaitingGeocode = true;
76 $.getJSON(document.location.protocol + OSM.NOMINATIM_URL + 'search?q=' + encodeURIComponent(endpoint.value) + '&format=json', function (json) {
77 endpoint.awaitingGeocode = false;
78 endpoint.hasGeocode = true;
79 if (json.length === 0) {
80 alert(I18n.t('javascripts.directions.errors.no_place'));
84 input.val(json[0].display_name);
86 endpoint.latlng = L.latLng(json[0]);
88 .setLatLng(endpoint.latlng)
91 if (awaitingGeocode) {
92 awaitingGeocode = false;
98 endpoint.setLatLng = function (ll) {
99 var precision = OSM.zoomPrecision(map.getZoom());
100 input.val(ll.lat.toFixed(precision) + ", " + ll.lng.toFixed(precision));
101 endpoint.hasGeocode = true;
102 endpoint.latlng = ll;
111 $(".directions_form .close").on("click", function(e) {
113 var route_from = endpoints[0].value;
115 OSM.router.route("/?query=" + encodeURIComponent(route_from) + OSM.formatHash(map));
117 OSM.router.route("/" + OSM.formatHash(map));
121 function formatDistance(m) {
123 return Math.round(m) + "m";
124 } else if (m < 10000) {
125 return (m / 1000.0).toFixed(1) + "km";
127 return Math.round(m / 1000) + "km";
131 function formatTime(s) {
132 var m = Math.round(s / 60);
133 var h = Math.floor(m / 60);
135 return h + ":" + (m < 10 ? '0' : '') + m;
138 function setEngine(id) {
139 engines.forEach(function(engine, i) {
140 if (engine.id === id) {
141 chosenEngine = engine;
147 function getRoute() {
148 // Cancel any route that is already in progress
149 if (awaitingRoute) awaitingRoute.abort();
151 // go fetch geocodes for any endpoints which have not already
153 for (var ep_i = 0; ep_i < 2; ++ep_i) {
154 var endpoint = endpoints[ep_i];
155 if (!endpoint.hasGeocode && !endpoint.awaitingGeocode) {
156 endpoint.getGeocode();
157 awaitingGeocode = true;
160 if (endpoints[0].awaitingGeocode || endpoints[1].awaitingGeocode) {
161 awaitingGeocode = true;
165 var o = endpoints[0].latlng,
166 d = endpoints[1].latlng;
168 if (!o || !d) return;
169 $("header").addClass("closed");
171 var precision = OSM.zoomPrecision(map.getZoom());
173 OSM.router.replace("/directions?" + querystring.stringify({
174 engine: chosenEngine.id,
175 route: o.lat.toFixed(precision) + ',' + o.lng.toFixed(precision) + ';' +
176 d.lat.toFixed(precision) + ',' + d.lng.toFixed(precision)
179 // copy loading item to sidebar and display it. we copy it, rather than
180 // just using it in-place and replacing it in case it has to be used
182 $('#sidebar_content').html($('.directions_form .loader_copy').html());
183 map.setSidebarOverlaid(false);
185 awaitingRoute = chosenEngine.getRoute([o, d], function (err, route) {
186 awaitingRoute = null;
189 map.removeLayer(polyline);
192 $('#sidebar_content').html('<p class="search_results_error">' + I18n.t('javascripts.directions.errors.no_route') + '</p>');
199 .setLatLngs(route.line)
203 map.fitBounds(polyline.getBounds().pad(0.05));
206 var html = '<h2><a class="geolink" href="#">' +
207 '<span class="icon close"></span></a>' + I18n.t('javascripts.directions.directions') +
208 '</h2><p id="routing_summary">' +
209 I18n.t('javascripts.directions.distance') + ': ' + formatDistance(route.distance) + '. ' +
210 I18n.t('javascripts.directions.time') + ': ' + formatTime(route.time) + '.';
211 if (typeof route.ascend !== 'undefined' && typeof route.descend !== 'undefined') {
213 I18n.t('javascripts.directions.ascend') + ': ' + Math.round(route.ascend) + 'm. ' +
214 I18n.t('javascripts.directions.descend') + ': ' + Math.round(route.descend) +'m.';
216 html += '</p><table id="turnbyturn" />';
218 $('#sidebar_content')
223 route.steps.forEach(function (step) {
226 instruction = step[2],
234 } else if (dist < 200) {
235 dist = Math.round(dist / 10) * 10 + "m";
236 } else if (dist < 1500) {
237 dist = Math.round(dist / 100) * 100 + "m";
238 } else if (dist < 5000) {
239 dist = Math.round(dist / 100) / 10 + "km";
241 dist = Math.round(dist / 1000) + "km";
244 var row = $("<tr class='turn'/>");
245 row.append("<td><div class='direction i" + direction + "'/></td> ");
246 row.append("<td class='instruction'>" + instruction);
247 row.append("<td class='distance'>" + dist);
249 row.on('click', function () {
252 .setContent("<p>" + instruction + "</p>")
256 row.hover(function () {
261 map.removeLayer(highlight);
264 $('#turnbyturn').append(row);
267 $('#sidebar_content').append('<p id="routing_credit">' +
268 I18n.t('javascripts.directions.instructions.courtesy', {link: chosenEngine.creditline}) +
271 $('#sidebar_content a.geolink').on('click', function(e) {
273 map.removeLayer(polyline);
274 $('#sidebar_content').html('');
275 map.setSidebarOverlaid(true);
276 // TODO: collapse width of sidebar back to previous
281 var engines = OSM.Directions.engines;
283 engines.sort(function (a, b) {
284 a = I18n.t('javascripts.directions.engines.' + a.id);
285 b = I18n.t('javascripts.directions.engines.' + b.id);
286 return a.localeCompare(b);
289 var select = $('select.routing_engines');
291 engines.forEach(function(engine, i) {
292 select.append("<option value='" + i + "'>" + I18n.t('javascripts.directions.engines.' + engine.id) + "</option>");
295 setEngine('osrm_car');
297 select.on("change", function (e) {
298 chosenEngine = engines[e.target.selectedIndex];
299 if (map.hasLayer(polyline)) {
304 $(".directions_form").on("submit", function(e) {
309 $(".routing_marker").on('dragstart', function (e) {
310 var dt = e.originalEvent.dataTransfer;
311 dt.effectAllowed = 'move';
312 var dragData = { type: $(this).data('type') };
313 dt.setData('text', JSON.stringify(dragData));
314 if (dt.setDragImage) {
315 var img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
316 dt.setDragImage(img.get(0), 12, 21);
322 page.pushstate = page.popstate = function() {
323 $(".search_form").hide();
324 $(".directions_form").show();
326 $("#map").on('dragend dragover', function (e) {
330 $("#map").on('drop', function (e) {
332 var oe = e.originalEvent;
333 var dragData = JSON.parse(oe.dataTransfer.getData('text'));
334 var type = dragData.type;
335 var pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
337 var ll = map.containerPointToLatLng(pt);
338 endpoints[type === 'from' ? 0 : 1].setLatLng(ll);
342 var params = querystring.parse(location.search.substring(1)),
343 route = (params.route || '').split(';');
346 setEngine(params.engine);
349 endpoints[0].setValue(params.from || "");
350 endpoints[1].setValue(params.to || "");
352 var o = route[0] && L.latLng(route[0].split(',')),
353 d = route[1] && L.latLng(route[1].split(','));
355 if (o) endpoints[0].setLatLng(o);
356 if (d) endpoints[1].setLatLng(d);
358 map.setSidebarOverlaid(!o || !d);
363 page.load = function() {
367 page.unload = function() {
368 $(".search_form").show();
369 $(".directions_form").hide();
370 $("#map").off('dragend dragover drop');
374 .removeLayer(polyline)
375 .removeLayer(endpoints[0].marker)
376 .removeLayer(endpoints[1].marker);
382 OSM.Directions.engines = [];
384 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
385 if (document.location.protocol === "http:" || supportsHTTPS) {
386 OSM.Directions.engines.push(engine);