]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/directions.js
Notes: show first comment as marker tooltip
[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           alert(I18n.t('javascripts.directions.errors.no_route'));
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) + '.</p>' +
211         '<table id="turnbyturn" />';
212
213       $('#sidebar_content')
214         .html(html);
215
216       // Add each row
217       var cumulative = 0;
218       route.steps.forEach(function (step) {
219         var ll        = step[0],
220           direction   = step[1],
221           instruction = step[2],
222           dist        = step[3],
223           lineseg     = step[4];
224
225         cumulative += dist;
226
227         if (dist < 5) {
228           dist = "";
229         } else if (dist < 200) {
230           dist = Math.round(dist / 10) * 10 + "m";
231         } else if (dist < 1500) {
232           dist = Math.round(dist / 100) * 100 + "m";
233         } else if (dist < 5000) {
234           dist = Math.round(dist / 100) / 10 + "km";
235         } else {
236           dist = Math.round(dist / 1000) + "km";
237         }
238
239         var row = $("<tr class='turn'/>");
240         row.append("<td><div class='direction i" + direction + "'/></td> ");
241         row.append("<td class='instruction'>" + instruction);
242         row.append("<td class='distance'>" + dist);
243
244         row.on('click', function () {
245           popup
246             .setLatLng(ll)
247             .setContent("<p>" + instruction + "</p>")
248             .openOn(map);
249         });
250
251         row.hover(function () {
252           highlight
253             .setLatLngs(lineseg)
254             .addTo(map);
255         }, function () {
256           map.removeLayer(highlight);
257         });
258
259         $('#turnbyturn').append(row);
260       });
261
262       $('#sidebar_content').append('<p id="routing_credit">' +
263         I18n.t('javascripts.directions.instructions.courtesy', {link: chosenEngine.creditline}) +
264         '</p>');
265
266       $('#sidebar_content a.geolink').on('click', function(e) {
267         e.preventDefault();
268         map.removeLayer(polyline);
269         $('#sidebar_content').html('');
270         map.setSidebarOverlaid(true);
271         // TODO: collapse width of sidebar back to previous
272       });
273     });
274   }
275
276   var engines = OSM.Directions.engines;
277
278   engines.sort(function (a, b) {
279     a = I18n.t('javascripts.directions.engines.' + a.id);
280     b = I18n.t('javascripts.directions.engines.' + b.id);
281     return a.localeCompare(b);
282   });
283
284   var select = $('select.routing_engines');
285
286   engines.forEach(function(engine, i) {
287     select.append("<option value='" + i + "'>" + I18n.t('javascripts.directions.engines.' + engine.id) + "</option>");
288   });
289
290   setEngine('osrm_car');
291
292   select.on("change", function (e) {
293     chosenEngine = engines[e.target.selectedIndex];
294     if (map.hasLayer(polyline)) {
295       getRoute();
296     }
297   });
298
299   $(".directions_form").on("submit", function(e) {
300     e.preventDefault();
301     getRoute();
302   });
303
304   $(".routing_marker").on('dragstart', function (e) {
305     e.originalEvent.dataTransfer.effectAllowed = 'move';
306     e.originalEvent.dataTransfer.setData('type', $(this).data('type'));
307     var img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
308     e.originalEvent.dataTransfer.setDragImage(img.get(0), 12, 21);
309   });
310
311   var page = {};
312
313   page.pushstate = page.popstate = function() {
314     $(".search_form").hide();
315     $(".directions_form").show();
316
317     $("#map").on('dragend dragover', function (e) {
318       e.preventDefault();
319     });
320
321     $("#map").on('drop', function (e) {
322       e.preventDefault();
323       var oe = e.originalEvent;
324       var type = oe.dataTransfer.getData('type');
325       var pt = L.DomEvent.getMousePosition(oe, map.getContainer());  // co-ordinates of the mouse pointer at present
326       pt.y += 20;
327       var ll = map.containerPointToLatLng(pt);
328       endpoints[type === 'from' ? 0 : 1].setLatLng(ll);
329       getRoute();
330     });
331
332     var params = querystring.parse(location.search.substring(1)),
333       route = (params.route || '').split(';');
334
335     if (params.engine) {
336       setEngine(params.engine);
337     }
338
339     if (params.from) {
340       endpoints[0].setValue(params.from);
341       endpoints[1].setValue("");
342     } else {
343       endpoints[0].setValue("");
344       endpoints[1].setValue("");
345     }
346
347     var o = route[0] && L.latLng(route[0].split(',')),
348         d = route[1] && L.latLng(route[1].split(','));
349
350     if (o) endpoints[0].setLatLng(o);
351     if (d) endpoints[1].setLatLng(d);
352
353     map.setSidebarOverlaid(!o || !d);
354
355     getRoute();
356   };
357
358   page.load = function() {
359     page.pushstate();
360   };
361
362   page.unload = function() {
363     $(".search_form").show();
364     $(".directions_form").hide();
365     $("#map").off('dragend dragover drop');
366
367     map
368       .removeLayer(popup)
369       .removeLayer(polyline)
370       .removeLayer(endpoints[0].marker)
371       .removeLayer(endpoints[1].marker);
372   };
373
374   return page;
375 };
376
377 OSM.Directions.engines = [];
378
379 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
380   if (document.location.protocol === "http:" || supportsHTTPS) {
381     OSM.Directions.engines.push(engine);
382   }
383 };