Close 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         *** 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                 $("#content").removeClass("overlay-sidebar");
99                 $('#sidebar_content').empty();
100                 var html='<h2><a class="geolink" href="#" onclick="$(~.close_directions~).click();return false;"><span class="icon close"></span></a>Directions</h2>'.replace(/~/g,"'");
101                 html+="<table>";
102                 for (var i=0; i<steps.length; i++) {
103                         var step=steps[i];
104                         var instCodes=step[0].split('-');
105                         // Assemble instruction text
106                         var instText="<b>"+(i+1)+".</b> ";
107                         instText+=TURN_INSTRUCTIONS[instCodes[0]];
108                         if (instCodes[1]) { instText+="exit "+instCodes[1]+" "; }
109                         if (instCodes[0]!=15) { instText+=step[1] ? "<b>"+step[1]+"</b>" : "(unnamed)"; }
110                         // Distance
111                         var dist=step[2];
112                         if (dist<5) { dist=""; }
113                         else if (dist<200) { dist=Math.round(dist/10)*10+"m"; }
114                         else if (dist<1500) { dist=Math.round(dist/100)*100+"m"; }
115                         else if (dist<5000) { dist=Math.round(dist/100)/10+"km"; }
116                         else { dist=Math.round(dist/1000)+"km"; }
117                         // Add to table
118                         html+="<tr>";
119                         html+="<td class='direction i"+instCodes[0]+"'> ";
120                         html+="<td class='instruction'>"+instText;
121                         html+="<td class='distance'>"+dist;
122                 }
123                 html+="</table>";
124         $('#sidebar_content').html(html);
125         };
126
127
128         // Close all routing UI
129         
130         r.close=function() {
131                 $("#content").addClass("overlay-sidebar");
132                 if (r.polyline) map.removeLayer(r.polyline);
133         };
134
135         // Add engines
136         
137         r.engines=[];
138         r.addEngine=function(engine) {
139                 // Save engine
140                 var i=r.engines.length;
141                 engine.subscript=i;
142                 r['engine'+i]=engine;
143                 r.engines.push(engine);
144
145                 // Add generic JSONP function
146                 engine.requestJSONP=function(url) {
147                         var script = document.createElement('script');
148                         script.src = url+"&jsonp="+r.name+".engine"+this.subscript+".gotRoute";
149                         // OSRM doesn't like non-alphanumeric, otherwise we could just do OSM.routing.engines["+engine.subscript+"].gotRoute
150                         document.body.appendChild(script); 
151                 };
152
153                 // Populate dropdown
154                 var select=jqSearch.find('select.routing_engines');
155                 select.append("<option value='"+i+"'>"+engine.name+"</option>");
156         };
157
158         // OSRM car engine
159         // *** this should all be shared from an OSRM library somewhere
160         // *** need to clear hints at some point
161
162         r.addEngine({
163                 name: 'Car (OSRM)',
164                 draggable: true,
165                 _hints: {},
166                 getRoute: function(final,points) {
167                         var url="http://router.project-osrm.org/viaroute?z=14&output=json";
168                         for (var i=0; i<points.length; i++) {
169                                 var pair=points[i].join(',');
170                                 url+="&loc="+pair;
171                                 if (this._hints[pair]) url+= "&hint="+this._hints[pair];
172                         }
173                         if (final) url+="&instructions=true";
174                         this.requestJSONP(url);
175                 },
176                 gotRoute: function(data) {
177                         if (data.status==207) {
178                                 alert("Couldn't find route between those two places");
179                                 return false;
180                         }
181                         // *** store hints
182                         var line=L.PolylineUtil.decode(data.route_geometry);
183                         for (i=0; i<line.length; i++) { line[i].lat/=10; line[i].lng/=10; }
184                         r.setPolyline(line);
185                         r.setItinerary(data.route_instructions);
186                 }
187         });
188
189         return r;
190 };