Reformat string to avoid long line
[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, 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, false);
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', false);
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, updateZoom) {
163                 if (r.route_from && r.route_to) {
164                         r.awaitingRoute=true;
165                         r.chosenEngine.getRoute(isFinal,[r.route_from,r.route_to]);
166                         if(updateZoom){
167                                 r.map.fitBounds(L.latLngBounds([r.route_from, r.route_to]).pad(0.05));
168                         }
169                         // then, when the route has been fetched, it'll call the engine's gotRoute function
170                 } else if (r.route_from==false || r.route_to==false) {
171                         // we're waiting for a Nominatim response before we can request a route
172                         r.awaitingGeocode=true;
173                 }
174         };
175
176         // Take an array of Leaflet LatLngs and draw it as a polyline
177         r.setPolyline=function(line) {
178                 if (r.polyline) map.removeLayer(r.polyline);
179                 r.polyline=L.polyline(line, ROUTING_POLYLINE).addTo(r.map);
180                 // r.map.fitBounds(r.polyline.getBounds());
181                 // *** ^^^ we only want to do this for geocode-originated routes
182         };
183
184         // Take directions and write them out
185         // data = { steps: array of [latlng, sprite number, instruction text, distance in metres] }
186         // sprite numbers equate to OSRM's route_instructions turn values
187         r.setItinerary=function(data) {
188                 // Create base table
189                 $("#content").removeClass("overlay-sidebar");
190                 $('#sidebar_content').empty();
191                 var html=('<h2><a class="geolink" href="#" onclick="$(~.close_directions~).click();return false;">' +
192                           '<span class="icon close"></span></a>' + I18n.t('javascripts.directions.directions') + 
193                           '</h2><table id="turnbyturn" />').replace(/~/g,"'");
194                 $('#sidebar_content').html(html);
195                 // Add each row
196                 var cumulative=0;
197                 for (var i=0; i<data.steps.length; i++) {
198                         var step=data.steps[i];
199                         // Distance
200                         var dist=step[3];
201                         if (dist<5) { dist=""; }
202                         else if (dist<200) { dist=Math.round(dist/10)*10+"m"; }
203                         else if (dist<1500) { dist=Math.round(dist/100)*100+"m"; }
204                         else if (dist<5000) { dist=Math.round(dist/100)/10+"km"; }
205                         else { dist=Math.round(dist/1000)+"km"; }
206                         // Add to table
207                         var row=$("<tr class='turn'/>");
208                         row.append("<td class='direction i"+step[1]+"'> ");
209                         row.append("<td class='instruction'>"+step[2]);
210                         row.append("<td class='distance'>"+dist);
211                         with ({ num: i, ll: step[0] }) {
212                                 row.on('click',function(e) { r.clickTurn(num, ll); });
213                         };
214                         $('#turnbyturn').append(row);
215                         cumulative+=step[3];
216                 }
217                 $('#sidebar_content').append('<p id="routing_credit">' + r.chosenEngine.creditline + '</p>');
218
219         };
220         r.clickTurn=function(num,latlng) {
221                 r.popup=L.popup().setLatLng(latlng).setContent("<p>"+(num+1)+"</p>").openOn(r.map);
222         };
223
224         // Close all routing UI
225         
226         r.close=function() {
227                 $("#content").addClass("overlay-sidebar");
228                 r.route_from=r.route_to=null;
229                 $(".query_wrapper.routing input").val("");
230                 var remove=['polyline','popup','marker_from','marker_to'];
231                 for (var i=0; i<remove.length; i++) {
232                         if (r[remove[i]]) { map.removeLayer(r[remove[i]]); r[remove[i]]=null; }
233                 }
234         };
235
236         // Routing engine handling
237
238         // Add all engines
239         var list=OSM.RoutingEngines.list;
240         list.sort(function(a,b) { return a.name>b.name; });
241         var select=r.jqSearch.find('select.routing_engines');
242         for (var i=0; i<list.length; i++) {
243                 // Set up JSONP callback
244                 with ({num: i}) {
245                         list[num].requestJSONP=function(url) {
246                                 var script = document.createElement('script');
247                                 script.src = url+r.name+".gotRoute"+num;
248                                 document.body.appendChild(script); 
249                         };
250                         r['gotRoute'+num]=function(data) { r.awaitingRoute=false; list[num].gotRoute(r,data); };
251                 }
252                 select.append("<option value='"+i+"'>"+I18n.t(list[i].name)+"</option>");
253         }
254         r.engines=list;
255         r.chosenEngine=list[0]; // default to first engine
256
257         // Choose an engine on dropdown change
258         r.selectEngine=function(e) {
259                 r.chosenEngine=r.engines[e.target.selectedIndex];
260                 if (r.polyline){ // and if a route is currently showing, must also refresh, else confusion
261                         r.requestRoute(true, false);
262                 }
263         };
264         // Choose an engine by name
265         r.chooseEngine=function(name) {
266                 for (var i=0; i<r.engines.length; i++) {
267                         if (r.engines[i].name==name) {
268                                 r.chosenEngine=r.engines[i];
269                                 r.jqSearch.find('select.routing_engines').val(i);
270                         }
271                 }
272         };
273
274         return r;
275 };