2 osm.org routing interface
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
9 *** draggable start/end markers
10 *** translation (including all alerts and presentation)
12 *** URL history (or do we consciously not want to support that?)
13 *** spinner when waiting for result (beneath 'Go' button?)
16 *** add GraphHopper engine
19 var TURN_INSTRUCTIONS=["",
21 "Slight right onto ", // 2
22 "Turn right onto ", // 3
23 "Sharp right onto ", // 4
25 "Sharp left onto ", // 6
26 "Turn left onto ", // 7
27 "Slight left onto ", // 8
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
38 var ROUTING_POLYLINE={
47 // common functions and constants, e.g. OSRM parser, can go here
50 OSM.Routing=function(map,name,jqSearch) {
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
57 r.route_from=null; // null=unset, false=awaiting response, [lat,lon]=geocoded
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
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
68 r.chosenEngine=null; // currently selected routing engine
70 var icon_from = L.icon({
71 iconUrl: <%= asset_path('marker-green.png').to_json %>,
74 popupAnchor: [1, -34],
75 shadowUrl: <%= asset_path('images/marker-shadow.png').to_json %>,
78 var icon_to = L.icon({
79 iconUrl: <%= asset_path('marker-red.png').to_json %>,
82 popupAnchor: [1, -34],
83 shadowUrl: <%= asset_path('images/marker-shadow.png').to_json %>,
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
97 $.getJSON(querystring, function(json) { _this._gotGeocode(json,field); });
100 r._gotGeocode=function(json,field) {
101 if (json.length==0) {
102 alert("Sorry, couldn't find that place."); // *** internationalise
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);
116 // Drag and drop markers
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
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,
134 r[id].on('drag',r.markerDragged);
135 r[id].on('dragend',r.markerDragged);
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);
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');
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);
162 r.requestRoute=function(isFinal) {
163 if (r.route_from && r.route_to) {
164 r.awaitingRoute=true;
165 r.chosenEngine.getRoute(isFinal,[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;
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
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
185 r.setItinerary=function(data) {
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);
194 for (var i=0; i<data.steps.length; i++) {
195 var step=data.steps[i];
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"; }
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); });
211 $('#turnbyturn').append(row);
215 r.clickTurn=function(num,latlng) {
216 r.popup=L.popup().setLatLng(latlng).setContent("<p>"+(num+1)+"</p>").openOn(r.map);
219 // Close all routing UI
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]);
229 // Routing engine handling
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
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);
243 r['gotRoute'+num]=function(data) { r.awaitingRoute=false; list[num].gotRoute(r,data); };
245 select.append("<option value='"+i+"'>"+list[i].name+"</option>");
248 r.chosenEngine=list[0]; // default to first engine
250 // Choose an engine on dropdown change
251 r.selectEngine=function(e) {
252 r.chosenEngine=r.engines[e.target.selectedIndex];
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);