2 //= require_tree ./directions_engines
4 OSM.Directions = function (map) {
5 $(".directions_form a.directions_close").on("click", function(e) {
7 var route_from = $(e.target).parent().parent().parent().find("input[name=route_from]").val();
9 OSM.router.route("/?query=" + encodeURIComponent(route_from) + OSM.formatHash(map));
11 OSM.router.route("/" + OSM.formatHash(map));
15 var awaitingGeocode; // true if the user has requested a route, but we're waiting on a geocode result
16 var awaitingRoute; // true if we've asked the engine for a route and are waiting to hear back
17 var dragging; // true if the user is dragging a start/end point
20 var popup = L.popup();
22 var polyline = L.polyline([], {
28 var highlight = L.polyline([], {
35 Endpoint($("#content input[name='route_from']"), <%= asset_path('marker-green.png').to_json %>),
36 Endpoint($("#content input[name='route_to']"), <%= asset_path('marker-red.png').to_json %>)
39 function Endpoint(input, iconUrl) {
42 endpoint.marker = L.marker([0, 0], {
47 popupAnchor: [1, -34],
48 shadowUrl: <%= asset_path('images/marker-shadow.png').to_json %>,
54 endpoint.marker.on('drag dragend', function (e) {
55 dragging = (e.type == 'drag');
56 if (dragging && !chosenEngine.draggable) return;
57 if (dragging && awaitingRoute) return;
58 endpoint.setLatLng(e.target.getLatLng());
59 if (map.hasLayer(polyline)) {
64 input.on("change", function (e) {
65 endpoint.getGeocode();
68 endpoint.getGeocode = function() {
69 var value = input.val();
71 // if no one has entered a value yet, then we can't geocode, so don't
77 endpoint.awaitingGeocode = true;
79 $.getJSON('<%= NOMINATIM_URL %>search?q=' + encodeURIComponent(value) + '&format=json', function (json) {
80 endpoint.awaitingGeocode = false;
81 endpoint.hasGeocode = true;
83 if (json.length == 0) {
84 alert(I18n.t('javascripts.directions.errors.no_place'));
88 input.val(json[0].display_name);
90 endpoint.latlng = L.latLng(json[0]);
92 .setLatLng(endpoint.latlng)
95 if (awaitingGeocode) {
96 awaitingGeocode = false;
102 endpoint.setLatLng = function (ll) {
103 var precision = OSM.zoomPrecision(map.getZoom());
104 input.val(ll.lat.toFixed(precision) + ", " + ll.lng.toFixed(precision));
105 endpoint.hasGeocode = true;
106 endpoint.latlng = ll;
115 function formatDistance(m) {
117 return Math.round(m) + "m";
118 } else if (m < 10000) {
119 return (m / 1000.0).toFixed(1) + "km";
121 return Math.round(m / 1000) + "km";
125 function formatTime(s) {
126 var m = Math.round(s / 60);
127 var h = Math.floor(m / 60);
129 return h + ":" + (m < 10 ? '0' : '') + m;
132 function setEngine(id) {
133 engines.forEach(function(engine, i) {
134 if (engine.id == id) {
135 chosenEngine = engine;
141 function getRoute() {
142 // go fetch geocodes for any endpoints which have not already
144 for (var ep_i = 0; ep_i < 2; ++ep_i) {
145 var endpoint = endpoints[ep_i];
146 if (!endpoint.hasGeocode && !endpoint.awaitingGeocode) {
147 endpoint.getGeocode();
148 awaitingGeocode = true;
151 if (endpoints[0].awaitingGeocode || endpoints[1].awaitingGeocode) {
152 awaitingGeocode = true;
156 var o = endpoints[0].latlng,
157 d = endpoints[1].latlng;
159 if (!o || !d) return;
161 var precision = OSM.zoomPrecision(map.getZoom());
163 OSM.router.replace("/directions?" + querystring.stringify({
164 engine: chosenEngine.id,
165 route: o.lat.toFixed(precision) + ',' + o.lng.toFixed(precision) + ';' +
166 d.lat.toFixed(precision) + ',' + d.lng.toFixed(precision)
169 // copy loading item to sidebar and display it. we copy it, rather than
170 // just using it in-place and replacing it in case it has to be used
172 $('#sidebar_content').html($('.directions_form .loader_copy').html());
173 awaitingRoute = true;
174 map.setSidebarOverlaid(false);
176 chosenEngine.getRoute([o, d], function (err, route) {
177 awaitingRoute = false;
180 map.removeLayer(polyline);
183 alert(I18n.t('javascripts.directions.errors.no_route'));
190 .setLatLngs(route.line)
194 map.fitBounds(polyline.getBounds().pad(0.05));
197 var html = '<h2><a class="geolink" href="#">' +
198 '<span class="icon close"></span></a>' + I18n.t('javascripts.directions.directions') +
199 '</h2><p id="routing_summary">' +
200 I18n.t('javascripts.directions.distance') + ': ' + formatDistance(route.distance) + '. ' +
201 I18n.t('javascripts.directions.time') + ': ' + formatTime(route.time) + '.</p>' +
202 '<table id="turnbyturn" />';
204 $('#sidebar_content')
209 route.steps.forEach(function (step) {
212 instruction = step[2],
220 } else if (dist < 200) {
221 dist = Math.round(dist / 10) * 10 + "m";
222 } else if (dist < 1500) {
223 dist = Math.round(dist / 100) * 100 + "m";
224 } else if (dist < 5000) {
225 dist = Math.round(dist / 100) / 10 + "km";
227 dist = Math.round(dist / 1000) + "km";
230 var row = $("<tr class='turn'/>");
231 row.append("<td><div class='direction i" + direction + "'/></td> ");
232 row.append("<td class='instruction'>" + instruction);
233 row.append("<td class='distance'>" + dist);
235 row.on('click', function () {
238 .setContent("<p>" + instruction + "</p>")
242 row.hover(function () {
247 map.removeLayer(highlight);
250 $('#turnbyturn').append(row);
253 $('#sidebar_content').append('<p id="routing_credit">' +
254 I18n.t('javascripts.directions.instructions.courtesy', {link: chosenEngine.creditline}) +
257 $('#sidebar_content a.geolink').on('click', function(e) {
259 map.removeLayer(polyline);
260 $('#sidebar_content').html('');
261 map.setSidebarOverlaid(true);
262 // TODO: collapse width of sidebar back to previous
267 var engines = OSM.Directions.engines;
269 engines.sort(function (a, b) {
270 a = I18n.t('javascripts.directions.engines.' + a.id);
271 b = I18n.t('javascripts.directions.engines.' + b.id);
272 return a.localeCompare(b);
275 var select = $('select.routing_engines');
277 engines.forEach(function(engine, i) {
278 select.append("<option value='" + i + "'>" + I18n.t('javascripts.directions.engines.' + engine.id) + "</option>");
281 setEngine('osrm_car');
283 select.on("change", function (e) {
284 chosenEngine = engines[e.target.selectedIndex];
285 if (map.hasLayer(polyline)) {
290 $(".directions_form").on("submit", function(e) {
292 $("header").addClass("closed");
296 $(".routing_marker").on('dragstart', function (e) {
297 e.originalEvent.dataTransfer.effectAllowed = 'move';
298 e.originalEvent.dataTransfer.setData('id', this.id);
299 var xo = e.originalEvent.clientX - $(e.target).offset().left;
300 var yo = e.originalEvent.clientY - $(e.target).offset().top;
301 e.originalEvent.dataTransfer.setData('offsetX', e.originalEvent.target.width / 2 - xo);
302 e.originalEvent.dataTransfer.setData('offsetY', e.originalEvent.target.height - yo);
307 page.pushstate = page.popstate = function() {
308 $(".search_form").hide();
309 $(".directions_form").show();
311 $("#map").on('dragend dragover', function (e) {
315 $("#map").on('drop', function (e) {
317 var oe = e.originalEvent;
318 var id = oe.dataTransfer.getData('id');
319 var pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
320 pt.x += Number(oe.dataTransfer.getData('offsetX'));
321 pt.y += Number(oe.dataTransfer.getData('offsetY'));
322 var ll = map.containerPointToLatLng(pt);
323 endpoints[id === 'marker_from' ? 0 : 1].setLatLng(ll);
327 var params = querystring.parse(location.search.substring(1)),
328 route = (params.route || '').split(';');
331 setEngine(params.engine);
335 $(".directions_form input[name='route_from']").val(params.from);
338 var o = route[0] && L.latLng(route[0].split(',')),
339 d = route[1] && L.latLng(route[1].split(','));
341 if (o) endpoints[0].setLatLng(o);
342 if (d) endpoints[1].setLatLng(d);
344 map.setSidebarOverlaid(!o || !d);
349 page.load = function() {
353 page.unload = function() {
354 $(".search_form").show();
355 $(".directions_form").hide();
356 $("#map").off('dragend dragover drop');
360 .removeLayer(polyline)
361 .removeLayer(endpoints[0].marker)
362 .removeLayer(endpoints[1].marker);
368 OSM.Directions.engines = [];
370 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
371 if (document.location.protocol == "http:" || supportsHTTPS) {
372 OSM.Directions.engines.push(engine);