]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/routing.js.erb
Add distance/time summary
[rails.git] / app / assets / javascripts / routing.js.erb
1 /*
2         osm.org routing interface
3         
4         See also:
5         https://github.com/apmon/openstreetmap-website/tree/routing2
6         https://github.com/apmon/openstreetmap-website/compare/routing2
7         https://github.com/apmon/openstreetmap-website/blob/9755c3ae0a8d0684d43760f91dc864ff42d8477a/app/views/routing/start.js.erb
8
9         *** translation (including all alerts and presentation)
10         *** export GPX
11         *** URL history (or do we consciously not want to support that?)
12         *** add YOURS engine
13 */
14
15 var TURN_INSTRUCTIONS=[]
16
17 var ROUTING_POLYLINE={
18         color: '#03f',
19         opacity: 0.3,
20         weight: 10
21 };
22
23
24 OSM.RoutingEngines={
25         list: []
26         // common functions and constants, e.g. OSRM parser, can go here
27 };
28
29 OSM.Routing=function(map,name,jqSearch) {
30         var r={};
31
32     TURN_INSTRUCTIONS=["",
33         I18n.t('javascripts.directions.instructions.continue_on'),                              // 1
34         I18n.t('javascripts.directions.instructions.slight_right'),             // 2
35         I18n.t('javascripts.directions.instructions.turn_right'),                       // 3
36         I18n.t('javascripts.directions.instructions.sharp_right'),              // 4
37         I18n.t('javascripts.directions.instructions.uturn'),                    // 5
38         I18n.t('javascripts.directions.instructions.sharp_left'),                       // 6
39         I18n.t('javascripts.directions.instructions.turn_left'),                        // 7
40         I18n.t('javascripts.directions.instructions.slight_left'),              // 8
41         I18n.t('javascripts.directions.instructions.via_point'),                                // 9
42         I18n.t('javascripts.directions.instructions.follow'),                                   // 10
43         I18n.t('javascripts.directions.instructions.roundabout'),               // 11
44         I18n.t('javascripts.directions.instructions.leave_roundabout'),         // 12
45         I18n.t('javascripts.directions.instructions.stay_roundabout'),  // 13
46         I18n.t('javascripts.directions.instructions.start'),                    // 14
47         I18n.t('javascripts.directions.instructions.destination'),              // 15
48         I18n.t('javascripts.directions.instructions.against_oneway'),   // 16
49         I18n.t('javascripts.directions.instructions.end_oneway')]               // 17
50
51         r.map=map;                              // Leaflet map
52         r.name=name;                    // global variable name of this instance (needed for JSONP)
53         r.jqSearch=jqSearch;    // JQuery object for search panel
54
55         r.route_from=null;              // null=unset, false=awaiting response, [lat,lon]=geocoded
56         r.route_to=null;                //  |
57         r.awaitingGeocode=false;// true if the user has requested a route, but we're waiting on a geocode result
58         r.awaitingRoute=false;  // true if we've asked the engine for a route and are waiting to hear back
59         r.dragging=false;               // true if the user is dragging a start/end point
60         r.viaPoints=[];                 // not yet used
61
62         r.polyline=null;                // Leaflet polyline object
63         r.popup=null;                   // Leaflet popup object
64         r.marker_from=null;             // Leaflet from marker
65         r.marker_to=null;               // Leaflet to marker
66
67         r.chosenEngine=null;    // currently selected routing engine
68
69         var icon_from = L.icon({
70                 iconUrl: <%= asset_path('marker-green.png').to_json %>,
71                 iconSize: [25, 41],
72                 iconAnchor: [12, 41],
73                 popupAnchor: [1, -34],
74                 shadowUrl: <%= asset_path('images/marker-shadow.png').to_json %>,
75                 shadowSize: [41, 41]
76         });
77         var icon_to = L.icon({
78                 iconUrl: <%= asset_path('marker-red.png').to_json %>,
79                 iconSize: [25, 41],
80                 iconAnchor: [12, 41],
81                 popupAnchor: [1, -34],
82                 shadowUrl: <%= asset_path('images/marker-shadow.png').to_json %>,
83                 shadowSize: [41, 41]
84         });
85
86         // Geocoding
87
88         r.geocode=function(id,event) { var _this=this;
89                 var field=event.target;
90                 var v=event.target.value;
91                 // *** do something if v==''
92                 var querystring = '<%= NOMINATIM_URL %>search?q=' + encodeURIComponent(v) + '&format=json';
93                 // *** &accept-language=<%#= request.user_preferred_languages.join(',') %>
94                 // *** prefer current viewport
95                 r[field.id]=false;
96                 $.getJSON(querystring, function(json) { _this._gotGeocode(json,field); });
97         };
98         
99         r._gotGeocode=function(json,field) {
100                 if (json.length==0) {
101                         alert(I18n.t('javascripts.directions.errors.no_place'));
102                         r[field.id]=null;
103                         return;
104                 }
105                 field.value=json[0].display_name;
106                 var lat=Number(json[0].lat), lon=Number(json[0].lon);
107                 r[field.id]=[lat,lon];
108                 r.updateMarker(field.id);
109                 if (r.awaitingGeocode) {
110                         r.awaitingGeocode=false;
111                         r.requestRoute(true, true);
112                 }
113         };
114
115         // Drag and drop markers
116         
117         r.handleDrop=function(e) {
118                 var oe=e.originalEvent;
119                 var id=oe.dataTransfer.getData('id');
120                 var pt=L.DomEvent.getMousePosition(oe,map.getContainer());      // co-ordinates of the mouse pointer at present
121                 pt.x+=Number(oe.dataTransfer.getData('offsetX'));
122                 pt.y+=Number(oe.dataTransfer.getData('offsetY'));
123                 var ll=map.containerPointToLatLng(pt);
124                 r.createMarker(ll,id);
125                 r.setNumericInput(ll,id);
126                 r.requestRoute(true, false);
127                 // update to/from field
128         };
129         r.createMarker=function(latlng,id) {
130                 if (r[id]) r.map.removeLayer(r[id]);
131                 r[id]=L.marker(latlng, {
132                         icon: id=='marker_from' ? icon_from : icon_to,
133                         draggable: true,
134                         name: id
135                 }).addTo(r.map);
136                 r[id].on('drag',r.markerDragged);
137                 r[id].on('dragend',r.markerDragged);
138         };
139         // Update marker from geocoded route input
140         r.updateMarker=function(id) {
141                 var m=id.replace('route','marker');
142                 if (!r[m]) { r.createMarker(r[id],m); return; }
143                 var ll=r[m].getLatLng();
144                 if (ll.lat!=r[id][0] || ll.lng!=r[id][1]) {
145                         r.createMarker(r[id],m);
146                 }
147         };
148         // Marker has been dragged
149         r.markerDragged=function(e) {
150                 r.dragging=(e.type=='drag');    // true for drag, false for dragend
151                 if (r.dragging && !r.chosenEngine.draggable) return;
152                 if (r.dragging && r.awaitingRoute) return;
153                 r.setNumericInput(e.target.getLatLng(), e.target.options.name);
154                 r.requestRoute(!r.dragging, false);
155         };
156         // Set a route input field to a numeric value
157         r.setNumericInput=function(ll,id) {
158                 var routeid=id.replace('marker','route');
159                 r[routeid]=[ll.lat,ll.lng];
160                 $("[name="+routeid+"]:visible").val(Math.round(ll.lat*10000)/10000+" "+Math.round(ll.lng*10000)/10000);
161         }
162         
163         // Route-fetching UI
164
165         r.requestRoute=function(isFinal, updateZoom) {
166                 if (r.route_from && r.route_to) {
167                         $(".query_wrapper.routing .spinner").show();
168                         r.awaitingRoute=true;
169                         r.chosenEngine.getRoute(isFinal,[r.route_from,r.route_to]);
170                         if(updateZoom){
171                                 r.map.fitBounds(L.latLngBounds([r.route_from, r.route_to]).pad(0.05));
172                         }
173                         // then, when the route has been fetched, it'll call the engine's gotRoute function
174                 } else if (r.route_from==false || r.route_to==false) {
175                         // we're waiting for a Nominatim response before we can request a route
176                         r.awaitingGeocode=true;
177                 }
178         };
179
180         // Take an array of Leaflet LatLngs and draw it as a polyline
181         r.setPolyline=function(line) {
182                 if (r.polyline) map.removeLayer(r.polyline);
183                 r.polyline=L.polyline(line, ROUTING_POLYLINE).addTo(r.map);
184                 // r.map.fitBounds(r.polyline.getBounds());
185                 // *** ^^^ we only want to do this for geocode-originated routes
186         };
187
188         // Take directions and write them out
189         // data = { steps: array of [latlng, sprite number, instruction text, distance in metres] }
190         // sprite numbers equate to OSRM's route_instructions turn values
191         r.setItinerary=function(data) {
192                 // Create base table
193                 $("#content").removeClass("overlay-sidebar");
194                 $('#sidebar_content').empty();
195                 var html=('<h2><a class="geolink" href="#" onclick="$(~.close_directions~).click();return false;">' +
196                           '<span class="icon close"></span></a>' + I18n.t('javascripts.directions.directions') + 
197                           '</h2><p id="routing_summary">' + 
198                           I18n.t('javascripts.directions.distance') + ': ' + r.formatDistance(data.distance)+ '. ' +
199                           I18n.t('javascripts.directions.time'    ) + ': ' + r.formatTime(data.time) + '.</p>' +
200                           '<table id="turnbyturn" />').replace(/~/g,"'");
201                 $('#sidebar_content').html(html);
202                 // Add each row
203                 var cumulative=0;
204                 for (var i=0; i<data.steps.length; i++) {
205                         var step=data.steps[i];
206                         // Distance
207                         var dist=step[3];
208                         if (dist<5) { dist=""; }
209                         else if (dist<200) { dist=Math.round(dist/10)*10+"m"; }
210                         else if (dist<1500) { dist=Math.round(dist/100)*100+"m"; }
211                         else if (dist<5000) { dist=Math.round(dist/100)/10+"km"; }
212                         else { dist=Math.round(dist/1000)+"km"; }
213                         // Add to table
214                         var row=$("<tr class='turn'/>");
215                         row.append("<td class='direction i"+step[1]+"'> ");
216                         row.append("<td class='instruction'>"+step[2]);
217                         row.append("<td class='distance'>"+dist);
218                         with ({ num: i, ll: step[0] }) {
219                                 row.on('click',function(e) { r.clickTurn(num, ll); });
220                         };
221                         $('#turnbyturn').append(row);
222                         cumulative+=step[3];
223                 }
224                 $('#sidebar_content').append('<p id="routing_credit">' + r.chosenEngine.creditline + '</p>');
225
226         };
227         r.clickTurn=function(num,latlng) {
228                 r.popup=L.popup().setLatLng(latlng).setContent("<p>"+(num+1)+"</p>").openOn(r.map);
229         };
230         r.formatDistance=function(m) {
231                 if      (m < 1000 ) { return Math.round(m) + "m"; }
232                 else if (m < 10000) { return (m/1000.0).toFixed(1) + "km"; }
233                 else                { return Math.round(m / 1000)  + "km"; }
234         };
235         r.formatTime=function(s) {
236                 var d=new Date(s*1000); var h=d.getHours(); var m=d.getMinutes();
237                 return h+":"+(m<10 ? '0' : '')+m;
238         };
239
240         // Close all routing UI
241         
242         r.close=function() {
243                 $("#content").addClass("overlay-sidebar");
244                 r.route_from=r.route_to=null;
245                 $(".query_wrapper.routing input").val("");
246                 var remove=['polyline','popup','marker_from','marker_to'];
247                 for (var i=0; i<remove.length; i++) {
248                         if (r[remove[i]]) { map.removeLayer(r[remove[i]]); r[remove[i]]=null; }
249                 }
250         };
251
252         // Routing engine handling
253
254         // Add all engines
255         var list=OSM.RoutingEngines.list;
256         list.sort(function(a,b) { return I18n.t(a.name)>I18n.t(b.name); });
257         var select=r.jqSearch.find('select.routing_engines');
258         for (var i=0; i<list.length; i++) {
259                 // Set up JSONP callback
260                 with ({num: i}) {
261                         list[num].requestJSONP=function(url) {
262                                 var script = document.createElement('script');
263                                 script.src = url+r.name+".gotRoute"+num;
264                                 document.body.appendChild(script); 
265                         };
266                         list[num].requestCORS=function(url) {
267                                 $.ajax({ url: url, method: "GET", data: {}, dataType: 'json', success: r['gotRoute'+num] });
268                         };
269                         r['gotRoute'+num]=function(data) { 
270                                 r.awaitingRoute=false;
271                                 $(".query_wrapper.routing .spinner").hide();
272                                 if (!list[num].gotRoute(r,data)) {
273                                         // No route found
274                                         if (r.polyline) {
275                                                 map.removeLayer(r.polyline);
276                                                 r.polyline=null;
277                                         }
278                                         if (!r.dragging) { alert(I18n.t('javascripts.directions.errors.no_route')); }
279                                 }
280                         };
281                 }
282                 select.append("<option value='"+i+"'>"+I18n.t(list[i].name)+"</option>");
283         }
284         r.engines=list;
285         r.chosenEngine=list[0]; // default to first engine
286
287         // Choose an engine on dropdown change
288         r.selectEngine=function(e) {
289                 r.chosenEngine=r.engines[e.target.selectedIndex];
290                 if (r.polyline){ // and if a route is currently showing, must also refresh, else confusion
291                         r.requestRoute(true, false);
292                 }
293         };
294         // Choose an engine by name
295         r.chooseEngine=function(name) {
296                 for (var i=0; i<r.engines.length; i++) {
297                         if (r.engines[i].name==name) {
298                                 r.chosenEngine=r.engines[i];
299                                 r.jqSearch.find('select.routing_engines').val(i);
300                         }
301                 }
302         };
303
304         return r;
305 };