]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/routing.js.erb
Remove some repeated-query funkiness
[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         "Continue on ",                         // 1
19         "Slight right onto ",           // 2
20         "Turn right onto ",                     // 3
21         "Sharp right onto ",            // 4
22         "U-turn along ",                        // 5
23         "Sharp left onto ",                     // 6
24         "Turn left onto ",                      // 7
25         "Slight left onto ",            // 8
26         "(via point) ",                         // 9
27         "Follow ",                                      // 10
28         "At roundabout take ",          // 11
29         "Leave roundabout - ",          // 12
30         "Stay on roundabout - ",        // 13
31         "Start at end of ",                     // 14
32         "Reach destination",            // 15
33         "Go against one-way on ",       // 16
34         "End of one-way on "]           // 17
35
36 var ROUTING_POLYLINE={
37         color: '#03f',
38         opacity: 0.3,
39         weight: 10
40 };
41
42
43 OSM.RoutingEngines={
44         list: []
45         // common functions and constants, e.g. OSRM parser, can go here
46 };
47
48 OSM.Routing=function(map,name,jqSearch) {
49         var r={};
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);
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);
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');
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) {
161                 if (r.route_from && r.route_to) {
162                         r.awaitingRoute=true;
163                         r.chosenEngine.getRoute(isFinal,[r.route_from,r.route_to]);
164                         // then, when the route has been fetched, it'll call the engine's gotRoute function
165                 } else if (r.route_from==false || r.route_to==false) {
166                         // we're waiting for a Nominatim response before we can request a route
167                         r.awaitingGeocode=true;
168                 }
169         };
170
171         // Take an array of Leaflet LatLngs and draw it as a polyline
172         r.setPolyline=function(line) {
173                 if (r.polyline) map.removeLayer(r.polyline);
174                 r.polyline=L.polyline(line, ROUTING_POLYLINE).addTo(r.map);
175                 // r.map.fitBounds(r.polyline.getBounds());
176                 // *** ^^^ we only want to do this for geocode-originated routes
177         };
178
179         // Take directions and write them out
180         // data = { steps: array of [latlng, sprite number, instruction text, distance in metres] }
181         // sprite numbers equate to OSRM's route_instructions turn values
182         // *** translations?
183         r.setItinerary=function(data) {
184                 // Create base table
185                 $("#content").removeClass("overlay-sidebar");
186                 $('#sidebar_content').empty();
187                 var html='<h2><a class="geolink" href="#" onclick="$(~.close_directions~).click();return false;"><span class="icon close"></span></a>Directions</h2>'.replace(/~/g,"'");
188                 html+="<table id='turnbyturn' />";
189                 $('#sidebar_content').html(html);
190                 // Add each row
191                 var cumulative=0;
192                 for (var i=0; i<data.steps.length; i++) {
193                         var step=data.steps[i];
194                         // Distance
195                         var dist=step[3];
196                         if (dist<5) { dist=""; }
197                         else if (dist<200) { dist=Math.round(dist/10)*10+"m"; }
198                         else if (dist<1500) { dist=Math.round(dist/100)*100+"m"; }
199                         else if (dist<5000) { dist=Math.round(dist/100)/10+"km"; }
200                         else { dist=Math.round(dist/1000)+"km"; }
201                         // Add to table
202                         var row=$("<tr class='turn'/>");
203                         row.append("<td class='direction i"+step[1]+"'> ");
204                         row.append("<td class='instruction'>"+step[2]);
205                         row.append("<td class='distance'>"+dist);
206                         with ({ num: i, ll: step[0] }) {
207                                 row.on('click',function(e) { r.clickTurn(num, ll); });
208                         };
209                         $('#turnbyturn').append(row);
210                         cumulative+=step[3];
211                 }
212         };
213         r.clickTurn=function(num,latlng) {
214                 r.popup=L.popup().setLatLng(latlng).setContent("<p>"+(num+1)+"</p>").openOn(r.map);
215         };
216
217         // Close all routing UI
218         
219         r.close=function() {
220                 $("#content").addClass("overlay-sidebar");
221                 r.route_from=r.route_to=null;
222                 $(".query_wrapper.routing input").val("");
223                 var remove=['polyline','popup','marker_from','marker_to'];
224                 for (var i=0; i<remove.length; i++) {
225                         if (r[remove[i]]) { map.removeLayer(r[remove[i]]); r[remove[i]]=null; }
226                 }
227         };
228
229         // Routing engine handling
230
231         // Add all engines
232         var list=OSM.RoutingEngines.list;
233         list.sort(function(a,b) { return a.name>b.name; });
234         var select=r.jqSearch.find('select.routing_engines');
235         for (var i=0; i<list.length; i++) {
236                 // Set up JSONP callback
237                 with ({num: i}) {
238                         list[num].requestJSONP=function(url) {
239                                 var script = document.createElement('script');
240                                 script.src = url+r.name+".gotRoute"+num;
241                                 document.body.appendChild(script); 
242                         };
243                         r['gotRoute'+num]=function(data) { r.awaitingRoute=false; list[num].gotRoute(r,data); };
244                 }
245                 select.append("<option value='"+i+"'>"+list[i].name+"</option>");
246         }
247         r.engines=list;
248         r.chosenEngine=list[0]; // default to first engine
249
250         // Choose an engine on dropdown change
251         r.selectEngine=function(e) {
252                 r.chosenEngine=r.engines[e.target.selectedIndex];
253         };
254         // Choose an engine by name
255         r.chooseEngine=function(name) {
256                 for (var i=0; i<r.engines.length; i++) {
257                         if (r.engines[i].name==name) {
258                                 r.chosenEngine=r.engines[i];
259                                 r.jqSearch.find('select.routing_engines').val(i);
260                         }
261                 }
262         };
263
264         return r;
265 };