2 //= require_tree ./directions_engines
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']"), <%= asset_path('marker-green.png').to_json %>),
26 Endpoint($("input[name='route_to']"), <%= asset_path('marker-red.png').to_json %>)
29 function Endpoint(input, iconUrl) {
32 endpoint.marker = L.marker([0, 0], {
37 popupAnchor: [1, -34],
38 shadowUrl: <%= asset_path('images/marker-shadow.png').to_json %>,
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)
58 endpoint.getGeocode();
61 endpoint.setValue = function(value) {
62 endpoint.value = value;
66 endpoint.getGeocode = function() {
67 // if no one has entered a value yet, then we can't geocode, so don't
69 if (!endpoint.value) {
73 endpoint.awaitingGeocode = true;
75 $.getJSON('<%= NOMINATIM_URL %>search?q=' + encodeURIComponent(endpoint.value) + '&format=json', function (json) {
76 endpoint.awaitingGeocode = false;
77 endpoint.hasGeocode = true;
78 if (json.length == 0) {
79 alert(I18n.t('javascripts.directions.errors.no_place'));
83 input.val(json[0].display_name);
85 endpoint.latlng = L.latLng(json[0]);
87 .setLatLng(endpoint.latlng)
90 if (awaitingGeocode) {
91 awaitingGeocode = false;
97 endpoint.setLatLng = function (ll) {
98 var precision = OSM.zoomPrecision(map.getZoom());
99 input.val(ll.lat.toFixed(precision) + ", " + ll.lng.toFixed(precision));
100 endpoint.hasGeocode = true;
101 endpoint.latlng = ll;
110 $(".directions_form a.directions_close").on("click", function(e) {
112 var route_from = endpoints[0].value;
114 OSM.router.route("/?query=" + encodeURIComponent(route_from) + OSM.formatHash(map));
116 OSM.router.route("/" + OSM.formatHash(map));
120 function formatDistance(m) {
122 return Math.round(m) + "m";
123 } else if (m < 10000) {
124 return (m / 1000.0).toFixed(1) + "km";
126 return Math.round(m / 1000) + "km";
130 function formatTime(s) {
131 var m = Math.round(s / 60);
132 var h = Math.floor(m / 60);
134 return h + ":" + (m < 10 ? '0' : '') + m;
137 function setEngine(id) {
138 engines.forEach(function(engine, i) {
139 if (engine.id == id) {
140 chosenEngine = engine;
146 function getRoute() {
147 // go fetch geocodes for any endpoints which have not already
149 for (var ep_i = 0; ep_i < 2; ++ep_i) {
150 var endpoint = endpoints[ep_i];
151 if (!endpoint.hasGeocode && !endpoint.awaitingGeocode) {
152 endpoint.getGeocode();
153 awaitingGeocode = true;
156 if (endpoints[0].awaitingGeocode || endpoints[1].awaitingGeocode) {
157 awaitingGeocode = true;
161 var o = endpoints[0].latlng,
162 d = endpoints[1].latlng;
164 if (!o || !d) return;
166 var precision = OSM.zoomPrecision(map.getZoom());
168 OSM.router.replace("/directions?" + querystring.stringify({
169 engine: chosenEngine.id,
170 route: o.lat.toFixed(precision) + ',' + o.lng.toFixed(precision) + ';' +
171 d.lat.toFixed(precision) + ',' + d.lng.toFixed(precision)
174 // copy loading item to sidebar and display it. we copy it, rather than
175 // just using it in-place and replacing it in case it has to be used
177 $('#sidebar_content').html($('.directions_form .loader_copy').html());
178 awaitingRoute = true;
179 map.setSidebarOverlaid(false);
181 chosenEngine.getRoute([o, d], function (err, route) {
182 awaitingRoute = false;
185 map.removeLayer(polyline);
188 alert(I18n.t('javascripts.directions.errors.no_route'));
195 .setLatLngs(route.line)
199 map.fitBounds(polyline.getBounds().pad(0.05));
202 var html = '<h2><a class="geolink" href="#">' +
203 '<span class="icon close"></span></a>' + I18n.t('javascripts.directions.directions') +
204 '</h2><p id="routing_summary">' +
205 I18n.t('javascripts.directions.distance') + ': ' + formatDistance(route.distance) + '. ' +
206 I18n.t('javascripts.directions.time') + ': ' + formatTime(route.time) + '.</p>' +
207 '<table id="turnbyturn" />';
209 $('#sidebar_content')
214 route.steps.forEach(function (step) {
217 instruction = step[2],
225 } else if (dist < 200) {
226 dist = Math.round(dist / 10) * 10 + "m";
227 } else if (dist < 1500) {
228 dist = Math.round(dist / 100) * 100 + "m";
229 } else if (dist < 5000) {
230 dist = Math.round(dist / 100) / 10 + "km";
232 dist = Math.round(dist / 1000) + "km";
235 var row = $("<tr class='turn'/>");
236 row.append("<td><div class='direction i" + direction + "'/></td> ");
237 row.append("<td class='instruction'>" + instruction);
238 row.append("<td class='distance'>" + dist);
240 row.on('click', function () {
243 .setContent("<p>" + instruction + "</p>")
247 row.hover(function () {
252 map.removeLayer(highlight);
255 $('#turnbyturn').append(row);
258 $('#sidebar_content').append('<p id="routing_credit">' +
259 I18n.t('javascripts.directions.instructions.courtesy', {link: chosenEngine.creditline}) +
262 $('#sidebar_content a.geolink').on('click', function(e) {
264 map.removeLayer(polyline);
265 $('#sidebar_content').html('');
266 map.setSidebarOverlaid(true);
267 // TODO: collapse width of sidebar back to previous
272 var engines = OSM.Directions.engines;
274 engines.sort(function (a, b) {
275 a = I18n.t('javascripts.directions.engines.' + a.id);
276 b = I18n.t('javascripts.directions.engines.' + b.id);
277 return a.localeCompare(b);
280 var select = $('select.routing_engines');
282 engines.forEach(function(engine, i) {
283 select.append("<option value='" + i + "'>" + I18n.t('javascripts.directions.engines.' + engine.id) + "</option>");
286 setEngine('osrm_car');
288 select.on("change", function (e) {
289 chosenEngine = engines[e.target.selectedIndex];
290 if (map.hasLayer(polyline)) {
295 $(".directions_form").on("submit", function(e) {
297 $("header").addClass("closed");
301 $(".routing_marker").on('dragstart', function (e) {
302 e.originalEvent.dataTransfer.effectAllowed = 'move';
303 e.originalEvent.dataTransfer.setData('id', this.id);
304 var xo = e.originalEvent.clientX - $(e.target).offset().left;
305 var yo = e.originalEvent.clientY - $(e.target).offset().top;
306 e.originalEvent.dataTransfer.setData('offsetX', e.originalEvent.target.width / 2 - xo);
307 e.originalEvent.dataTransfer.setData('offsetY', e.originalEvent.target.height - yo);
312 page.pushstate = page.popstate = function() {
313 $(".search_form").hide();
314 $(".directions_form").show();
316 $("#map").on('dragend dragover', function (e) {
320 $("#map").on('drop', function (e) {
322 var oe = e.originalEvent;
323 var id = oe.dataTransfer.getData('id');
324 var pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
325 pt.x += Number(oe.dataTransfer.getData('offsetX'));
326 pt.y += Number(oe.dataTransfer.getData('offsetY'));
327 var ll = map.containerPointToLatLng(pt);
328 endpoints[id === 'marker_from' ? 0 : 1].setLatLng(ll);
332 var params = querystring.parse(location.search.substring(1)),
333 route = (params.route || '').split(';');
336 setEngine(params.engine);
340 endpoints[0].setValue(params.from);
343 var o = route[0] && L.latLng(route[0].split(',')),
344 d = route[1] && L.latLng(route[1].split(','));
346 if (o) endpoints[0].setLatLng(o);
347 if (d) endpoints[1].setLatLng(d);
349 map.setSidebarOverlaid(!o || !d);
354 page.load = function() {
358 page.unload = function() {
359 $(".search_form").show();
360 $(".directions_form").hide();
361 $("#map").off('dragend dragover drop');
365 .removeLayer(polyline)
366 .removeLayer(endpoints[0].marker)
367 .removeLayer(endpoints[1].marker);
373 OSM.Directions.engines = [];
375 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
376 if (document.location.protocol == "http:" || supportsHTTPS) {
377 OSM.Directions.engines.push(engine);