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