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