]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/routing.js.erb
f496262d2aac30aab377ecdcf8a5d8e0b8085f15
[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         *** click each part
11         *** translation (including all alerts and presentation)
12         *** export GPX
13         *** URL history (or do we consciously not want to support that?)
14 */
15
16 var TURN_INSTRUCTIONS=["",
17         "Continue on ",                         // 1
18         "Slight right onto ",           // 2
19         "Turn right onto ",                     // 3
20         "Sharp right onto ",            // 4
21         "U-turn along ",                        // 5
22         "Sharp left onto ",                     // 6
23         "Turn left onto ",                      // 7
24         "Slight left onto ",            // 8
25         "(via point) ",                         // 9
26         "Follow ",                                      // 10
27         "At roundabout take ",          // 11
28         "Leave roundabout - ",          // 12
29         "Stay on roundabout - ",        // 13
30         "Start at end of ",                     // 14
31         "Reach destination",            // 15
32         "Go against one-way on ",       // 16
33         "End of one-way on "]           // 17
34
35 var ROUTING_POLYLINE={
36         color: '#03f',
37         opacity: 0.3,
38         weight: 10
39 };
40
41
42 OSM.Routing=function(map,name,jqSearch) {
43         var r={};
44         r.map=map;                              // Leaflet map
45         r.name=name;                    // global variable name of this instance (needed for JSONP)
46         r.jqSearch=jqSearch;    // JQuery object for search panel
47
48         r.route_from=null;
49         r.route_to=null;
50         r.viaPoints=[];
51         r.polyline=null;
52
53         // Geocoding
54
55         r.geocode=function(id,event) { var _this=this;
56                 var field=event.target;
57                 var v=event.target.value;
58                 // *** do something if v==''
59                 var querystring = '<%= NOMINATIM_URL %>search?q=' + encodeURIComponent(v) + '&format=json';
60                 // *** &accept-language=<%#= request.user_preferred_languages.join(',') %>
61                 // *** prefer current viewport
62                 $.getJSON(querystring, function(json) { _this._gotGeocode(json,field); });
63         };
64         
65         r._gotGeocode=function(json,field) {
66                 if (json.length==0) {
67                         alert("Sorry, couldn't find that place.");      // *** internationalise
68                         r[field.id]=null;
69                         return;
70                 }
71                 field.value=json[0].display_name;
72                 var lat=Number(json[0].lat), lon=Number(json[0].lon);
73                 r[field.id]=[lat,lon];
74                 // ** update markers
75         };
76         
77         // Route-fetching UI
78
79         r.requestRoute=function() {
80                 if (r.route_from && r.route_to) {
81                         var chosen=jqSearch.find('select.routing_engines :selected').val();
82                         r.engines[chosen].getRoute(true,[r.route_from,r.route_to]);
83                         // then, when the route has been fetched, it'll call the engine's gotRoute function
84                 }
85         };
86
87         // Take an array of Leaflet LatLngs and draw it as a polyline
88         r.setPolyline=function(line) {
89                 if (r.polyline) map.removeLayer(r.polyline);
90                 r.polyline=L.polyline(line, ROUTING_POLYLINE).addTo(r.map);
91                 r.map.fitBounds(r.polyline.getBounds());
92         };
93
94         // Take an array of directions and write it out
95         // (we use OSRM's route_instructions format)
96         // *** translations?
97         r.setItinerary=function(steps) {
98                 // Create base table
99                 $("#content").removeClass("overlay-sidebar");
100                 $('#sidebar_content').empty();
101                 var html='<h2><a class="geolink" href="#" onclick="$(~.close_directions~).click();return false;"><span class="icon close"></span></a>Directions</h2>'.replace(/~/g,"'");
102                 html+="<table id='turnbyturn' />";
103         $('#sidebar_content').html(html);
104                 // Add each row
105                 for (var i=0; i<steps.length; i++) {
106                         var step=steps[i];
107                         var instCodes=step[0].split('-');
108                         // Assemble instruction text
109                         var instText="<b>"+(i+1)+".</b> ";
110                         instText+=TURN_INSTRUCTIONS[instCodes[0]];
111                         if (instCodes[1]) { instText+="exit "+instCodes[1]+" "; }
112                         if (instCodes[0]!=15) { instText+=step[1] ? "<b>"+step[1]+"</b>" : "(unnamed)"; }
113                         // Distance
114                         var dist=step[2];
115                         if (dist<5) { dist=""; }
116                         else if (dist<200) { dist=Math.round(dist/10)*10+"m"; }
117                         else if (dist<1500) { dist=Math.round(dist/100)*100+"m"; }
118                         else if (dist<5000) { dist=Math.round(dist/100)/10+"km"; }
119                         else { dist=Math.round(dist/1000)+"km"; }
120                         // Add to table
121                         var row=$("<tr class='turn'/>");
122                         row.append("<td class='direction i"+instCodes[0]+"'> ");
123                         row.append("<td class='instruction'>"+instText);
124                         row.append("<td class='distance'>"+dist);
125                         with ({n: i}) { row.on('click',function(e) { r.clickTurn(n); });
126                         }
127                         $('#turnbyturn').append(row);
128                 }
129         };
130         r.clickTurn=function(num) {
131                 console.log("clicked turn",num);
132         };
133
134
135         // Close all routing UI
136         
137         r.close=function() {
138                 $("#content").addClass("overlay-sidebar");
139                 if (r.polyline) map.removeLayer(r.polyline);
140         };
141
142         // Add engines
143         
144         r.engines=[];
145         r.addEngine=function(engine) {
146                 // Save engine
147                 var i=r.engines.length;
148                 engine.subscript=i;
149                 r['engine'+i]=engine;
150                 r.engines.push(engine);
151
152                 // Add generic JSONP function
153                 engine.requestJSONP=function(url) {
154                         var script = document.createElement('script');
155                         script.src = url+"&jsonp="+r.name+".engine"+this.subscript+".gotRoute";
156                         // OSRM doesn't like non-alphanumeric, otherwise we could just do OSM.routing.engines["+engine.subscript+"].gotRoute
157                         document.body.appendChild(script); 
158                 };
159
160                 // Populate dropdown
161                 var select=jqSearch.find('select.routing_engines');
162                 select.append("<option value='"+i+"'>"+engine.name+"</option>");
163         };
164
165         // OSRM car engine
166         // *** this should all be shared from an OSRM library somewhere
167         // *** need to clear hints at some point
168
169         r.addEngine({
170                 name: 'Car (OSRM)',
171                 draggable: true,
172                 _hints: {},
173                 getRoute: function(final,points) {
174                         var url="http://router.project-osrm.org/viaroute?z=14&output=json";
175                         for (var i=0; i<points.length; i++) {
176                                 var pair=points[i].join(',');
177                                 url+="&loc="+pair;
178                                 if (this._hints[pair]) url+= "&hint="+this._hints[pair];
179                         }
180                         if (final) url+="&instructions=true";
181                         this.requestJSONP(url);
182                 },
183                 gotRoute: function(data) {
184                         if (data.status==207) {
185                                 alert("Couldn't find route between those two places");
186                                 return false;
187                         }
188                         // *** store hints
189                         var line=L.PolylineUtil.decode(data.route_geometry);
190                         for (i=0; i<line.length; i++) { line[i].lat/=10; line[i].lng/=10; }
191                         r.setPolyline(line);
192                         r.setItinerary(data.route_instructions);
193                 }
194         });
195
196         return r;
197 };