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