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