]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/routing.js.erb
45ae08d81cd7dbe8accf86f0d90397ff386252e0
[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.viaPoints=[];                 // not yet used
60         r.polyline=null;                // Leaflet polyline object
61         r.chosenEngine=null;    // currently selected routing engine
62
63         // Geocoding
64
65         r.geocode=function(id,event) { var _this=this;
66                 var field=event.target;
67                 var v=event.target.value;
68                 // *** do something if v==''
69                 var querystring = '<%= NOMINATIM_URL %>search?q=' + encodeURIComponent(v) + '&format=json';
70                 // *** &accept-language=<%#= request.user_preferred_languages.join(',') %>
71                 // *** prefer current viewport
72                 r[field.id]=false;
73                 $.getJSON(querystring, function(json) { _this._gotGeocode(json,field); });
74         };
75         
76         r._gotGeocode=function(json,field) {
77                 if (json.length==0) {
78                         alert("Sorry, couldn't find that place.");      // *** internationalise
79                         r[field.id]=null;
80                         return;
81                 }
82                 field.value=json[0].display_name;
83                 var lat=Number(json[0].lat), lon=Number(json[0].lon);
84                 r[field.id]=[lat,lon];
85                 // ** update markers
86                 if (r.awaitingGeocode) {
87                         r.awaitingGeocode=false;
88                         r.requestRoute();
89                 }
90         };
91
92         // Drag and drop markers
93         
94         r.handleDrop=function(e) {
95                 console.log(r.map.mouseEventToLatLng(e.originalEvent))
96         };
97         
98         // Route-fetching UI
99
100         r.requestRoute=function() {
101                 if (r.route_from && r.route_to) {
102                         r.chosenEngine.getRoute(true,[r.route_from,r.route_to]);
103                         // then, when the route has been fetched, it'll call the engine's gotRoute function
104                 } else if (r.route_from==false || r.route_to==false) {
105                         // we're waiting for a Nominatim response before we can request a route
106                         r.awaitingGeocode=true;
107                 }
108         };
109
110         // Take an array of Leaflet LatLngs and draw it as a polyline
111         r.setPolyline=function(line) {
112                 if (r.polyline) map.removeLayer(r.polyline);
113                 r.polyline=L.polyline(line, ROUTING_POLYLINE).addTo(r.map);
114                 r.map.fitBounds(r.polyline.getBounds());
115         };
116
117         // Take directions and write them out
118         // data = { steps: array of [latlng, sprite number, instruction text, distance in metres] }
119         // sprite numbers equate to OSRM's route_instructions turn values
120         // *** translations?
121         r.setItinerary=function(data) {
122                 // Create base table
123                 $("#content").removeClass("overlay-sidebar");
124                 $('#sidebar_content').empty();
125                 var html='<h2><a class="geolink" href="#" onclick="$(~.close_directions~).click();return false;"><span class="icon close"></span></a>Directions</h2>'.replace(/~/g,"'");
126                 html+="<table id='turnbyturn' />";
127                 $('#sidebar_content').html(html);
128                 // Add each row
129                 var cumulative=0;
130                 for (var i=0; i<data.steps.length; i++) {
131                         var step=data.steps[i];
132                         // Distance
133                         var dist=step[3];
134                         if (dist<5) { dist=""; }
135                         else if (dist<200) { dist=Math.round(dist/10)*10+"m"; }
136                         else if (dist<1500) { dist=Math.round(dist/100)*100+"m"; }
137                         else if (dist<5000) { dist=Math.round(dist/100)/10+"km"; }
138                         else { dist=Math.round(dist/1000)+"km"; }
139                         // Add to table
140                         var row=$("<tr class='turn'/>");
141                         row.append("<td class='direction i"+step[1]+"'> ");
142                         row.append("<td class='instruction'>"+step[2]);
143                         row.append("<td class='distance'>"+dist);
144                         with ({ num: i, ll: step[0] }) {
145                                 row.on('click',function(e) { r.clickTurn(num, ll); });
146                         };
147                         $('#turnbyturn').append(row);
148                         cumulative+=step[3];
149                 }
150         };
151         r.clickTurn=function(num,latlng) {
152                 L.popup().setLatLng(latlng).setContent("<p>"+(num+1)+"</p>").openOn(r.map);
153         };
154
155
156         // Close all routing UI
157         
158         r.close=function() {
159                 $("#content").addClass("overlay-sidebar");
160                 if (r.polyline) map.removeLayer(r.polyline);
161         };
162
163         // Routing engine handling
164
165         // Add all engines
166         var list=OSM.RoutingEngines.list;
167         list.sort(function(a,b) { return a.name>b.name; });
168         var select=r.jqSearch.find('select.routing_engines');
169         for (var i=0; i<list.length; i++) {
170                 // Set up JSONP callback
171                 with ({num: i}) {
172                         list[num].requestJSONP=function(url) {
173                                 var script = document.createElement('script');
174                                 script.src = url+r.name+".gotRoute"+num;
175                                 document.body.appendChild(script); 
176                         };
177                         r['gotRoute'+num]=function(data) { list[num].gotRoute(r,data); };
178                 }
179                 select.append("<option value='"+i+"'>"+list[i].name+"</option>");
180         }
181         r.engines=list;
182         r.chosenEngine=list[0]; // default to first engine
183
184         // Choose an engine on dropdown change
185         r.selectEngine=function(e) {
186                 r.chosenEngine=r.engines[e.target.selectedIndex];
187         };
188         // Choose an engine by name
189         r.chooseEngine=function(name) {
190                 for (var i=0; i<r.engines.length; i++) {
191                         if (r.engines[i].name==name) {
192                                 r.chosenEngine=r.engines[i];
193                                 r.jqSearch.find('select.routing_engines').val(i);
194                         }
195                 }
196         };
197
198         return r;
199 };