]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/directions.js.erb
ee2cce667c113d5f4aa2372957205af56bfa4c33
[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($("#content input[name='route_from']"), <%= asset_path('marker-green.png').to_json %>),
36     Endpoint($("#content 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.getGeocode();
66     });
67
68     endpoint.getGeocode = function() {
69       var value = input.val();
70
71       // if no one has entered a value yet, then we can't geocode, so don't
72       // even try.
73       if (!value) {
74         return;
75       }
76
77       endpoint.awaitingGeocode = true;
78
79       $.getJSON('<%= NOMINATIM_URL %>search?q=' + encodeURIComponent(value) + '&format=json', function (json) {
80         endpoint.awaitingGeocode = false;
81         endpoint.hasGeocode = true;
82
83         if (json.length == 0) {
84           alert(I18n.t('javascripts.directions.errors.no_place'));
85           return;
86         }
87
88         input.val(json[0].display_name);
89
90         endpoint.latlng = L.latLng(json[0]);
91         endpoint.marker
92           .setLatLng(endpoint.latlng)
93           .addTo(map);
94
95         if (awaitingGeocode) {
96           awaitingGeocode = false;
97           getRoute();
98         }
99       });
100     }
101
102     endpoint.setLatLng = function (ll) {
103       var precision = OSM.zoomPrecision(map.getZoom());
104       input.val(ll.lat.toFixed(precision) + ", " + ll.lng.toFixed(precision));
105       endpoint.hasGeocode = true;
106       endpoint.latlng = ll;
107       endpoint.marker
108         .setLatLng(ll)
109         .addTo(map);
110     };
111
112     return endpoint;
113   }
114
115   function formatDistance(m) {
116     if (m < 1000) {
117       return Math.round(m) + "m";
118     } else if (m < 10000) {
119       return (m / 1000.0).toFixed(1) + "km";
120     } else {
121       return Math.round(m / 1000) + "km";
122     }
123   }
124
125   function formatTime(s) {
126     var m = Math.round(s / 60);
127     var h = Math.floor(m / 60);
128     m -= h * 60;
129     return h + ":" + (m < 10 ? '0' : '') + m;
130   }
131
132   function setEngine(id) {
133     engines.forEach(function(engine, i) {
134       if (engine.id == id) {
135         chosenEngine = engine;
136         select.val(i);
137       }
138     });
139   }
140
141   function getRoute() {
142     // go fetch geocodes for any endpoints which have not already
143     // been geocoded.
144     for (var ep_i = 0; ep_i < 2; ++ep_i) {
145       var endpoint = endpoints[ep_i];
146       if (!endpoint.hasGeocode && !endpoint.awaitingGeocode) {
147         endpoint.getGeocode();
148         awaitingGeocode = true;
149       }
150     }
151     if (endpoints[0].awaitingGeocode || endpoints[1].awaitingGeocode) {
152       awaitingGeocode = true;
153       return;
154     }
155
156     var o = endpoints[0].latlng,
157         d = endpoints[1].latlng;
158
159     if (!o || !d) return;
160
161     var precision = OSM.zoomPrecision(map.getZoom());
162
163     OSM.router.replace("/directions?" + querystring.stringify({
164       engine: chosenEngine.id,
165       route: o.lat.toFixed(precision) + ',' + o.lng.toFixed(precision) + ';' +
166              d.lat.toFixed(precision) + ',' + d.lng.toFixed(precision)
167     }));
168
169     $(".directions_form .spinner").show();
170     awaitingRoute = true;
171
172     chosenEngine.getRoute([o, d], function (err, route) {
173       awaitingRoute = false;
174
175       $(".directions_form .spinner").hide();
176
177       if (err) {
178         map.removeLayer(polyline);
179
180         if (!dragging) {
181           alert(I18n.t('javascripts.directions.errors.no_route'));
182         }
183
184         return;
185       }
186
187       polyline
188         .setLatLngs(route.line)
189         .addTo(map);
190
191       map.setSidebarOverlaid(false);
192
193       if (!dragging) {
194         map.fitBounds(polyline.getBounds().pad(0.05));
195       }
196
197       var html = '<h2><a class="geolink" href="#">' +
198         '<span class="icon close"></span></a>' + I18n.t('javascripts.directions.directions') +
199         '</h2><p id="routing_summary">' +
200         I18n.t('javascripts.directions.distance') + ': ' + formatDistance(route.distance) + '. ' +
201         I18n.t('javascripts.directions.time') + ': ' + formatTime(route.time) + '.</p>' +
202         '<table id="turnbyturn" />';
203
204       $('#sidebar_content')
205         .html(html);
206
207       // Add each row
208       var cumulative = 0;
209       route.steps.forEach(function (step) {
210         var ll        = step[0],
211           direction   = step[1],
212           instruction = step[2],
213           dist        = step[3],
214           lineseg     = step[4];
215
216         cumulative += dist;
217
218         if (dist < 5) {
219           dist = "";
220         } else if (dist < 200) {
221           dist = Math.round(dist / 10) * 10 + "m";
222         } else if (dist < 1500) {
223           dist = Math.round(dist / 100) * 100 + "m";
224         } else if (dist < 5000) {
225           dist = Math.round(dist / 100) / 10 + "km";
226         } else {
227           dist = Math.round(dist / 1000) + "km";
228         }
229
230         var row = $("<tr class='turn'/>");
231         row.append("<td><div class='direction i" + direction + "'/></td> ");
232         row.append("<td class='instruction'>" + instruction);
233         row.append("<td class='distance'>" + dist);
234
235         row.on('click', function () {
236           popup
237             .setLatLng(ll)
238             .setContent("<p>" + instruction + "</p>")
239             .openOn(map);
240         });
241
242         row.hover(function () {
243           highlight
244             .setLatLngs(lineseg)
245             .addTo(map);
246         }, function () {
247           map.removeLayer(highlight);
248         });
249
250         $('#turnbyturn').append(row);
251       });
252
253       $('#sidebar_content').append('<p id="routing_credit">' +
254         I18n.t('javascripts.directions.instructions.courtesy', {link: chosenEngine.creditline}) +
255         '</p>');
256     });
257   }
258
259   var engines = OSM.Directions.engines;
260
261   engines.sort(function (a, b) {
262     a = I18n.t('javascripts.directions.engines.' + a.id);
263     b = I18n.t('javascripts.directions.engines.' + b.id);
264     return a.localeCompare(b);
265   });
266
267   var select = $('select.routing_engines');
268
269   engines.forEach(function(engine, i) {
270     select.append("<option value='" + i + "'>" + I18n.t('javascripts.directions.engines.' + engine.id) + "</option>");
271   });
272
273   setEngine('osrm_car');
274
275   select.on("change", function (e) {
276     chosenEngine = engines[e.target.selectedIndex];
277     if (map.hasLayer(polyline)) {
278       getRoute();
279     }
280   });
281
282   $(".directions_form").on("submit", function(e) {
283     e.preventDefault();
284     $("header").addClass("closed");
285     getRoute();
286   });
287
288   $(".routing_marker").on('dragstart', function (e) {
289     e.originalEvent.dataTransfer.effectAllowed = 'move';
290     e.originalEvent.dataTransfer.setData('id', this.id);
291     var xo = e.originalEvent.clientX - $(e.target).offset().left;
292     var yo = e.originalEvent.clientY - $(e.target).offset().top;
293     e.originalEvent.dataTransfer.setData('offsetX', e.originalEvent.target.width / 2 - xo);
294     e.originalEvent.dataTransfer.setData('offsetY', e.originalEvent.target.height - yo);
295   });
296
297   var page = {};
298
299   page.pushstate = page.popstate = function() {
300     $(".search_form").hide();
301     $(".directions_form").show();
302
303     $("#map").on('dragend dragover', function (e) {
304       e.preventDefault();
305     });
306
307     $("#map").on('drop', function (e) {
308       e.preventDefault();
309       var oe = e.originalEvent;
310       var id = oe.dataTransfer.getData('id');
311       var pt = L.DomEvent.getMousePosition(oe, map.getContainer());  // co-ordinates of the mouse pointer at present
312       pt.x += Number(oe.dataTransfer.getData('offsetX'));
313       pt.y += Number(oe.dataTransfer.getData('offsetY'));
314       var ll = map.containerPointToLatLng(pt);
315       endpoints[id === 'marker_from' ? 0 : 1].setLatLng(ll);
316       getRoute();
317     });
318
319     var params = querystring.parse(location.search.substring(1)),
320       route = (params.route || '').split(';');
321
322     if (params.engine) {
323       setEngine(params.engine);
324     }
325
326     if (params.from) {
327       $(".directions_form input[name='route_from']").val(params.from);
328     }
329
330     var o = route[0] && L.latLng(route[0].split(',')),
331         d = route[1] && L.latLng(route[1].split(','));
332
333     if (o) endpoints[0].setLatLng(o);
334     if (d) endpoints[1].setLatLng(d);
335
336     map.setSidebarOverlaid(!o || !d);
337
338     getRoute();
339   };
340
341   page.load = function() {
342     page.pushstate();
343   };
344
345   page.unload = function() {
346     $(".search_form").show();
347     $(".directions_form").hide();
348     $("#map").off('dragend dragover drop');
349
350     map
351       .removeLayer(popup)
352       .removeLayer(polyline)
353       .removeLayer(endpoints[0].marker)
354       .removeLayer(endpoints[1].marker);
355   };
356
357   return page;
358 };
359
360 OSM.Directions.engines = [];
361
362 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
363   if (document.location.protocol == "http:" || supportsHTTPS) {
364     OSM.Directions.engines.push(engine);
365   }
366 };