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