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