]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/directions.js.erb
Made top & bottom spacing in directions list consistent.
[rails.git] / app / assets / javascripts / index / directions.js.erb
1 //= require_self
2 //= require_tree ./directions_engines
3
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
8   var chosenEngine;
9
10   var popup = L.popup();
11
12   var polyline = L.polyline([], {
13     color: '#03f',
14     opacity: 0.3,
15     weight: 10
16   });
17
18   var highlight = L.polyline([], {
19     color: '#ff0',
20     opacity: 0.5,
21     weight: 12
22   });
23
24   var endpoints = [
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 %>)
27   ];
28
29   function Endpoint(input, iconUrl) {
30     var endpoint = {};
31
32     endpoint.marker = L.marker([0, 0], {
33       icon: L.icon({
34         iconUrl: iconUrl,
35         iconSize: [25, 41],
36         iconAnchor: [12, 41],
37         popupAnchor: [1, -34],
38         shadowUrl: <%= asset_path('images/marker-shadow.png').to_json %>,
39         shadowSize: [41, 41]
40       }),
41       draggable: true
42     });
43
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)) {
50         getRoute();
51       }
52     });
53
54     input.on("change", function (e) {
55       endpoint.awaitingGeocode = true;
56
57       $.getJSON('<%= NOMINATIM_URL %>search?q=' + encodeURIComponent(e.target.value) + '&format=json', function (json) {
58         endpoint.awaitingGeocode = false;
59
60         if (json.length == 0) {
61           alert(I18n.t('javascripts.directions.errors.no_place'));
62           return;
63         }
64
65         input.val(json[0].display_name);
66
67         endpoint.latlng = L.latLng(json[0]);
68         endpoint.marker
69           .setLatLng(endpoint.latlng)
70           .addTo(map);
71
72         if (awaitingGeocode) {
73           awaitingGeocode = false;
74           getRoute();
75         }
76       });
77     });
78
79     endpoint.setLatLng = function (ll) {
80       var precision = OSM.zoomPrecision(map.getZoom());
81       input.val(ll.lat.toFixed(precision) + ", " + ll.lng.toFixed(precision));
82       endpoint.latlng = ll;
83       endpoint.marker
84         .setLatLng(ll)
85         .addTo(map);
86     };
87
88     return endpoint;
89   }
90
91   function formatDistance(m) {
92     if (m < 1000) {
93       return Math.round(m) + "m";
94     } else if (m < 10000) {
95       return (m / 1000.0).toFixed(1) + "km";
96     } else {
97       return Math.round(m / 1000) + "km";
98     }
99   }
100
101   function formatTime(s) {
102     var m = Math.round(s / 60);
103     var h = Math.floor(m / 60);
104     m -= h * 60;
105     return h + ":" + (m < 10 ? '0' : '') + m;
106   }
107
108   function setEngine(id) {
109     engines.forEach(function(engine, i) {
110       if (engine.id == id) {
111         chosenEngine = engine;
112         select.val(i);
113       }
114     });
115   }
116
117   function getRoute() {
118     if (endpoints[0].awaitingGeocode || endpoints[1].awaitingGeocode) {
119       awaitingGeocode = true;
120       return;
121     }
122
123     var o = endpoints[0].latlng,
124         d = endpoints[1].latlng;
125
126     if (!o || !d) return;
127
128     var precision = OSM.zoomPrecision(map.getZoom());
129
130     OSM.router.replace("/directions?" + querystring.stringify({
131       engine: chosenEngine.id,
132       route: o.lat.toFixed(precision) + ',' + o.lng.toFixed(precision) + ';' +
133              d.lat.toFixed(precision) + ',' + d.lng.toFixed(precision)
134     }));
135
136     $(".directions_form .spinner").show();
137     awaitingRoute = true;
138
139     chosenEngine.getRoute([o, d], function (err, route) {
140       awaitingRoute = false;
141
142       $(".directions_form .spinner").hide();
143
144       if (err) {
145         map.removeLayer(polyline);
146
147         if (!dragging) {
148           alert(I18n.t('javascripts.directions.errors.no_route'));
149         }
150
151         return;
152       }
153
154       polyline
155         .setLatLngs(route.line)
156         .addTo(map);
157
158       map.setSidebarOverlaid(false);
159
160       if (!dragging) {
161         map.fitBounds(polyline.getBounds().pad(0.05));
162       }
163
164       var html = '<h2><a class="geolink" href="#">' +
165         '<span class="icon close"></span></a>' + I18n.t('javascripts.directions.directions') +
166         '</h2><p id="routing_summary">' +
167         I18n.t('javascripts.directions.distance') + ': ' + formatDistance(route.distance) + '. ' +
168         I18n.t('javascripts.directions.time') + ': ' + formatTime(route.time) + '.</p>' +
169         '<table id="turnbyturn" />';
170
171       $('#sidebar_content')
172         .html(html);
173
174       // Add each row
175       var cumulative = 0;
176       route.steps.forEach(function (step) {
177         var ll        = step[0],
178           direction   = step[1],
179           instruction = step[2],
180           dist        = step[3],
181           lineseg     = step[4];
182
183         cumulative += dist;
184
185         if (dist < 5) {
186           dist = "";
187         } else if (dist < 200) {
188           dist = Math.round(dist / 10) * 10 + "m";
189         } else if (dist < 1500) {
190           dist = Math.round(dist / 100) * 100 + "m";
191         } else if (dist < 5000) {
192           dist = Math.round(dist / 100) / 10 + "km";
193         } else {
194           dist = Math.round(dist / 1000) + "km";
195         }
196
197         var row = $("<tr class='turn'/>");
198         row.append("<td><div class='direction i" + direction + "'/></td> ");
199         row.append("<td class='instruction'>" + instruction);
200         row.append("<td class='distance'>" + dist);
201
202         row.on('click', function () {
203           popup
204             .setLatLng(ll)
205             .setContent("<p>" + instruction + "</p>")
206             .openOn(map);
207         });
208
209         row.hover(function () {
210           highlight
211             .setLatLngs(lineseg)
212             .addTo(map);
213         }, function () {
214           map.removeLayer(highlight);
215         });
216
217         $('#turnbyturn').append(row);
218       });
219
220       $('#sidebar_content').append('<p id="routing_credit">' +
221         I18n.t('javascripts.directions.instructions.courtesy', {link: chosenEngine.creditline}) +
222         '</p>');
223     });
224   }
225
226   var engines = OSM.Directions.engines;
227
228   engines.sort(function (a, b) {
229     a = I18n.t('javascripts.directions.engines.' + a.id);
230     b = I18n.t('javascripts.directions.engines.' + b.id);
231     return a.localeCompare(b);
232   });
233
234   var select = $('select.routing_engines');
235
236   engines.forEach(function(engine, i) {
237     select.append("<option value='" + i + "'>" + I18n.t('javascripts.directions.engines.' + engine.id) + "</option>");
238   });
239
240   setEngine('osrm_car');
241
242   select.on("change", function (e) {
243     chosenEngine = engines[e.target.selectedIndex];
244     if (map.hasLayer(polyline)) {
245       getRoute();
246     }
247   });
248
249   $(".directions_form").on("submit", function(e) {
250     e.preventDefault();
251     $("header").addClass("closed");
252     getRoute();
253   });
254
255   $(".routing_marker").on('dragstart', function (e) {
256     e.originalEvent.dataTransfer.effectAllowed = 'move';
257     e.originalEvent.dataTransfer.setData('id', this.id);
258     var xo = e.originalEvent.clientX - $(e.target).offset().left;
259     var yo = e.originalEvent.clientY - $(e.target).offset().top;
260     e.originalEvent.dataTransfer.setData('offsetX', e.originalEvent.target.width / 2 - xo);
261     e.originalEvent.dataTransfer.setData('offsetY', e.originalEvent.target.height - yo);
262   });
263
264   var page = {};
265
266   page.pushstate = page.popstate = function() {
267     $(".search_form").hide();
268     $(".directions_form").show();
269
270     $("#map").on('dragend dragover', function (e) {
271       e.preventDefault();
272     });
273
274     $("#map").on('drop', function (e) {
275       e.preventDefault();
276       var oe = e.originalEvent;
277       var id = oe.dataTransfer.getData('id');
278       var pt = L.DomEvent.getMousePosition(oe, map.getContainer());  // co-ordinates of the mouse pointer at present
279       pt.x += Number(oe.dataTransfer.getData('offsetX'));
280       pt.y += Number(oe.dataTransfer.getData('offsetY'));
281       var ll = map.containerPointToLatLng(pt);
282       endpoints[id === 'marker_from' ? 0 : 1].setLatLng(ll);
283       getRoute();
284     });
285
286     var params = querystring.parse(location.search.substring(1)),
287       route = (params.route || '').split(';');
288
289     if (params.engine) {
290       setEngine(params.engine);
291     }
292
293     var o = route[0] && L.latLng(route[0].split(',')),
294         d = route[1] && L.latLng(route[1].split(','));
295
296     if (o) endpoints[0].setLatLng(o);
297     if (d) endpoints[1].setLatLng(d);
298
299     map.setSidebarOverlaid(!o || !d);
300
301     getRoute();
302   };
303
304   page.load = function() {
305     page.pushstate();
306   };
307
308   page.unload = function() {
309     $(".search_form").show();
310     $(".directions_form").hide();
311     $("#map").off('dragend dragover drop');
312
313     map
314       .removeLayer(popup)
315       .removeLayer(polyline)
316       .removeLayer(endpoints[0].marker)
317       .removeLayer(endpoints[1].marker);
318   };
319
320   return page;
321 };
322
323 OSM.Directions.engines = [];
324
325 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
326   if (document.location.protocol == "http:" || supportsHTTPS) {
327     OSM.Directions.engines.push(engine);
328   }
329 };