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