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