]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/directions.js
c0aed706c6043702e3b6465495e0fabb7ec1a029
[rails.git] / app / assets / javascripts / index / directions.js
1 //= require_self
2 //= require_tree ./directions
3
4 OSM.Directions = function (map) {
5   var awaitingGeocode; // true if the user has requested a route, but we're waiting on a geocode result
6   var awaitingRoute;   // true if we've asked the engine for a route and are waiting to hear back
7   var dragging;        // true if the user is dragging a start/end point
8   var chosenEngine;
9
10   var popup = L.popup({autoPanPadding: [100, 100]});
11
12   var polyline = L.polyline([], {
13     color: '#03f',
14     opacity: 0.3,
15     weight: 10
16   });
17
18   var highlight = L.polyline([], {
19     color: '#ff0',
20     opacity: 0.5,
21     weight: 12
22   });
23
24   var endpoints = [
25     Endpoint($("input[name='route_from']"), OSM.MARKER_GREEN),
26     Endpoint($("input[name='route_to']"), OSM.MARKER_RED)
27   ];
28
29   var expiry = new Date();
30   expiry.setYear(expiry.getFullYear() + 10);
31
32   function Endpoint(input, iconUrl) {
33     var endpoint = {};
34
35     endpoint.marker = L.marker([0, 0], {
36       icon: L.icon({
37         iconUrl: iconUrl,
38         iconSize: [25, 41],
39         iconAnchor: [12, 41],
40         popupAnchor: [1, -34],
41         shadowUrl: OSM.MARKER_SHADOW,
42         shadowSize: [41, 41]
43       }),
44       draggable: true
45     });
46
47     endpoint.marker.on('drag dragend', function (e) {
48       dragging = (e.type === 'drag');
49       if (dragging && !chosenEngine.draggable) return;
50       if (dragging && awaitingRoute) return;
51       endpoint.setLatLng(e.target.getLatLng());
52       if (map.hasLayer(polyline)) {
53         getRoute();
54       }
55     });
56
57     input.on("change", function (e) {
58       // make text the same in both text boxes
59       var value = e.target.value;
60       endpoint.setValue(value);
61     });
62
63     endpoint.setValue = function(value, latlng) {
64       endpoint.value = value;
65       delete endpoint.latlng;
66       input.val(value);
67
68       if (latlng) {
69         endpoint.setLatLng(latlng);
70       } else {
71         endpoint.getGeocode();
72       }
73     };
74
75     endpoint.getGeocode = function() {
76       // if no one has entered a value yet, then we can't geocode, so don't
77       // even try.
78       if (!endpoint.value) {
79         return;
80       }
81
82       endpoint.awaitingGeocode = true;
83
84       $.getJSON(OSM.NOMINATIM_URL + 'search?q=' + encodeURIComponent(endpoint.value) + '&format=json', function (json) {
85         endpoint.awaitingGeocode = false;
86         endpoint.hasGeocode = true;
87         if (json.length === 0) {
88           alert(I18n.t('javascripts.directions.errors.no_place'));
89           return;
90         }
91
92         input.val(json[0].display_name);
93
94         endpoint.latlng = L.latLng(json[0]);
95         endpoint.marker
96           .setLatLng(endpoint.latlng)
97           .addTo(map);
98
99         if (awaitingGeocode) {
100           awaitingGeocode = false;
101           getRoute();
102         }
103       });
104     };
105
106     endpoint.setLatLng = function (ll) {
107       var precision = OSM.zoomPrecision(map.getZoom());
108       input.val(ll.lat.toFixed(precision) + ", " + ll.lng.toFixed(precision));
109       endpoint.hasGeocode = true;
110       endpoint.latlng = ll;
111       endpoint.marker
112         .setLatLng(ll)
113         .addTo(map);
114     };
115
116     return endpoint;
117   }
118
119   $(".directions_form .reverse_directions").on("click", function() {
120     var from = endpoints[0].latlng,
121         to = endpoints[1].latlng;
122
123     OSM.router.route("/directions?" + querystring.stringify({
124       from: $("#route_to").val(),
125       to: $("#route_from").val(),
126       route: to.lat + "," + to.lng + ";" + from.lat + "," + from.lng
127     }));
128   });
129
130   $(".directions_form .close").on("click", function(e) {
131     e.preventDefault();
132     var route_from = endpoints[0].value;
133     if (route_from) {
134       OSM.router.route("/?query=" + encodeURIComponent(route_from) + OSM.formatHash(map));
135     } else {
136       OSM.router.route("/" + OSM.formatHash(map));
137     }
138   });
139
140   function formatDistance(m) {
141     if (m < 1000) {
142       return Math.round(m) + "m";
143     } else if (m < 10000) {
144       return (m / 1000.0).toFixed(1) + "km";
145     } else {
146       return Math.round(m / 1000) + "km";
147     }
148   }
149
150   function formatTime(s) {
151     var m = Math.round(s / 60);
152     var h = Math.floor(m / 60);
153     m -= h * 60;
154     return h + ":" + (m < 10 ? '0' : '') + m;
155   }
156
157   function setEngine(id) {
158     engines.forEach(function(engine, i) {
159       if (engine.id === id) {
160         chosenEngine = engine;
161         select.val(i);
162       }
163     });
164   }
165
166   function getRoute() {
167     // Cancel any route that is already in progress
168     if (awaitingRoute) awaitingRoute.abort();
169
170     // go fetch geocodes for any endpoints which have not already
171     // been geocoded.
172     for (var ep_i = 0; ep_i < 2; ++ep_i) {
173       var endpoint = endpoints[ep_i];
174       if (!endpoint.hasGeocode && !endpoint.awaitingGeocode) {
175         endpoint.getGeocode();
176         awaitingGeocode = true;
177       }
178     }
179     if (endpoints[0].awaitingGeocode || endpoints[1].awaitingGeocode) {
180       awaitingGeocode = true;
181       return;
182     }
183
184     var o = endpoints[0].latlng,
185         d = endpoints[1].latlng;
186
187     if (!o || !d) return;
188     $("header").addClass("closed");
189
190     var precision = OSM.zoomPrecision(map.getZoom());
191
192     OSM.router.replace("/directions?" + querystring.stringify({
193       engine: chosenEngine.id,
194       route: o.lat.toFixed(precision) + ',' + o.lng.toFixed(precision) + ';' +
195              d.lat.toFixed(precision) + ',' + d.lng.toFixed(precision)
196     }));
197
198     // copy loading item to sidebar and display it. we copy it, rather than
199     // just using it in-place and replacing it in case it has to be used
200     // again.
201     $('#sidebar_content').html($('.directions_form .loader_copy').html());
202     map.setSidebarOverlaid(false);
203
204     awaitingRoute = chosenEngine.getRoute([o, d], function (err, route) {
205       awaitingRoute = null;
206
207       if (err) {
208         map.removeLayer(polyline);
209
210         if (!dragging) {
211           $('#sidebar_content').html('<p class="search_results_error">' + I18n.t('javascripts.directions.errors.no_route') + '</p>');
212         }
213
214         return;
215       }
216
217       polyline
218         .setLatLngs(route.line)
219         .addTo(map);
220
221       if (!dragging) {
222         map.fitBounds(polyline.getBounds().pad(0.05));
223       }
224
225       var html = '<h2><a class="geolink" href="#">' +
226         '<span class="icon close"></span></a>' + I18n.t('javascripts.directions.directions') +
227         '</h2><p id="routing_summary">' +
228         I18n.t('javascripts.directions.distance') + ': ' + formatDistance(route.distance) + '. ' +
229         I18n.t('javascripts.directions.time') + ': ' + formatTime(route.time) + '.';
230       if (typeof route.ascend !== 'undefined' && typeof route.descend !== 'undefined') {
231         html += '<br />' +
232           I18n.t('javascripts.directions.ascend') + ': ' + Math.round(route.ascend) + 'm. ' +
233           I18n.t('javascripts.directions.descend') + ': ' + Math.round(route.descend) +'m.';
234       }
235       html += '</p><table id="turnbyturn" />';
236
237       $('#sidebar_content')
238         .html(html);
239
240       // Add each row
241       var cumulative = 0;
242       route.steps.forEach(function (step) {
243         var ll        = step[0],
244           direction   = step[1],
245           instruction = step[2],
246           dist        = step[3],
247           lineseg     = step[4];
248
249         cumulative += dist;
250
251         if (dist < 5) {
252           dist = "";
253         } else if (dist < 200) {
254           dist = Math.round(dist / 10) * 10 + "m";
255         } else if (dist < 1500) {
256           dist = Math.round(dist / 100) * 100 + "m";
257         } else if (dist < 5000) {
258           dist = Math.round(dist / 100) / 10 + "km";
259         } else {
260           dist = Math.round(dist / 1000) + "km";
261         }
262
263         var row = $("<tr class='turn'/>");
264         row.append("<td><div class='direction i" + direction + "'/></td> ");
265         row.append("<td class='instruction'>" + instruction);
266         row.append("<td class='distance'>" + dist);
267
268         row.on('click', function () {
269           popup
270             .setLatLng(ll)
271             .setContent("<p>" + instruction + "</p>")
272             .openOn(map);
273         });
274
275         row.hover(function () {
276           highlight
277             .setLatLngs(lineseg)
278             .addTo(map);
279         }, function () {
280           map.removeLayer(highlight);
281         });
282
283         $('#turnbyturn').append(row);
284       });
285
286       $('#sidebar_content').append('<p id="routing_credit">' +
287         I18n.t('javascripts.directions.instructions.courtesy', {link: chosenEngine.creditline}) +
288         '</p>');
289
290       $('#sidebar_content a.geolink').on('click', function(e) {
291         e.preventDefault();
292         map.removeLayer(polyline);
293         $('#sidebar_content').html('');
294         map.setSidebarOverlaid(true);
295         // TODO: collapse width of sidebar back to previous
296       });
297     });
298   }
299
300   var engines = OSM.Directions.engines;
301
302   engines.sort(function (a, b) {
303     a = I18n.t('javascripts.directions.engines.' + a.id);
304     b = I18n.t('javascripts.directions.engines.' + b.id);
305     return a.localeCompare(b);
306   });
307
308   var select = $('select.routing_engines');
309
310   engines.forEach(function(engine, i) {
311     select.append("<option value='" + i + "'>" + I18n.t('javascripts.directions.engines.' + engine.id) + "</option>");
312   });
313
314   var chosenEngineId = $.cookie('_osm_directions_engine');
315   if(!chosenEngineId) {
316     chosenEngineId = 'osrm_car';
317   }
318   setEngine(chosenEngineId);
319
320   select.on("change", function (e) {
321     chosenEngine = engines[e.target.selectedIndex];
322     $.cookie('_osm_directions_engine', chosenEngine.id, { expires: expiry, path: '/' });
323     if (map.hasLayer(polyline)) {
324       getRoute();
325     }
326   });
327
328   $(".directions_form").on("submit", function(e) {
329     e.preventDefault();
330     getRoute();
331   });
332
333   $(".routing_marker").on('dragstart', function (e) {
334     var dt = e.originalEvent.dataTransfer;
335     dt.effectAllowed = 'move';
336     var dragData = { type: $(this).data('type') };
337     dt.setData('text', JSON.stringify(dragData));
338     if (dt.setDragImage) {
339       var img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
340       dt.setDragImage(img.get(0), 12, 21);
341     }
342   });
343
344   var page = {};
345
346   page.pushstate = page.popstate = function() {
347     $(".search_form").hide();
348     $(".directions_form").show();
349
350     $("#map").on('dragend dragover', function (e) {
351       e.preventDefault();
352     });
353
354     $("#map").on('drop', function (e) {
355       e.preventDefault();
356       var oe = e.originalEvent;
357       var dragData = JSON.parse(oe.dataTransfer.getData('text'));
358       var type = dragData.type;
359       var pt = L.DomEvent.getMousePosition(oe, map.getContainer());  // co-ordinates of the mouse pointer at present
360       pt.y += 20;
361       var ll = map.containerPointToLatLng(pt);
362       endpoints[type === 'from' ? 0 : 1].setLatLng(ll);
363       getRoute();
364     });
365
366     var params = querystring.parse(location.search.substring(1)),
367         route = (params.route || '').split(';'),
368         from = route[0] && L.latLng(route[0].split(',')),
369         to = route[1] && L.latLng(route[1].split(','));
370
371     if (params.engine) {
372       setEngine(params.engine);
373     }
374
375     endpoints[0].setValue(params.from || "", from);
376     endpoints[1].setValue(params.to || "", to);
377
378     map.setSidebarOverlaid(!from || !to);
379
380     getRoute();
381   };
382
383   page.load = function() {
384     page.pushstate();
385   };
386
387   page.unload = function() {
388     $(".search_form").show();
389     $(".directions_form").hide();
390     $("#map").off('dragend dragover drop');
391
392     map
393       .removeLayer(popup)
394       .removeLayer(polyline)
395       .removeLayer(endpoints[0].marker)
396       .removeLayer(endpoints[1].marker);
397   };
398
399   return page;
400 };
401
402 OSM.Directions.engines = [];
403
404 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
405   if (document.location.protocol === "http:" || supportsHTTPS) {
406     OSM.Directions.engines.push(engine);
407   }
408 };