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