]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/directions.js.erb
f1f45814e3bf6ee4d54d4d7fda90f498f98abd3b
[rails.git] / app / assets / javascripts / index / directions.js.erb
1 //= require_self
2 //= require_tree ./directions_engines
3
4 OSM.Directions = function (map) {
5   $(".directions_form a.directions_close").on("click", function(e) {
6     e.preventDefault();
7     var route_from = $(e.target).parent().parent().parent().find("input[name=route_from]").val();
8     if (route_from) {
9       OSM.router.route("/?query=" + encodeURIComponent(route_from) + OSM.formatHash(map));
10     } else {
11       OSM.router.route("/" + OSM.formatHash(map));
12     }
13   });
14
15   var awaitingGeocode; // true if the user has requested a route, but we're waiting on a geocode result
16   var awaitingRoute;   // true if we've asked the engine for a route and are waiting to hear back
17   var dragging;        // true if the user is dragging a start/end point
18   var chosenEngine;
19
20   var popup = L.popup();
21
22   var polyline = L.polyline([], {
23     color: '#03f',
24     opacity: 0.3,
25     weight: 10
26   });
27
28   var highlight = L.polyline([], {
29     color: '#ff0',
30     opacity: 0.5,
31     weight: 12
32   });
33
34   var endpoints = [
35     Endpoint($("input[name='route_from']"), <%= asset_path('marker-green.png').to_json %>),
36     Endpoint($("input[name='route_to']"),   <%= asset_path('marker-red.png').to_json %>)
37   ];
38
39   function Endpoint(input, iconUrl) {
40     var endpoint = {};
41
42     endpoint.marker = L.marker([0, 0], {
43       icon: L.icon({
44         iconUrl: iconUrl,
45         iconSize: [25, 41],
46         iconAnchor: [12, 41],
47         popupAnchor: [1, -34],
48         shadowUrl: <%= asset_path('images/marker-shadow.png').to_json %>,
49         shadowSize: [41, 41]
50       }),
51       draggable: true
52     });
53
54     endpoint.marker.on('drag dragend', function (e) {
55       dragging = (e.type == 'drag');
56       if (dragging && !chosenEngine.draggable) return;
57       if (dragging && awaitingRoute) return;
58       endpoint.setLatLng(e.target.getLatLng());
59       if (map.hasLayer(polyline)) {
60         getRoute();
61       }
62     });
63
64     input.on("change", function (e) {
65       endpoint.awaitingGeocode = true;
66
67       $.getJSON('<%= NOMINATIM_URL %>search?q=' + encodeURIComponent(e.target.value) + '&format=json', function (json) {
68         endpoint.awaitingGeocode = false;
69
70         if (json.length == 0) {
71           alert(I18n.t('javascripts.directions.errors.no_place'));
72           return;
73         }
74
75         input.val(json[0].display_name);
76
77         endpoint.latlng = L.latLng(json[0]);
78         endpoint.marker
79           .setLatLng(endpoint.latlng)
80           .addTo(map);
81
82         if (awaitingGeocode) {
83           awaitingGeocode = false;
84           getRoute();
85         }
86       });
87     });
88
89     endpoint.setLatLng = function (ll) {
90       var precision = OSM.zoomPrecision(map.getZoom());
91       input.val(ll.lat.toFixed(precision) + ", " + ll.lng.toFixed(precision));
92       endpoint.latlng = ll;
93       endpoint.marker
94         .setLatLng(ll)
95         .addTo(map);
96     };
97
98     return endpoint;
99   }
100
101   function formatDistance(m) {
102     if (m < 1000) {
103       return Math.round(m) + "m";
104     } else if (m < 10000) {
105       return (m / 1000.0).toFixed(1) + "km";
106     } else {
107       return Math.round(m / 1000) + "km";
108     }
109   }
110
111   function formatTime(s) {
112     var m = Math.round(s / 60);
113     var h = Math.floor(m / 60);
114     m -= h * 60;
115     return h + ":" + (m < 10 ? '0' : '') + m;
116   }
117
118   function setEngine(id) {
119     engines.forEach(function(engine, i) {
120       if (engine.id == id) {
121         chosenEngine = engine;
122         select.val(i);
123       }
124     });
125   }
126
127   function getRoute() {
128     if (endpoints[0].awaitingGeocode || endpoints[1].awaitingGeocode) {
129       awaitingGeocode = true;
130       return;
131     }
132
133     var o = endpoints[0].latlng,
134         d = endpoints[1].latlng;
135
136     if (!o || !d) return;
137
138     var precision = OSM.zoomPrecision(map.getZoom());
139
140     OSM.router.replace("/directions?" + querystring.stringify({
141       engine: chosenEngine.id,
142       route: o.lat.toFixed(precision) + ',' + o.lng.toFixed(precision) + ';' +
143              d.lat.toFixed(precision) + ',' + d.lng.toFixed(precision)
144     }));
145
146     $(".directions_form .spinner").show();
147     awaitingRoute = true;
148
149     chosenEngine.getRoute([o, d], function (err, route) {
150       awaitingRoute = false;
151
152       $(".directions_form .spinner").hide();
153
154       if (err) {
155         map.removeLayer(polyline);
156
157         if (!dragging) {
158           alert(I18n.t('javascripts.directions.errors.no_route'));
159         }
160
161         return;
162       }
163
164       polyline
165         .setLatLngs(route.line)
166         .addTo(map);
167
168       map.setSidebarOverlaid(false);
169
170       if (!dragging) {
171         map.fitBounds(polyline.getBounds().pad(0.05));
172       }
173
174       var html = '<h2><a class="geolink" href="#">' +
175         '<span class="icon close"></span></a>' + I18n.t('javascripts.directions.directions') +
176         '</h2><p id="routing_summary">' +
177         I18n.t('javascripts.directions.distance') + ': ' + formatDistance(route.distance) + '. ' +
178         I18n.t('javascripts.directions.time') + ': ' + formatTime(route.time) + '.</p>' +
179         '<table id="turnbyturn" />';
180
181       $('#sidebar_content')
182         .html(html);
183
184       // Add each row
185       var cumulative = 0;
186       route.steps.forEach(function (step) {
187         var ll        = step[0],
188           direction   = step[1],
189           instruction = step[2],
190           dist        = step[3],
191           lineseg     = step[4];
192
193         cumulative += dist;
194
195         if (dist < 5) {
196           dist = "";
197         } else if (dist < 200) {
198           dist = Math.round(dist / 10) * 10 + "m";
199         } else if (dist < 1500) {
200           dist = Math.round(dist / 100) * 100 + "m";
201         } else if (dist < 5000) {
202           dist = Math.round(dist / 100) / 10 + "km";
203         } else {
204           dist = Math.round(dist / 1000) + "km";
205         }
206
207         var row = $("<tr class='turn'/>");
208         row.append("<td><div class='direction i" + direction + "'/></td> ");
209         row.append("<td class='instruction'>" + instruction);
210         row.append("<td class='distance'>" + dist);
211
212         row.on('click', function () {
213           popup
214             .setLatLng(ll)
215             .setContent("<p>" + instruction + "</p>")
216             .openOn(map);
217         });
218
219         row.hover(function () {
220           highlight
221             .setLatLngs(lineseg)
222             .addTo(map);
223         }, function () {
224           map.removeLayer(highlight);
225         });
226
227         $('#turnbyturn').append(row);
228       });
229
230       $('#sidebar_content').append('<p id="routing_credit">' +
231         I18n.t('javascripts.directions.instructions.courtesy', {link: chosenEngine.creditline}) +
232         '</p>');
233     });
234   }
235
236   var engines = OSM.Directions.engines;
237
238   engines.sort(function (a, b) {
239     a = I18n.t('javascripts.directions.engines.' + a.id);
240     b = I18n.t('javascripts.directions.engines.' + b.id);
241     return a.localeCompare(b);
242   });
243
244   var select = $('select.routing_engines');
245
246   engines.forEach(function(engine, i) {
247     select.append("<option value='" + i + "'>" + I18n.t('javascripts.directions.engines.' + engine.id) + "</option>");
248   });
249
250   setEngine('osrm_car');
251
252   select.on("change", function (e) {
253     chosenEngine = engines[e.target.selectedIndex];
254     if (map.hasLayer(polyline)) {
255       getRoute();
256     }
257   });
258
259   $(".directions_form").on("submit", function(e) {
260     e.preventDefault();
261     $("header").addClass("closed");
262     getRoute();
263   });
264
265   $(".routing_marker").on('dragstart', function (e) {
266     e.originalEvent.dataTransfer.effectAllowed = 'move';
267     e.originalEvent.dataTransfer.setData('id', this.id);
268     var xo = e.originalEvent.clientX - $(e.target).offset().left;
269     var yo = e.originalEvent.clientY - $(e.target).offset().top;
270     e.originalEvent.dataTransfer.setData('offsetX', e.originalEvent.target.width / 2 - xo);
271     e.originalEvent.dataTransfer.setData('offsetY', e.originalEvent.target.height - yo);
272   });
273
274   var page = {};
275
276   page.pushstate = page.popstate = function() {
277     $(".search_form").hide();
278     $(".directions_form").show();
279
280     $("#map").on('dragend dragover', function (e) {
281       e.preventDefault();
282     });
283
284     $("#map").on('drop', function (e) {
285       e.preventDefault();
286       var oe = e.originalEvent;
287       var id = oe.dataTransfer.getData('id');
288       var pt = L.DomEvent.getMousePosition(oe, map.getContainer());  // co-ordinates of the mouse pointer at present
289       pt.x += Number(oe.dataTransfer.getData('offsetX'));
290       pt.y += Number(oe.dataTransfer.getData('offsetY'));
291       var ll = map.containerPointToLatLng(pt);
292       endpoints[id === 'marker_from' ? 0 : 1].setLatLng(ll);
293       getRoute();
294     });
295
296     var params = querystring.parse(location.search.substring(1)),
297       route = (params.route || '').split(';');
298
299     if (params.engine) {
300       setEngine(params.engine);
301     }
302
303     if (params.from) {
304       $(".directions_form input[name='route_from']").val(params.from);
305     }
306
307     var o = route[0] && L.latLng(route[0].split(',')),
308         d = route[1] && L.latLng(route[1].split(','));
309
310     if (o) endpoints[0].setLatLng(o);
311     if (d) endpoints[1].setLatLng(d);
312
313     map.setSidebarOverlaid(!o || !d);
314
315     getRoute();
316   };
317
318   page.load = function() {
319     page.pushstate();
320   };
321
322   page.unload = function() {
323     $(".search_form").show();
324     $(".directions_form").hide();
325     $("#map").off('dragend dragover drop');
326
327     map
328       .removeLayer(popup)
329       .removeLayer(polyline)
330       .removeLayer(endpoints[0].marker)
331       .removeLayer(endpoints[1].marker);
332   };
333
334   return page;
335 };
336
337 OSM.Directions.engines = [];
338
339 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
340   if (document.location.protocol == "http:" || supportsHTTPS) {
341     OSM.Directions.engines.push(engine);
342   }
343 };