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