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