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']"), <%= 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)
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 + '<%= 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 a.directions_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 // go fetch geocodes for any endpoints which have not already
150 for (var ep_i = 0; ep_i < 2; ++ep_i) {
151 var endpoint = endpoints[ep_i];
152 if (!endpoint.hasGeocode && !endpoint.awaitingGeocode) {
153 endpoint.getGeocode();
154 awaitingGeocode = true;
157 if (endpoints[0].awaitingGeocode || endpoints[1].awaitingGeocode) {
158 awaitingGeocode = true;
162 var o = endpoints[0].latlng,
163 d = endpoints[1].latlng;
165 if (!o || !d) return;
166 $("header").addClass("closed");
168 var precision = OSM.zoomPrecision(map.getZoom());
170 OSM.router.replace("/directions?" + querystring.stringify({
171 engine: chosenEngine.id,
172 route: o.lat.toFixed(precision) + ',' + o.lng.toFixed(precision) + ';' +
173 d.lat.toFixed(precision) + ',' + d.lng.toFixed(precision)
176 // copy loading item to sidebar and display it. we copy it, rather than
177 // just using it in-place and replacing it in case it has to be used
179 $('#sidebar_content').html($('.directions_form .loader_copy').html());
180 awaitingRoute = true;
181 map.setSidebarOverlaid(false);
183 chosenEngine.getRoute([o, d], function (err, route) {
184 awaitingRoute = false;
187 map.removeLayer(polyline);
190 alert(I18n.t('javascripts.directions.errors.no_route'));
197 .setLatLngs(route.line)
201 map.fitBounds(polyline.getBounds().pad(0.05));
204 var html = '<h2><a class="geolink" href="#">' +
205 '<span class="icon close"></span></a>' + I18n.t('javascripts.directions.directions') +
206 '</h2><p id="routing_summary">' +
207 I18n.t('javascripts.directions.distance') + ': ' + formatDistance(route.distance) + '. ' +
208 I18n.t('javascripts.directions.time') + ': ' + formatTime(route.time) + '.</p>' +
209 '<table id="turnbyturn" />';
211 $('#sidebar_content')
216 route.steps.forEach(function (step) {
219 instruction = step[2],
227 } else if (dist < 200) {
228 dist = Math.round(dist / 10) * 10 + "m";
229 } else if (dist < 1500) {
230 dist = Math.round(dist / 100) * 100 + "m";
231 } else if (dist < 5000) {
232 dist = Math.round(dist / 100) / 10 + "km";
234 dist = Math.round(dist / 1000) + "km";
237 var row = $("<tr class='turn'/>");
238 row.append("<td><div class='direction i" + direction + "'/></td> ");
239 row.append("<td class='instruction'>" + instruction);
240 row.append("<td class='distance'>" + dist);
242 row.on('click', function () {
245 .setContent("<p>" + instruction + "</p>")
249 row.hover(function () {
254 map.removeLayer(highlight);
257 $('#turnbyturn').append(row);
260 $('#sidebar_content').append('<p id="routing_credit">' +
261 I18n.t('javascripts.directions.instructions.courtesy', {link: chosenEngine.creditline}) +
264 $('#sidebar_content a.geolink').on('click', function(e) {
266 map.removeLayer(polyline);
267 $('#sidebar_content').html('');
268 map.setSidebarOverlaid(true);
269 // TODO: collapse width of sidebar back to previous
274 var engines = OSM.Directions.engines;
276 engines.sort(function (a, b) {
277 a = I18n.t('javascripts.directions.engines.' + a.id);
278 b = I18n.t('javascripts.directions.engines.' + b.id);
279 return a.localeCompare(b);
282 var select = $('select.routing_engines');
284 engines.forEach(function(engine, i) {
285 select.append("<option value='" + i + "'>" + I18n.t('javascripts.directions.engines.' + engine.id) + "</option>");
288 setEngine('osrm_car');
290 select.on("change", function (e) {
291 chosenEngine = engines[e.target.selectedIndex];
292 if (map.hasLayer(polyline)) {
297 $(".directions_form").on("submit", function(e) {
302 $(".routing_marker").on('dragstart', function (e) {
303 e.originalEvent.dataTransfer.effectAllowed = 'move';
304 e.originalEvent.dataTransfer.setData('id', this.id);
305 var xo = e.originalEvent.clientX - $(e.target).offset().left;
306 var yo = e.originalEvent.clientY - $(e.target).offset().top;
307 e.originalEvent.dataTransfer.setData('offsetX', e.originalEvent.target.width / 2 - xo);
308 e.originalEvent.dataTransfer.setData('offsetY', e.originalEvent.target.height - yo);
313 page.pushstate = page.popstate = function() {
314 $(".search_form").hide();
315 $(".directions_form").show();
317 $("#map").on('dragend dragover', function (e) {
321 $("#map").on('drop', function (e) {
323 var oe = e.originalEvent;
324 var id = oe.dataTransfer.getData('id');
325 var pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
326 pt.x += Number(oe.dataTransfer.getData('offsetX'));
327 pt.y += Number(oe.dataTransfer.getData('offsetY'));
328 var ll = map.containerPointToLatLng(pt);
329 endpoints[id === 'marker_from' ? 0 : 1].setLatLng(ll);
333 var params = querystring.parse(location.search.substring(1)),
334 route = (params.route || '').split(';');
337 setEngine(params.engine);
341 endpoints[0].setValue(params.from);
342 endpoints[1].setValue("");
344 endpoints[0].setValue("");
345 endpoints[1].setValue("");
348 var o = route[0] && L.latLng(route[0].split(',')),
349 d = route[1] && L.latLng(route[1].split(','));
351 if (o) endpoints[0].setLatLng(o);
352 if (d) endpoints[1].setLatLng(d);
354 map.setSidebarOverlaid(!o || !d);
359 page.load = function() {
363 page.unload = function() {
364 $(".search_form").show();
365 $(".directions_form").hide();
366 $("#map").off('dragend dragover drop');
370 .removeLayer(polyline)
371 .removeLayer(endpoints[0].marker)
372 .removeLayer(endpoints[1].marker);
378 OSM.Directions.engines = [];
380 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
381 if (document.location.protocol == "http:" || supportsHTTPS) {
382 OSM.Directions.engines.push(engine);