]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/routing.js.erb
Start MapQuest Open support
[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 an array of directions and write it out
103         // (we use OSRM's route_instructions format)
104         // *** translations?
105         r.setItinerary=function(steps) {
106                 // Create base table
107                 $("#content").removeClass("overlay-sidebar");
108                 $('#sidebar_content').empty();
109                 var html='<h2><a class="geolink" href="#" onclick="$(~.close_directions~).click();return false;"><span class="icon close"></span></a>Directions</h2>'.replace(/~/g,"'");
110                 html+="<table id='turnbyturn' />";
111                 $('#sidebar_content').html(html);
112                 // Add each row
113                 var cumulative=0;
114                 for (var i=0; i<steps.length; i++) {
115                         var step=steps[i];
116                         var instCodes=step[0].split('-');
117                         // Assemble instruction text
118                         var instText="<b>"+(i+1)+".</b> ";
119                         instText+=TURN_INSTRUCTIONS[instCodes[0]];
120                         if (instCodes[1]) { instText+="exit "+instCodes[1]+" "; }
121                         if (instCodes[0]!=15) { instText+=step[1] ? "<b>"+step[1]+"</b>" : "(unnamed)"; }
122                         // Distance
123                         var dist=step[2];
124                         if (dist<5) { dist=""; }
125                         else if (dist<200) { dist=Math.round(dist/10)*10+"m"; }
126                         else if (dist<1500) { dist=Math.round(dist/100)*100+"m"; }
127                         else if (dist<5000) { dist=Math.round(dist/100)/10+"km"; }
128                         else { dist=Math.round(dist/1000)+"km"; }
129                         // Add to table
130                         var row=$("<tr class='turn'/>");
131                         row.append("<td class='direction i"+instCodes[0]+"'> ");
132                         row.append("<td class='instruction'>"+instText);
133                         row.append("<td class='distance'>"+dist);
134                         with ({num: i, dist: step[3]}) {
135                                 row.on('click',function(e) { 
136                                         r.clickTurn(num, r.polyline.getLatLngs()[dist]);
137                                 });
138                         };
139                         $('#turnbyturn').append(row);
140                         cumulative+=step[2];
141                 }
142         };
143         r.clickTurn=function(num,latlng) {
144                 L.popup().setLatLng(latlng).setContent("<p>"+(num+1)+"</p>").openOn(r.map);
145         };
146
147
148         // Close all routing UI
149         
150         r.close=function() {
151                 $("#content").addClass("overlay-sidebar");
152                 if (r.polyline) map.removeLayer(r.polyline);
153         };
154
155         // Routing engine handling
156
157         // Add all engines
158         var list=OSM.RoutingEngines.list;
159         list.sort(function(a,b) { return a.name>b.name; });
160         var select=r.jqSearch.find('select.routing_engines');
161         for (var i=0; i<list.length; i++) {
162                 // Set up JSONP callback
163                 with ({num: i}) {
164                         list[num].requestJSONP=function(url) {
165                                 var script = document.createElement('script');
166                                 script.src = url+r.name+".gotRoute"+num;
167                                 document.body.appendChild(script); 
168                         };
169                         r['gotRoute'+num]=function(data) { list[num].gotRoute(r,data); };
170                 }
171                 select.append("<option value='"+i+"'>"+list[i].name+"</option>");
172         }
173         r.engines=list;
174         r.chosenEngine=list[0]; // default to first engine
175
176         // Choose an engine on dropdown change
177         r.selectEngine=function(e) {
178                 r.chosenEngine=r.engines[e.target.selectedIndex];
179         };
180         // Choose an engine by name
181         r.chooseEngine=function(name) {
182                 for (var i=0; i<r.engines.length; i++) {
183                         if (r.engines[i].name==name) {
184                                 r.chosenEngine=r.engines[i];
185                                 r.jqSearch.find('select.routing_engines').val(i);
186                         }
187                 }
188         };
189
190         return r;
191 };