2 //= require_tree ./directions
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
10 var popup = L.popup();
12 var polyline = L.polyline([], {
18 var highlight = L.polyline([], {
25 Endpoint($("input[name='route_from']"), OSM.MARKER_GREEN),
26 Endpoint($("input[name='route_to']"), OSM.MARKER_RED)
29 function Endpoint(input, iconUrl) {
32 endpoint.marker = L.marker([0, 0], {
37 popupAnchor: [1, -34],
38 shadowUrl: OSM.MARKER_SHADOW,
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)) {
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);
60 endpoint.setValue = function(value) {
61 endpoint.value = value;
62 delete endpoint.latlng;
64 endpoint.getGeocode();
67 endpoint.getGeocode = function() {
68 // if no one has entered a value yet, then we can't geocode, so don't
70 if (!endpoint.value) {
74 endpoint.awaitingGeocode = true;
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'));
84 input.val(json[0].display_name);
86 endpoint.latlng = L.latLng(json[0]);
88 .setLatLng(endpoint.latlng)
91 if (awaitingGeocode) {
92 awaitingGeocode = false;
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;
111 $(".directions_form .close").on("click", function(e) {
113 var route_from = endpoints[0].value;
115 OSM.router.route("/?query=" + encodeURIComponent(route_from) + OSM.formatHash(map));
117 OSM.router.route("/" + OSM.formatHash(map));
121 function formatDistance(m) {
123 return Math.round(m) + "m";
124 } else if (m < 10000) {
125 return (m / 1000.0).toFixed(1) + "km";
127 return Math.round(m / 1000) + "km";
131 function formatTime(s) {
132 var m = Math.round(s / 60);
133 var h = Math.floor(m / 60);
135 return h + ":" + (m < 10 ? '0' : '') + m;
138 function setEngine(id) {
139 engines.forEach(function(engine, i) {
140 if (engine.id === id) {
141 chosenEngine = engine;
147 function getRoute() {
148 // Cancel any route that is already in progress
149 if (awaitingRoute) awaitingRoute.abort();
151 // go fetch geocodes for any endpoints which have not already
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;
160 if (endpoints[0].awaitingGeocode || endpoints[1].awaitingGeocode) {
161 awaitingGeocode = true;
165 var o = endpoints[0].latlng,
166 d = endpoints[1].latlng;
168 if (!o || !d) return;
169 $("header").addClass("closed");
171 var precision = OSM.zoomPrecision(map.getZoom());
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)
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
182 $('#sidebar_content').html($('.directions_form .loader_copy').html());
183 map.setSidebarOverlaid(false);
185 awaitingRoute = chosenEngine.getRoute([o, d], function (err, route) {
186 awaitingRoute = null;
189 map.removeLayer(polyline);
192 alert(I18n.t('javascripts.directions.errors.no_route'));
199 .setLatLngs(route.line)
203 map.fitBounds(polyline.getBounds().pad(0.05));
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" />';
213 $('#sidebar_content')
218 route.steps.forEach(function (step) {
221 instruction = step[2],
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";
236 dist = Math.round(dist / 1000) + "km";
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);
244 row.on('click', function () {
247 .setContent("<p>" + instruction + "</p>")
251 row.hover(function () {
256 map.removeLayer(highlight);
259 $('#turnbyturn').append(row);
262 $('#sidebar_content').append('<p id="routing_credit">' +
263 I18n.t('javascripts.directions.instructions.courtesy', {link: chosenEngine.creditline}) +
266 $('#sidebar_content a.geolink').on('click', function(e) {
268 map.removeLayer(polyline);
269 $('#sidebar_content').html('');
270 map.setSidebarOverlaid(true);
271 // TODO: collapse width of sidebar back to previous
276 var engines = OSM.Directions.engines;
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);
284 var select = $('select.routing_engines');
286 engines.forEach(function(engine, i) {
287 select.append("<option value='" + i + "'>" + I18n.t('javascripts.directions.engines.' + engine.id) + "</option>");
290 setEngine('osrm_car');
292 select.on("change", function (e) {
293 chosenEngine = engines[e.target.selectedIndex];
294 if (map.hasLayer(polyline)) {
299 $(".directions_form").on("submit", function(e) {
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);
313 page.pushstate = page.popstate = function() {
314 $(".search_form").hide();
315 $(".directions_form").show();
317 $("#map").on('dragend dragover', function (e) {
321 $("#map").on('drop', function (e) {
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
327 var ll = map.containerPointToLatLng(pt);
328 endpoints[type === 'from' ? 0 : 1].setLatLng(ll);
332 var params = querystring.parse(location.search.substring(1)),
333 route = (params.route || '').split(';');
336 setEngine(params.engine);
340 endpoints[0].setValue(params.from);
341 endpoints[1].setValue("");
343 endpoints[0].setValue("");
344 endpoints[1].setValue("");
347 var o = route[0] && L.latLng(route[0].split(',')),
348 d = route[1] && L.latLng(route[1].split(','));
350 if (o) endpoints[0].setLatLng(o);
351 if (d) endpoints[1].setLatLng(d);
353 map.setSidebarOverlaid(!o || !d);
358 page.load = function() {
362 page.unload = function() {
363 $(".search_form").show();
364 $(".directions_form").hide();
365 $("#map").off('dragend dragover drop');
369 .removeLayer(polyline)
370 .removeLayer(endpoints[0].marker)
371 .removeLayer(endpoints[1].marker);
377 OSM.Directions.engines = [];
379 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
380 if (document.location.protocol === "http:" || supportsHTTPS) {
381 OSM.Directions.engines.push(engine);