]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/routing.js.erb
Put marker at exact position user dragged it to
[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         *** translation (including all alerts and presentation)
10         *** export GPX
11         *** URL history (or do we consciously not want to support that?)
12         *** add YOURS engine
13 */
14
15 var TURN_INSTRUCTIONS=[]
16
17 var ROUTING_POLYLINE={
18         color: '#03f',
19         opacity: 0.3,
20         weight: 10
21 };
22
23
24 OSM.RoutingEngines={
25         list: []
26         // common functions and constants, e.g. OSRM parser, can go here
27 };
28
29 OSM.Routing=function(map,name,jqSearch) {
30         var r={};
31
32     TURN_INSTRUCTIONS=["",
33         I18n.t('javascripts.directions.instructions.continue_on'),                              // 1
34         I18n.t('javascripts.directions.instructions.slight_right'),             // 2
35         I18n.t('javascripts.directions.instructions.turn_right'),                       // 3
36         I18n.t('javascripts.directions.instructions.sharp_right'),              // 4
37         I18n.t('javascripts.directions.instructions.uturn'),                    // 5
38         I18n.t('javascripts.directions.instructions.sharp_left'),                       // 6
39         I18n.t('javascripts.directions.instructions.turn_left'),                        // 7
40         I18n.t('javascripts.directions.instructions.slight_left'),              // 8
41         I18n.t('javascripts.directions.instructions.via_point'),                                // 9
42         I18n.t('javascripts.directions.instructions.follow'),                                   // 10
43         I18n.t('javascripts.directions.instructions.roundabout'),               // 11
44         I18n.t('javascripts.directions.instructions.leave_roundabout'),         // 12
45         I18n.t('javascripts.directions.instructions.stay_roundabout'),  // 13
46         I18n.t('javascripts.directions.instructions.start'),                    // 14
47         I18n.t('javascripts.directions.instructions.destination'),              // 15
48         I18n.t('javascripts.directions.instructions.against_oneway'),   // 16
49         I18n.t('javascripts.directions.instructions.end_oneway')]               // 17
50
51         r.map=map;                              // Leaflet map
52         r.name=name;                    // global variable name of this instance (needed for JSONP)
53         r.jqSearch=jqSearch;    // JQuery object for search panel
54
55         r.route_from=null;              // null=unset, false=awaiting response, [lat,lon]=geocoded
56         r.route_to=null;                //  |
57         r.awaitingGeocode=false;// true if the user has requested a route, but we're waiting on a geocode result
58         r.awaitingRoute=false;  // true if we've asked the engine for a route and are waiting to hear back
59         r.dragging=false;               // true if the user is dragging a start/end point
60         r.viaPoints=[];                 // not yet used
61
62         r.polyline=null;                // Leaflet polyline object
63         r.popup=null;                   // Leaflet popup object
64         r.marker_from=null;             // Leaflet from marker
65         r.marker_to=null;               // Leaflet to marker
66
67         r.chosenEngine=null;    // currently selected routing engine
68
69         var icon_from = L.icon({
70                 iconUrl: <%= asset_path('marker-green.png').to_json %>,
71                 iconSize: [25, 41],
72                 iconAnchor: [12, 41],
73                 popupAnchor: [1, -34],
74                 shadowUrl: <%= asset_path('images/marker-shadow.png').to_json %>,
75                 shadowSize: [41, 41]
76         });
77         var icon_to = L.icon({
78                 iconUrl: <%= asset_path('marker-red.png').to_json %>,
79                 iconSize: [25, 41],
80                 iconAnchor: [12, 41],
81                 popupAnchor: [1, -34],
82                 shadowUrl: <%= asset_path('images/marker-shadow.png').to_json %>,
83                 shadowSize: [41, 41]
84         });
85
86         // Geocoding
87
88         r.geocode=function(id,event) { var _this=this;
89                 var field=event.target;
90                 var v=event.target.value;
91                 // *** do something if v==''
92                 var querystring = '<%= NOMINATIM_URL %>search?q=' + encodeURIComponent(v) + '&format=json';
93                 // *** &accept-language=<%#= request.user_preferred_languages.join(',') %>
94                 // *** prefer current viewport
95                 r[field.id]=false;
96                 $.getJSON(querystring, function(json) { _this._gotGeocode(json,field); });
97         };
98         
99         r._gotGeocode=function(json,field) {
100                 if (json.length==0) {
101                         alert(I18n.t('javascripts.directions.errors.no_place'));
102                         r[field.id]=null;
103                         return;
104                 }
105                 field.value=json[0].display_name;
106                 var lat=Number(json[0].lat), lon=Number(json[0].lon);
107                 r[field.id]=[lat,lon];
108                 r.updateMarker(field.id);
109                 if (r.awaitingGeocode) {
110                         r.awaitingGeocode=false;
111                         r.requestRoute(true, true);
112                 }
113         };
114
115         // Drag and drop markers
116         
117         r.handleDrop=function(e) {
118                 var oe=e.originalEvent;
119                 var id=oe.dataTransfer.getData('id');
120                 var pt=L.DomEvent.getMousePosition(oe,map.getContainer());      // co-ordinates of the mouse pointer at present
121                 pt.x+=Number(oe.dataTransfer.getData('offsetX'));
122                 pt.y+=Number(oe.dataTransfer.getData('offsetY'));
123                 var ll=map.containerPointToLatLng(pt);
124                 r.createMarker(ll,id);
125                 r.setNumericInput(ll,id);
126                 r.requestRoute(true, false);
127                 // update to/from field
128         };
129         r.createMarker=function(latlng,id) {
130                 if (r[id]) r.map.removeLayer(r[id]);
131                 r[id]=L.marker(latlng, {
132                         icon: id=='marker_from' ? icon_from : icon_to,
133                         draggable: true,
134                         name: id
135                 }).addTo(r.map);
136                 r[id].on('drag',r.markerDragged);
137                 r[id].on('dragend',r.markerDragged);
138         };
139         // Update marker from geocoded route input
140         r.updateMarker=function(id) {
141                 var m=id.replace('route','marker');
142                 if (!r[m]) { r.createMarker(r[id],m); return; }
143                 var ll=r[m].getLatLng();
144                 if (ll.lat!=r[id][0] || ll.lng!=r[id][1]) {
145                         r.createMarker(r[id],m);
146                 }
147         };
148         // Marker has been dragged
149         r.markerDragged=function(e) {
150                 r.dragging=(e.type=='drag');    // true for drag, false for dragend
151                 if (r.dragging && !r.chosenEngine.draggable) return;
152                 if (r.dragging && r.awaitingRoute) return;
153                 r.setNumericInput(e.target.getLatLng(), e.target.options.name);
154                 r.requestRoute(!r.dragging, false);
155         };
156         // Set a route input field to a numeric value
157         r.setNumericInput=function(ll,id) {
158                 var routeid=id.replace('marker','route');
159                 r[routeid]=[ll.lat,ll.lng];
160                 $("[name="+routeid+"]:visible").val(Math.round(ll.lat*10000)/10000+" "+Math.round(ll.lng*10000)/10000);
161         }
162         
163         // Route-fetching UI
164
165         r.requestRoute=function(isFinal, updateZoom) {
166                 if (r.route_from && r.route_to) {
167                         $(".query_wrapper.routing .spinner").show();
168                         r.awaitingRoute=true;
169                         r.chosenEngine.getRoute(isFinal,[r.route_from,r.route_to]);
170                         if(updateZoom){
171                                 r.map.fitBounds(L.latLngBounds([r.route_from, r.route_to]).pad(0.05));
172                         }
173                         // then, when the route has been fetched, it'll call the engine's gotRoute function
174                 } else if (r.route_from==false || r.route_to==false) {
175                         // we're waiting for a Nominatim response before we can request a route
176                         r.awaitingGeocode=true;
177                 }
178         };
179
180         // Take an array of Leaflet LatLngs and draw it as a polyline
181         r.setPolyline=function(line) {
182                 if (r.polyline) map.removeLayer(r.polyline);
183                 r.polyline=L.polyline(line, ROUTING_POLYLINE).addTo(r.map);
184                 // r.map.fitBounds(r.polyline.getBounds());
185                 // *** ^^^ we only want to do this for geocode-originated routes
186         };
187
188         // Take directions and write them out
189         // data = { steps: array of [latlng, sprite number, instruction text, distance in metres] }
190         // sprite numbers equate to OSRM's route_instructions turn values
191         r.setItinerary=function(data) {
192                 // Create base table
193                 $("#content").removeClass("overlay-sidebar");
194                 $('#sidebar_content').empty();
195                 var html=('<h2><a class="geolink" href="#" onclick="$(~.close_directions~).click();return false;">' +
196                           '<span class="icon close"></span></a>' + I18n.t('javascripts.directions.directions') + 
197                           '</h2><table id="turnbyturn" />').replace(/~/g,"'");
198                 $('#sidebar_content').html(html);
199                 // Add each row
200                 var cumulative=0;
201                 for (var i=0; i<data.steps.length; i++) {
202                         var step=data.steps[i];
203                         // Distance
204                         var dist=step[3];
205                         if (dist<5) { dist=""; }
206                         else if (dist<200) { dist=Math.round(dist/10)*10+"m"; }
207                         else if (dist<1500) { dist=Math.round(dist/100)*100+"m"; }
208                         else if (dist<5000) { dist=Math.round(dist/100)/10+"km"; }
209                         else { dist=Math.round(dist/1000)+"km"; }
210                         // Add to table
211                         var row=$("<tr class='turn'/>");
212                         row.append("<td class='direction i"+step[1]+"'> ");
213                         row.append("<td class='instruction'>"+step[2]);
214                         row.append("<td class='distance'>"+dist);
215                         with ({ num: i, ll: step[0] }) {
216                                 row.on('click',function(e) { r.clickTurn(num, ll); });
217                         };
218                         $('#turnbyturn').append(row);
219                         cumulative+=step[3];
220                 }
221                 $('#sidebar_content').append('<p id="routing_credit">' + r.chosenEngine.creditline + '</p>');
222
223         };
224         r.clickTurn=function(num,latlng) {
225                 r.popup=L.popup().setLatLng(latlng).setContent("<p>"+(num+1)+"</p>").openOn(r.map);
226         };
227
228         // Close all routing UI
229         
230         r.close=function() {
231                 $("#content").addClass("overlay-sidebar");
232                 r.route_from=r.route_to=null;
233                 $(".query_wrapper.routing input").val("");
234                 var remove=['polyline','popup','marker_from','marker_to'];
235                 for (var i=0; i<remove.length; i++) {
236                         if (r[remove[i]]) { map.removeLayer(r[remove[i]]); r[remove[i]]=null; }
237                 }
238         };
239
240         // Routing engine handling
241
242         // Add all engines
243         var list=OSM.RoutingEngines.list;
244         list.sort(function(a,b) { return I18n.t(a.name)>I18n.t(b.name); });
245         var select=r.jqSearch.find('select.routing_engines');
246         for (var i=0; i<list.length; i++) {
247                 // Set up JSONP callback
248                 with ({num: i}) {
249                         list[num].requestJSONP=function(url) {
250                                 var script = document.createElement('script');
251                                 script.src = url+r.name+".gotRoute"+num;
252                                 document.body.appendChild(script); 
253                         };
254                         list[num].requestCORS=function(url) {
255                                 $.ajax({ url: url, method: "GET", data: {}, dataType: 'json', success: r['gotRoute'+num] });
256                         };
257                         r['gotRoute'+num]=function(data) { 
258                                 r.awaitingRoute=false;
259                                 $(".query_wrapper.routing .spinner").hide();
260                                 if (!list[num].gotRoute(r,data)) {
261                                         // No route found
262                                         if (r.polyline) {
263                                                 map.removeLayer(r.polyline);
264                                                 r.polyline=null;
265                                         }
266                                         if (!r.dragging) { alert(I18n.t('javascripts.directions.errors.no_route')); }
267                                 }
268                         };
269                 }
270                 select.append("<option value='"+i+"'>"+I18n.t(list[i].name)+"</option>");
271         }
272         r.engines=list;
273         r.chosenEngine=list[0]; // default to first engine
274
275         // Choose an engine on dropdown change
276         r.selectEngine=function(e) {
277                 r.chosenEngine=r.engines[e.target.selectedIndex];
278                 if (r.polyline){ // and if a route is currently showing, must also refresh, else confusion
279                         r.requestRoute(true, false);
280                 }
281         };
282         // Choose an engine by name
283         r.chooseEngine=function(name) {
284                 for (var i=0; i<r.engines.length; i++) {
285                         if (r.engines[i].name==name) {
286                                 r.chosenEngine=r.engines[i];
287                                 r.jqSearch.find('select.routing_engines').val(i);
288                         }
289                 }
290         };
291
292         return r;
293 };