]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/routing.js.erb
0c11f93a06af0ba8546dc0a84e7b962f3149f86b
[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         *** draggable start/end markers
10         *** translation (including all alerts and presentation)
11         *** export GPX
12         *** URL history (or do we consciously not want to support that?)
13
14         *** add YOURS engine
15         *** add GraphHopper engine
16 */
17
18 var TURN_INSTRUCTIONS=["",
19         "Continue on ",                         // 1
20         "Slight right onto ",           // 2
21         "Turn right onto ",                     // 3
22         "Sharp right onto ",            // 4
23         "U-turn along ",                        // 5
24         "Sharp left onto ",                     // 6
25         "Turn left onto ",                      // 7
26         "Slight left onto ",            // 8
27         "(via point) ",                         // 9
28         "Follow ",                                      // 10
29         "At roundabout take ",          // 11
30         "Leave roundabout - ",          // 12
31         "Stay on roundabout - ",        // 13
32         "Start at end of ",                     // 14
33         "Reach destination",            // 15
34         "Go against one-way on ",       // 16
35         "End of one-way on "]           // 17
36
37 var ROUTING_POLYLINE={
38         color: '#03f',
39         opacity: 0.3,
40         weight: 10
41 };
42
43
44 OSM.RoutingEngines={
45         list: []
46         // common functions and constants, e.g. OSRM parser, can go here
47 };
48
49 OSM.Routing=function(map,name,jqSearch) {
50         var r={};
51
52         r.map=map;                              // Leaflet map
53         r.name=name;                    // global variable name of this instance (needed for JSONP)
54         r.jqSearch=jqSearch;    // JQuery object for search panel
55
56         r.route_from=null;              // null=unset, false=awaiting response, [lat,lon]=geocoded
57         r.route_to=null;                //  |
58         r.awaitingGeocode=false;// true if the user has requested a route, but we're waiting on a geocode result
59         r.awaitingRoute=false;  // true if we've asked the engine for a route and are waiting to hear back
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("Sorry, couldn't find that place.");      // *** internationalise
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.updateMarkers(field.id);
109                 if (r.awaitingGeocode) {
110                         r.awaitingGeocode=false;
111                         r.requestRoute(true);
112                 }
113         };
114
115         // Drag and drop markers
116         
117         r.handleDrop=function(e) {
118                 var id=e.originalEvent.dataTransfer.getData('id');
119                 var ll=r.map.mouseEventToLatLng(e.originalEvent);
120                 // *** ^^^ this is slightly off - we need to work out the latLng of the tip
121                 r.createMarker(ll,id);
122                 r[id.replace('marker','route')]=[ll.lat,ll.lng];
123                 r.requestRoute(true);
124                 // update to/from field
125         };
126         r.createMarker=function(latlng,id) {
127                 if (r[id]) r.map.removeLayer(r[id]);
128                 r[id]=L.marker(latlng, {
129                         icon: id=='marker_from' ? icon_from : icon_to,
130                         draggable: true,
131                         name: id
132                 }).addTo(r.map);
133                 r[id].on('drag',r.markerDragged);
134                 r[id].on('dragend',r.markerDragged);
135         };
136         r.updateMarkers=function(id) {
137         };
138         r.markerDragged=function(e) {
139                 // marker has been dragged
140                 if (e.type=='drag' && !r.chosenEngine.draggable) return;
141                 if (e.type=='drag' && r.awaitingRoute) return;
142                 var id=e.target.options.name;
143                 var ll=e.target.getLatLng();
144                 r[id.replace('marker','route')]=[ll.lat,ll.lng];
145                 r.requestRoute(e.type=='dragend');
146                 // update to/from field
147         };
148         
149         // Route-fetching UI
150
151         r.requestRoute=function(final) {
152                 if (r.route_from && r.route_to) {
153                         r.awaitingRoute=true;
154                         r.chosenEngine.getRoute(final,[r.route_from,r.route_to]);
155                         // then, when the route has been fetched, it'll call the engine's gotRoute function
156                 } else if (r.route_from==false || r.route_to==false) {
157                         // we're waiting for a Nominatim response before we can request a route
158                         r.awaitingGeocode=true;
159                 }
160         };
161
162         // Take an array of Leaflet LatLngs and draw it as a polyline
163         r.setPolyline=function(line) {
164                 if (r.polyline) map.removeLayer(r.polyline);
165                 r.polyline=L.polyline(line, ROUTING_POLYLINE).addTo(r.map);
166                 // r.map.fitBounds(r.polyline.getBounds());
167                 // *** ^^^ we only want to do this for geocode-originated routes
168         };
169
170         // Take directions and write them out
171         // data = { steps: array of [latlng, sprite number, instruction text, distance in metres] }
172         // sprite numbers equate to OSRM's route_instructions turn values
173         // *** translations?
174         r.setItinerary=function(data) {
175                 // Create base table
176                 $("#content").removeClass("overlay-sidebar");
177                 $('#sidebar_content').empty();
178                 var html='<h2><a class="geolink" href="#" onclick="$(~.close_directions~).click();return false;"><span class="icon close"></span></a>Directions</h2>'.replace(/~/g,"'");
179                 html+="<table id='turnbyturn' />";
180                 $('#sidebar_content').html(html);
181                 // Add each row
182                 var cumulative=0;
183                 for (var i=0; i<data.steps.length; i++) {
184                         var step=data.steps[i];
185                         // Distance
186                         var dist=step[3];
187                         if (dist<5) { dist=""; }
188                         else if (dist<200) { dist=Math.round(dist/10)*10+"m"; }
189                         else if (dist<1500) { dist=Math.round(dist/100)*100+"m"; }
190                         else if (dist<5000) { dist=Math.round(dist/100)/10+"km"; }
191                         else { dist=Math.round(dist/1000)+"km"; }
192                         // Add to table
193                         var row=$("<tr class='turn'/>");
194                         row.append("<td class='direction i"+step[1]+"'> ");
195                         row.append("<td class='instruction'>"+step[2]);
196                         row.append("<td class='distance'>"+dist);
197                         with ({ num: i, ll: step[0] }) {
198                                 row.on('click',function(e) { r.clickTurn(num, ll); });
199                         };
200                         $('#turnbyturn').append(row);
201                         cumulative+=step[3];
202                 }
203         };
204         r.clickTurn=function(num,latlng) {
205                 r.popup=L.popup().setLatLng(latlng).setContent("<p>"+(num+1)+"</p>").openOn(r.map);
206         };
207
208         // Close all routing UI
209         
210         r.close=function() {
211                 $("#content").addClass("overlay-sidebar");
212                 var remove=[r.polyline,r.popup,r.marker_from,r.marker_to];
213                 for (var i=0; i<remove.length; i++) {
214                         if (remove[i]) map.removeLayer(remove[i]);
215                 }
216         };
217
218         // Routing engine handling
219
220         // Add all engines
221         var list=OSM.RoutingEngines.list;
222         list.sort(function(a,b) { return a.name>b.name; });
223         var select=r.jqSearch.find('select.routing_engines');
224         for (var i=0; i<list.length; i++) {
225                 // Set up JSONP callback
226                 with ({num: i}) {
227                         list[num].requestJSONP=function(url) {
228                                 var script = document.createElement('script');
229                                 script.src = url+r.name+".gotRoute"+num;
230                                 document.body.appendChild(script); 
231                         };
232                         r['gotRoute'+num]=function(data) { r.awaitingRoute=false; list[num].gotRoute(r,data); };
233                 }
234                 select.append("<option value='"+i+"'>"+list[i].name+"</option>");
235         }
236         r.engines=list;
237         r.chosenEngine=list[0]; // default to first engine
238
239         // Choose an engine on dropdown change
240         r.selectEngine=function(e) {
241                 r.chosenEngine=r.engines[e.target.selectedIndex];
242         };
243         // Choose an engine by name
244         r.chooseEngine=function(name) {
245                 for (var i=0; i<r.engines.length; i++) {
246                         if (r.engines[i].name==name) {
247                                 r.chosenEngine=r.engines[i];
248                                 r.jqSearch.find('select.routing_engines').val(i);
249                         }
250                 }
251         };
252
253         return r;
254 };