]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/routing.js.erb
Parse MapQuest directions
[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 MapQuest engine
15         *** add YOURS engine
16         *** finish CloudMade engine
17 */
18
19 var TURN_INSTRUCTIONS=["",
20         "Continue on ",                         // 1
21         "Slight right onto ",           // 2
22         "Turn right onto ",                     // 3
23         "Sharp right onto ",            // 4
24         "U-turn along ",                        // 5
25         "Sharp left onto ",                     // 6
26         "Turn left onto ",                      // 7
27         "Slight left onto ",            // 8
28         "(via point) ",                         // 9
29         "Follow ",                                      // 10
30         "At roundabout take ",          // 11
31         "Leave roundabout - ",          // 12
32         "Stay on roundabout - ",        // 13
33         "Start at end of ",                     // 14
34         "Reach destination",            // 15
35         "Go against one-way on ",       // 16
36         "End of one-way on "]           // 17
37
38 var ROUTING_POLYLINE={
39         color: '#03f',
40         opacity: 0.3,
41         weight: 10
42 };
43
44
45 OSM.RoutingEngines={
46         list: []
47         // common functions and constants, e.g. OSRM parser, can go here
48 };
49
50 OSM.Routing=function(map,name,jqSearch) {
51         var r={};
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;
57         r.route_to=null;
58         r.viaPoints=[];
59         r.polyline=null;
60         r.chosenEngine=null;
61
62         // Geocoding
63
64         r.geocode=function(id,event) { var _this=this;
65                 var field=event.target;
66                 var v=event.target.value;
67                 // *** do something if v==''
68                 var querystring = '<%= NOMINATIM_URL %>search?q=' + encodeURIComponent(v) + '&format=json';
69                 // *** &accept-language=<%#= request.user_preferred_languages.join(',') %>
70                 // *** prefer current viewport
71                 $.getJSON(querystring, function(json) { _this._gotGeocode(json,field); });
72         };
73         
74         r._gotGeocode=function(json,field) {
75                 if (json.length==0) {
76                         alert("Sorry, couldn't find that place.");      // *** internationalise
77                         r[field.id]=null;
78                         return;
79                 }
80                 field.value=json[0].display_name;
81                 var lat=Number(json[0].lat), lon=Number(json[0].lon);
82                 r[field.id]=[lat,lon];
83                 // ** update markers
84         };
85         
86         // Route-fetching UI
87
88         r.requestRoute=function() {
89                 if (r.route_from && r.route_to) {
90                         r.chosenEngine.getRoute(true,[r.route_from,r.route_to]);
91                         // then, when the route has been fetched, it'll call the engine's gotRoute function
92                 }
93         };
94
95         // Take an array of Leaflet LatLngs and draw it as a polyline
96         r.setPolyline=function(line) {
97                 if (r.polyline) map.removeLayer(r.polyline);
98                 r.polyline=L.polyline(line, ROUTING_POLYLINE).addTo(r.map);
99                 r.map.fitBounds(r.polyline.getBounds());
100         };
101
102         // Take directions and write them out
103         // data = { steps: array of [latlng, sprite number, instruction text, distance in metres] }
104         // sprite numbers equate to OSRM's route_instructions turn values
105         // *** translations?
106         r.setItinerary=function(data) {
107                 // Create base table
108                 $("#content").removeClass("overlay-sidebar");
109                 $('#sidebar_content').empty();
110                 var html='<h2><a class="geolink" href="#" onclick="$(~.close_directions~).click();return false;"><span class="icon close"></span></a>Directions</h2>'.replace(/~/g,"'");
111                 html+="<table id='turnbyturn' />";
112                 $('#sidebar_content').html(html);
113                 // Add each row
114                 var cumulative=0;
115                 for (var i=0; i<data.steps.length; i++) {
116                         var step=data.steps[i];
117                         // Distance
118                         var dist=step[3];
119                         if (dist<5) { dist=""; }
120                         else if (dist<200) { dist=Math.round(dist/10)*10+"m"; }
121                         else if (dist<1500) { dist=Math.round(dist/100)*100+"m"; }
122                         else if (dist<5000) { dist=Math.round(dist/100)/10+"km"; }
123                         else { dist=Math.round(dist/1000)+"km"; }
124                         // Add to table
125                         var row=$("<tr class='turn'/>");
126                         row.append("<td class='direction i"+step[1]+"'> ");
127                         row.append("<td class='instruction'>"+step[2]);
128                         row.append("<td class='distance'>"+dist);
129                         with ({ num: i, ll: step[0] }) {
130                                 row.on('click',function(e) { r.clickTurn(num, ll); });
131                         };
132                         $('#turnbyturn').append(row);
133                         cumulative+=step[3];
134                 }
135         };
136         r.clickTurn=function(num,latlng) {
137                 L.popup().setLatLng(latlng).setContent("<p>"+(num+1)+"</p>").openOn(r.map);
138         };
139
140
141         // Close all routing UI
142         
143         r.close=function() {
144                 $("#content").addClass("overlay-sidebar");
145                 if (r.polyline) map.removeLayer(r.polyline);
146         };
147
148         // Routing engine handling
149
150         // Add all engines
151         var list=OSM.RoutingEngines.list;
152         list.sort(function(a,b) { return a.name>b.name; });
153         var select=r.jqSearch.find('select.routing_engines');
154         for (var i=0; i<list.length; i++) {
155                 // Set up JSONP callback
156                 with ({num: i}) {
157                         list[num].requestJSONP=function(url) {
158                                 var script = document.createElement('script');
159                                 script.src = url+r.name+".gotRoute"+num;
160                                 document.body.appendChild(script); 
161                         };
162                         r['gotRoute'+num]=function(data) { list[num].gotRoute(r,data); };
163                 }
164                 select.append("<option value='"+i+"'>"+list[i].name+"</option>");
165         }
166         r.engines=list;
167         r.chosenEngine=list[0]; // default to first engine
168
169         // Choose an engine on dropdown change
170         r.selectEngine=function(e) {
171                 r.chosenEngine=r.engines[e.target.selectedIndex];
172         };
173         // Choose an engine by name
174         r.chooseEngine=function(name) {
175                 for (var i=0; i<r.engines.length; i++) {
176                         if (r.engines[i].name==name) {
177                                 r.chosenEngine=r.engines[i];
178                                 r.jqSearch.find('select.routing_engines').val(i);
179                         }
180                 }
181         };
182
183         return r;
184 };