]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/routing.js.erb
Allow user to click Go before geocode result
[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         // Route-fetching UI
93
94         r.requestRoute=function() {
95                 if (r.route_from && r.route_to) {
96                         r.chosenEngine.getRoute(true,[r.route_from,r.route_to]);
97                         // then, when the route has been fetched, it'll call the engine's gotRoute function
98                 } else if (r.route_from==false || r.route_to==false) {
99                         // we're waiting for a Nominatim response before we can request a route
100                         r.awaitingGeocode=true;
101                 }
102         };
103
104         // Take an array of Leaflet LatLngs and draw it as a polyline
105         r.setPolyline=function(line) {
106                 if (r.polyline) map.removeLayer(r.polyline);
107                 r.polyline=L.polyline(line, ROUTING_POLYLINE).addTo(r.map);
108                 r.map.fitBounds(r.polyline.getBounds());
109         };
110
111         // Take directions and write them out
112         // data = { steps: array of [latlng, sprite number, instruction text, distance in metres] }
113         // sprite numbers equate to OSRM's route_instructions turn values
114         // *** translations?
115         r.setItinerary=function(data) {
116                 // Create base table
117                 $("#content").removeClass("overlay-sidebar");
118                 $('#sidebar_content').empty();
119                 var html='<h2><a class="geolink" href="#" onclick="$(~.close_directions~).click();return false;"><span class="icon close"></span></a>Directions</h2>'.replace(/~/g,"'");
120                 html+="<table id='turnbyturn' />";
121                 $('#sidebar_content').html(html);
122                 // Add each row
123                 var cumulative=0;
124                 for (var i=0; i<data.steps.length; i++) {
125                         var step=data.steps[i];
126                         // Distance
127                         var dist=step[3];
128                         if (dist<5) { dist=""; }
129                         else if (dist<200) { dist=Math.round(dist/10)*10+"m"; }
130                         else if (dist<1500) { dist=Math.round(dist/100)*100+"m"; }
131                         else if (dist<5000) { dist=Math.round(dist/100)/10+"km"; }
132                         else { dist=Math.round(dist/1000)+"km"; }
133                         // Add to table
134                         var row=$("<tr class='turn'/>");
135                         row.append("<td class='direction i"+step[1]+"'> ");
136                         row.append("<td class='instruction'>"+step[2]);
137                         row.append("<td class='distance'>"+dist);
138                         with ({ num: i, ll: step[0] }) {
139                                 row.on('click',function(e) { r.clickTurn(num, ll); });
140                         };
141                         $('#turnbyturn').append(row);
142                         cumulative+=step[3];
143                 }
144         };
145         r.clickTurn=function(num,latlng) {
146                 L.popup().setLatLng(latlng).setContent("<p>"+(num+1)+"</p>").openOn(r.map);
147         };
148
149
150         // Close all routing UI
151         
152         r.close=function() {
153                 $("#content").addClass("overlay-sidebar");
154                 if (r.polyline) map.removeLayer(r.polyline);
155         };
156
157         // Routing engine handling
158
159         // Add all engines
160         var list=OSM.RoutingEngines.list;
161         list.sort(function(a,b) { return a.name>b.name; });
162         var select=r.jqSearch.find('select.routing_engines');
163         for (var i=0; i<list.length; i++) {
164                 // Set up JSONP callback
165                 with ({num: i}) {
166                         list[num].requestJSONP=function(url) {
167                                 var script = document.createElement('script');
168                                 script.src = url+r.name+".gotRoute"+num;
169                                 document.body.appendChild(script); 
170                         };
171                         r['gotRoute'+num]=function(data) { list[num].gotRoute(r,data); };
172                 }
173                 select.append("<option value='"+i+"'>"+list[i].name+"</option>");
174         }
175         r.engines=list;
176         r.chosenEngine=list[0]; // default to first engine
177
178         // Choose an engine on dropdown change
179         r.selectEngine=function(e) {
180                 r.chosenEngine=r.engines[e.target.selectedIndex];
181         };
182         // Choose an engine by name
183         r.chooseEngine=function(name) {
184                 for (var i=0; i<r.engines.length; i++) {
185                         if (r.engines[i].name==name) {
186                                 r.chosenEngine=r.engines[i];
187                                 r.jqSearch.find('select.routing_engines').val(i);
188                         }
189                 }
190         };
191
192         return r;
193 };