]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/routing.js.erb
fc2bb8d30e4f02adc6441f254647e3c10fc9984b
[rails.git] / app / assets / javascripts / routing.js.erb
1 /*
2  osm.org routing interface
3 */
4
5 var TURN_INSTRUCTIONS = [];
6
7 var ROUTING_POLYLINE = {
8   color: '#03f',
9   opacity: 0.3,
10   weight: 10
11 };
12
13 var ROUTING_POLYLINE_HIGHLIGHT = {
14   color: '#ff0',
15   opacity: 0.5,
16   weight: 12
17 };
18
19 OSM.RoutingEngines = {
20   list: [],
21   add: function (supportsHTTPS, engine) {
22     if (document.location.protocol == "http:" || supportsHTTPS) this.list.push(engine);
23   }
24 };
25
26 OSM.Routing = function (map, name, jqSearch) {
27   var r = {};
28
29   TURN_INSTRUCTIONS = [
30     "",
31     I18n.t('javascripts.directions.instructions.continue_on'),      // 1
32     I18n.t('javascripts.directions.instructions.slight_right'),     // 2
33     I18n.t('javascripts.directions.instructions.turn_right'),       // 3
34     I18n.t('javascripts.directions.instructions.sharp_right'),      // 4
35     I18n.t('javascripts.directions.instructions.uturn'),            // 5
36     I18n.t('javascripts.directions.instructions.sharp_left'),       // 6
37     I18n.t('javascripts.directions.instructions.turn_left'),        // 7
38     I18n.t('javascripts.directions.instructions.slight_left'),      // 8
39     I18n.t('javascripts.directions.instructions.via_point'),        // 9
40     I18n.t('javascripts.directions.instructions.follow'),           // 10
41     I18n.t('javascripts.directions.instructions.roundabout'),       // 11
42     I18n.t('javascripts.directions.instructions.leave_roundabout'), // 12
43     I18n.t('javascripts.directions.instructions.stay_roundabout'),  // 13
44     I18n.t('javascripts.directions.instructions.start'),            // 14
45     I18n.t('javascripts.directions.instructions.destination'),      // 15
46     I18n.t('javascripts.directions.instructions.against_oneway'),   // 16
47     I18n.t('javascripts.directions.instructions.end_oneway')        // 17
48   ];
49
50   r.map = map;              // Leaflet map
51   r.name = name;            // global variable name of this instance (needed for JSONP)
52   r.jqSearch = jqSearch;    // JQuery object for search panel
53
54   r.route_from = null;      // null=unset, false=awaiting response, [lat,lon]=geocoded
55   r.route_to = null;        //  |
56   r.awaitingGeocode = false;// true if the user has requested a route, but we're waiting on a geocode result
57   r.awaitingRoute = false;  // true if we've asked the engine for a route and are waiting to hear back
58   r.dragging = false;       // true if the user is dragging a start/end point
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
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) {
89     var _this = this;
90     var field = event.target;
91     var v = event.target.value;
92     var querystring = '<%= NOMINATIM_URL %>search?q=' + encodeURIComponent(v) + '&format=json';
93     // *** &accept-language=<%#= request.user_preferred_languages.join(',') %>
94     r[field.id] = false;
95     $.getJSON(querystring, function (json) {
96       _this._gotGeocode(json, field);
97     });
98   };
99
100   r._gotGeocode = function (json, field) {
101     if (json.length == 0) {
102       alert(I18n.t('javascripts.directions.errors.no_place'));
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, true);
113     }
114   };
115
116   // Drag and drop markers
117
118   r.handleDrop = function (e) {
119     var oe = e.originalEvent;
120     var id = oe.dataTransfer.getData('id');
121     var pt = L.DomEvent.getMousePosition(oe, map.getContainer());  // co-ordinates of the mouse pointer at present
122     pt.x += Number(oe.dataTransfer.getData('offsetX'));
123     pt.y += Number(oe.dataTransfer.getData('offsetY'));
124     var ll = map.containerPointToLatLng(pt);
125     r.createMarker(ll, id);
126     r.setNumericInput(ll, id);
127     r.requestRoute(true, false);
128     // update to/from field
129   };
130
131   r.createMarker = function (latlng, id) {
132     if (r[id]) r.map.removeLayer(r[id]);
133     r[id] = L.marker(latlng, {
134       icon: id == 'marker_from' ? icon_from : icon_to,
135       draggable: true,
136       name: id
137     }).addTo(r.map);
138     r[id].on('drag', r.markerDragged);
139     r[id].on('dragend', r.markerDragged);
140   };
141
142   // Update marker from geocoded route input
143   r.updateMarker = function (id) {
144     var m = id.replace('route', 'marker');
145     if (!r[m]) {
146       r.createMarker(r[id], m);
147       return;
148     }
149     var ll = r[m].getLatLng();
150     if (ll.lat != r[id][0] || ll.lng != r[id][1]) {
151       r.createMarker(r[id], m);
152     }
153   };
154
155   // Marker has been dragged
156   r.markerDragged = function (e) {
157     r.dragging = (e.type == 'drag');    // true for drag, false for dragend
158     if (r.dragging && !r.chosenEngine.draggable) return;
159     if (r.dragging && r.awaitingRoute) return;
160     r.setNumericInput(e.target.getLatLng(), e.target.options.name);
161     r.requestRoute(!r.dragging, false);
162   };
163
164   // Set a route input field to a numeric value
165   r.setNumericInput = function (ll, id) {
166     var routeid = id.replace('marker', 'route');
167     r[routeid] = [ll.lat, ll.lng];
168     $("[name=" + routeid + "]:visible").val(Math.round(ll.lat * 10000) / 10000 + " " + Math.round(ll.lng * 10000) / 10000);
169   };
170
171   // Route-fetching UI
172
173   r.requestRoute = function (isFinal, updateZoom) {
174     if (r.route_from && r.route_to) {
175       $(".query_wrapper.routing .spinner").show();
176       r.awaitingRoute = true;
177       r.chosenEngine.getRoute(isFinal, [r.route_from, r.route_to]);
178       if (updateZoom) {
179         r.map.fitBounds(L.latLngBounds([r.route_from, r.route_to]).pad(0.05));
180       }
181       // then, when the route has been fetched, it'll call the engine's gotRoute function
182     } else if (r.route_from == false || r.route_to == false) {
183       // we're waiting for a Nominatim response before we can request a route
184       r.awaitingGeocode = true;
185     }
186   };
187
188   // Take an array of Leaflet LatLngs and draw it as a polyline
189   r.setPolyline = function (line) {
190     if (r.polyline) map.removeLayer(r.polyline);
191     r.polyline = L.polyline(line, ROUTING_POLYLINE).addTo(r.map);
192   };
193
194   // Take directions and write them out
195   // data = { steps: array of [latlng, sprite number, instruction text, distance in metres, highlightPolyline] }
196   // sprite numbers equate to OSRM's route_instructions turn values
197   r.setItinerary = function (data) {
198     // Create base table
199     $("#content").removeClass("overlay-sidebar");
200     $('#sidebar_content').empty();
201     var html = ('<h2><a class="geolink" href="#" onclick="$(~.close_directions~).click();return false;">' +
202       '<span class="icon close"></span></a>' + I18n.t('javascripts.directions.directions') +
203       '</h2><p id="routing_summary">' +
204       I18n.t('javascripts.directions.distance') + ': ' + r.formatDistance(data.distance) + '. ' +
205       I18n.t('javascripts.directions.time') + ': ' + r.formatTime(data.time) + '.</p>' +
206       '<table id="turnbyturn" />').replace(/~/g, "'");
207     $('#sidebar_content').html(html);
208     // Add each row
209     var cumulative = 0;
210     for (var i = 0; i < data.steps.length; i++) {
211       var step = data.steps[i];
212       // Distance
213       var dist = step[3];
214       if (dist < 5) {
215         dist = "";
216       }
217       else if (dist < 200) {
218         dist = Math.round(dist / 10) * 10 + "m";
219       }
220       else if (dist < 1500) {
221         dist = Math.round(dist / 100) * 100 + "m";
222       }
223       else if (dist < 5000) {
224         dist = Math.round(dist / 100) / 10 + "km";
225       }
226       else {
227         dist = Math.round(dist / 1000) + "km";
228       }
229       // Add to table
230       var row = $("<tr class='turn'/>");
231       row.append("<td class='direction i" + step[1] + "'> ");
232       row.append("<td class='instruction'>" + step[2]);
233       row.append("<td class='distance'>" + dist);
234       with ({ instruction: step[2], ll: step[0], lineseg: step[4] }) {
235         row.on('click', function (e) {
236           r.clickTurn(instruction, ll);
237         });
238         row.hover(function (e) {
239           r.highlightSegment(lineseg);
240         }, function (e) {
241           r.unhighlightSegment();
242         });
243       }
244       ;
245       $('#turnbyturn').append(row);
246       cumulative += step[3];
247     }
248     $('#sidebar_content').append('<p id="routing_credit">' + I18n.t('javascripts.directions.instructions.courtesy', {link: r.chosenEngine.creditline}) + '</p>');
249   };
250
251   r.clickTurn = function (instruction, latlng) {
252     r.popup = L.popup().setLatLng(latlng).setContent("<p>" + instruction + "</p>").openOn(r.map);
253   };
254
255   r.highlightSegment = function (lineseg) {
256     if (r.highlighted) map.removeLayer(r.highlighted);
257     r.highlighted = L.polyline(lineseg, ROUTING_POLYLINE_HIGHLIGHT).addTo(r.map);
258   };
259
260   r.unhighlightSegment = function () {
261     if (r.highlighted) map.removeLayer(r.highlighted);
262   };
263
264   r.formatDistance = function (m) {
265     if (m < 1000) {
266       return Math.round(m) + "m";
267     }
268     else if (m < 10000) {
269       return (m / 1000.0).toFixed(1) + "km";
270     }
271     else {
272       return Math.round(m / 1000) + "km";
273     }
274   };
275
276   r.formatTime = function (s) {
277     var m = Math.round(s / 60);
278     var h = Math.floor(m / 60);
279     m -= h * 60;
280     return h + ":" + (m < 10 ? '0' : '') + m;
281   };
282
283   // Close all routing UI
284
285   r.close = function () {
286     $("#content").addClass("overlay-sidebar");
287     r.route_from = r.route_to = null;
288     $(".query_wrapper.routing input").val("");
289     var remove = ['polyline', 'popup', 'marker_from', 'marker_to'];
290     for (var i = 0; i < remove.length; i++) {
291       if (r[remove[i]]) {
292         map.removeLayer(r[remove[i]]);
293         r[remove[i]] = null;
294       }
295     }
296   };
297
298   // Routing engine handling
299
300   // Add all engines
301   var list = OSM.RoutingEngines.list;
302   list.sort(function (a, b) {
303     return I18n.t(a.name) > I18n.t(b.name);
304   });
305   var select = r.jqSearch.find('select.routing_engines');
306   for (var i = 0; i < list.length; i++) {
307     // Set up JSONP callback
308     with ({num: i}) {
309       list[num].requestJSONP = function (url) {
310         var script = document.createElement('script');
311         script.src = url + r.name + ".gotRoute" + num;
312         document.body.appendChild(script);
313       };
314       list[num].requestCORS = function (url) {
315         $.ajax({ url: url, method: "GET", data: {}, dataType: 'json', success: r['gotRoute' + num] });
316       };
317       r['gotRoute' + num] = function (data) {
318         r.awaitingRoute = false;
319         $(".query_wrapper.routing .spinner").hide();
320         if (!list[num].gotRoute(r, data)) {
321           // No route found
322           if (r.polyline) {
323             map.removeLayer(r.polyline);
324             r.polyline = null;
325           }
326           if (!r.dragging) {
327             alert(I18n.t('javascripts.directions.errors.no_route'));
328           }
329         }
330       };
331     }
332     select.append("<option value='" + i + "'>" + I18n.t(list[i].name) + "</option>");
333   }
334
335   r.engines = list;
336   r.chosenEngine = list[0]; // default to first engine
337
338   // Choose an engine on dropdown change
339   r.selectEngine = function (e) {
340     r.chosenEngine = r.engines[e.target.selectedIndex];
341     if (r.polyline) { // and if a route is currently showing, must also refresh, else confusion
342       r.requestRoute(true, false);
343     }
344   };
345
346   // Choose an engine by name
347   r.chooseEngine = function (name) {
348     for (var i = 0; i < r.engines.length; i++) {
349       if (r.engines[i].name == name) {
350         r.chosenEngine = r.engines[i];
351         r.jqSearch.find('select.routing_engines').val(i);
352       }
353     }
354   };
355
356   return r;
357 };