]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/routing.js.erb
Integrate marker & geocoding behaviours
[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         *** spinner when waiting for result (beneath 'Go' button?)
14
15         *** add YOURS engine
16         *** add GraphHopper 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
53         r.map=map;                              // Leaflet map
54         r.name=name;                    // global variable name of this instance (needed for JSONP)
55         r.jqSearch=jqSearch;    // JQuery object for search panel
56
57         r.route_from=null;              // null=unset, false=awaiting response, [lat,lon]=geocoded
58         r.route_to=null;                //  |
59         r.awaitingGeocode=false;// true if the user has requested a route, but we're waiting on a geocode result
60         r.awaitingRoute=false;  // true if we've asked the engine for a route and are waiting to hear back
61         r.viaPoints=[];                 // not yet used
62
63         r.polyline=null;                // Leaflet polyline object
64         r.popup=null;                   // Leaflet popup object
65         r.marker_from=null;             // Leaflet from marker
66         r.marker_to=null;               // Leaflet to marker
67
68         r.chosenEngine=null;    // currently selected routing engine
69
70         var icon_from = L.icon({
71                 iconUrl: <%= asset_path('marker-green.png').to_json %>,
72                 iconSize: [25, 41],
73                 iconAnchor: [12, 41],
74                 popupAnchor: [1, -34],
75                 shadowUrl: <%= asset_path('images/marker-shadow.png').to_json %>,
76                 shadowSize: [41, 41]
77         });
78         var icon_to = L.icon({
79                 iconUrl: <%= asset_path('marker-red.png').to_json %>,
80                 iconSize: [25, 41],
81                 iconAnchor: [12, 41],
82                 popupAnchor: [1, -34],
83                 shadowUrl: <%= asset_path('images/marker-shadow.png').to_json %>,
84                 shadowSize: [41, 41]
85         });
86
87         // Geocoding
88
89         r.geocode=function(id,event) { var _this=this;
90                 var field=event.target;
91                 var v=event.target.value;
92                 // *** do something if v==''
93                 var querystring = '<%= NOMINATIM_URL %>search?q=' + encodeURIComponent(v) + '&format=json';
94                 // *** &accept-language=<%#= request.user_preferred_languages.join(',') %>
95                 // *** prefer current viewport
96                 r[field.id]=false;
97                 $.getJSON(querystring, function(json) { _this._gotGeocode(json,field); });
98         };
99         
100         r._gotGeocode=function(json,field) {
101                 if (json.length==0) {
102                         alert("Sorry, couldn't find that place.");      // *** internationalise
103                         r[field.id]=null;
104                         return;
105                 }
106                 field.value=json[0].display_name;
107                 var lat=Number(json[0].lat), lon=Number(json[0].lon);
108                 r[field.id]=[lat,lon];
109                 r.updateMarker(field.id);
110                 if (r.awaitingGeocode) {
111                         r.awaitingGeocode=false;
112                         r.requestRoute(true);
113                 }
114         };
115
116         // Drag and drop markers
117         
118         r.handleDrop=function(e) {
119                 var id=e.originalEvent.dataTransfer.getData('id');
120                 var ll=r.map.mouseEventToLatLng(e.originalEvent);
121                 // *** ^^^ this is slightly off - we need to work out the latLng of the tip
122                 r.createMarker(ll,id);
123                 r.setNumericInput(ll,id);
124                 r.requestRoute(true);
125                 // update to/from field
126         };
127         r.createMarker=function(latlng,id) {
128                 if (r[id]) r.map.removeLayer(r[id]);
129                 r[id]=L.marker(latlng, {
130                         icon: id=='marker_from' ? icon_from : icon_to,
131                         draggable: true,
132                         name: id
133                 }).addTo(r.map);
134                 r[id].on('drag',r.markerDragged);
135                 r[id].on('dragend',r.markerDragged);
136         };
137         // Update marker from geocoded route input
138         r.updateMarker=function(id) {
139                 var m=id.replace('route','marker');
140                 if (!r[m]) { r.createMarker(r[id],m); return; }
141                 var ll=r[m].getLatLng();
142                 if (ll.lat!=r[id][0] || ll.lng!=r[id][1]) {
143                         r.createMarker(r[id],m);
144                 }
145         };
146         // Marker has been dragged
147         r.markerDragged=function(e) {
148                 if (e.type=='drag' && !r.chosenEngine.draggable) return;
149                 if (e.type=='drag' && r.awaitingRoute) return;
150                 r.setNumericInput(e.target.getLatLng(), e.target.options.name);
151                 r.requestRoute(e.type=='dragend');
152         };
153         // Set a route input field to a numeric value
154         r.setNumericInput=function(ll,id) {
155                 var routeid=id.replace('marker','route');
156                 r[routeid]=[ll.lat,ll.lng];
157                 $("[name="+routeid+"]:visible").val(Math.round(ll.lat*10000)/10000+" "+Math.round(ll.lng*10000)/10000);
158         }
159         
160         // Route-fetching UI
161
162         r.requestRoute=function(final) {
163                 if (r.route_from && r.route_to) {
164                         r.awaitingRoute=true;
165                         r.chosenEngine.getRoute(final,[r.route_from,r.route_to]);
166                         // then, when the route has been fetched, it'll call the engine's gotRoute function
167                 } else if (r.route_from==false || r.route_to==false) {
168                         // we're waiting for a Nominatim response before we can request a route
169                         r.awaitingGeocode=true;
170                 }
171         };
172
173         // Take an array of Leaflet LatLngs and draw it as a polyline
174         r.setPolyline=function(line) {
175                 if (r.polyline) map.removeLayer(r.polyline);
176                 r.polyline=L.polyline(line, ROUTING_POLYLINE).addTo(r.map);
177                 // r.map.fitBounds(r.polyline.getBounds());
178                 // *** ^^^ we only want to do this for geocode-originated routes
179         };
180
181         // Take directions and write them out
182         // data = { steps: array of [latlng, sprite number, instruction text, distance in metres] }
183         // sprite numbers equate to OSRM's route_instructions turn values
184         // *** translations?
185         r.setItinerary=function(data) {
186                 // Create base table
187                 $("#content").removeClass("overlay-sidebar");
188                 $('#sidebar_content').empty();
189                 var html='<h2><a class="geolink" href="#" onclick="$(~.close_directions~).click();return false;"><span class="icon close"></span></a>Directions</h2>'.replace(/~/g,"'");
190                 html+="<table id='turnbyturn' />";
191                 $('#sidebar_content').html(html);
192                 // Add each row
193                 var cumulative=0;
194                 for (var i=0; i<data.steps.length; i++) {
195                         var step=data.steps[i];
196                         // Distance
197                         var dist=step[3];
198                         if (dist<5) { dist=""; }
199                         else if (dist<200) { dist=Math.round(dist/10)*10+"m"; }
200                         else if (dist<1500) { dist=Math.round(dist/100)*100+"m"; }
201                         else if (dist<5000) { dist=Math.round(dist/100)/10+"km"; }
202                         else { dist=Math.round(dist/1000)+"km"; }
203                         // Add to table
204                         var row=$("<tr class='turn'/>");
205                         row.append("<td class='direction i"+step[1]+"'> ");
206                         row.append("<td class='instruction'>"+step[2]);
207                         row.append("<td class='distance'>"+dist);
208                         with ({ num: i, ll: step[0] }) {
209                                 row.on('click',function(e) { r.clickTurn(num, ll); });
210                         };
211                         $('#turnbyturn').append(row);
212                         cumulative+=step[3];
213                 }
214         };
215         r.clickTurn=function(num,latlng) {
216                 r.popup=L.popup().setLatLng(latlng).setContent("<p>"+(num+1)+"</p>").openOn(r.map);
217         };
218
219         // Close all routing UI
220         
221         r.close=function() {
222                 $("#content").addClass("overlay-sidebar");
223                 var remove=[r.polyline,r.popup,r.marker_from,r.marker_to];
224                 for (var i=0; i<remove.length; i++) {
225                         if (remove[i]) map.removeLayer(remove[i]);
226                 }
227         };
228
229         // Routing engine handling
230
231         // Add all engines
232         var list=OSM.RoutingEngines.list;
233         list.sort(function(a,b) { return a.name>b.name; });
234         var select=r.jqSearch.find('select.routing_engines');
235         for (var i=0; i<list.length; i++) {
236                 // Set up JSONP callback
237                 with ({num: i}) {
238                         list[num].requestJSONP=function(url) {
239                                 var script = document.createElement('script');
240                                 script.src = url+r.name+".gotRoute"+num;
241                                 document.body.appendChild(script); 
242                         };
243                         r['gotRoute'+num]=function(data) { r.awaitingRoute=false; list[num].gotRoute(r,data); };
244                 }
245                 select.append("<option value='"+i+"'>"+list[i].name+"</option>");
246         }
247         r.engines=list;
248         r.chosenEngine=list[0]; // default to first engine
249
250         // Choose an engine on dropdown change
251         r.selectEngine=function(e) {
252                 r.chosenEngine=r.engines[e.target.selectedIndex];
253         };
254         // Choose an engine by name
255         r.chooseEngine=function(name) {
256                 for (var i=0; i<r.engines.length; i++) {
257                         if (r.engines[i].name==name) {
258                                 r.chosenEngine=r.engines[i];
259                                 r.jqSearch.find('select.routing_engines').val(i);
260                         }
261                 }
262         };
263
264         return r;
265 };