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