]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index.js
Refer to the id for the distance/time summary
[rails.git] / app / assets / javascripts / index.js
1 //= require_self
2 //= require leaflet.sidebar
3 //= require leaflet.locate
4 //= require leaflet.layers
5 //= require leaflet.key
6 //= require leaflet.note
7 //= require leaflet.share
8 //= require leaflet.polyline
9 //= require index/search
10 //= require index/browse
11 //= require index/export
12 //= require index/notes
13 //= require index/history
14 //= require index/note
15 //= require index/new_note
16 //= require router
17 //= require routing
18 //= require_tree ./routing_engines
19
20 (function() {
21   var loaderTimeout;
22
23   OSM.loadSidebarContent = function(path, callback) {
24     clearTimeout(loaderTimeout);
25
26     loaderTimeout = setTimeout(function() {
27       $('#sidebar_loader').show();
28     }, 200);
29
30     // IE<10 doesn't respect Vary: X-Requested-With header, so
31     // prevent caching the XHR response as a full-page URL.
32     if (path.indexOf('?') >= 0) {
33       path += '&xhr=1'
34     } else {
35       path += '?xhr=1'
36     }
37
38     $('#sidebar_content')
39       .empty();
40
41     $.ajax({
42       url: path,
43       dataType: "html",
44       complete: function(xhr) {
45         clearTimeout(loaderTimeout);
46         $('#flash').empty();
47         $('#sidebar_loader').hide();
48
49         var content = $(xhr.responseText);
50
51         if (xhr.getResponseHeader('X-Page-Title')) {
52           var title = xhr.getResponseHeader('X-Page-Title');
53           document.title = decodeURIComponent(escape(title));
54         }
55
56         $('head')
57           .find('link[type="application/atom+xml"]')
58           .remove();
59
60         $('head')
61           .append(content.filter('link[type="application/atom+xml"]'));
62
63         $('#sidebar_content').html(content.not('link[type="application/atom+xml"]'));
64
65         if (callback) {
66           callback();
67         }
68       }
69     });
70   };
71 })();
72
73 $(document).ready(function () {
74   var params = OSM.mapParams();
75
76   var map = new L.OSM.Map("map", {
77     zoomControl: false,
78     layerControl: false
79   });
80
81   map.attributionControl.setPrefix('');
82
83   map.updateLayers(params.layers);
84
85   map.on("baselayerchange", function (e) {
86     if (map.getZoom() > e.layer.options.maxZoom) {
87       map.setView(map.getCenter(), e.layer.options.maxZoom, { reset: true });
88     }
89   });
90
91   var position = $('html').attr('dir') === 'rtl' ? 'topleft' : 'topright';
92
93   L.OSM.zoom({position: position})
94     .addTo(map);
95
96   L.control.locate({
97     position: position,
98     strings: {
99       title: I18n.t('javascripts.map.locate.title'),
100       popup: I18n.t('javascripts.map.locate.popup')
101     }
102   }).addTo(map);
103
104   var sidebar = L.OSM.sidebar('#map-ui')
105     .addTo(map);
106
107   L.OSM.layers({
108     position: position,
109     layers: map.baseLayers,
110     sidebar: sidebar
111   }).addTo(map);
112
113   L.OSM.key({
114     position: position,
115     sidebar: sidebar
116   }).addTo(map);
117
118   L.OSM.share({
119     position: position,
120     sidebar: sidebar,
121     short: true
122   }).addTo(map);
123
124   L.OSM.note({
125     position: position,
126     sidebar: sidebar
127   }).addTo(map);
128
129   L.control.scale()
130     .addTo(map);
131
132   if (OSM.STATUS != 'api_offline' && OSM.STATUS != 'database_offline') {
133     initializeNotes(map);
134     if (params.layers.indexOf(map.noteLayer.options.code) >= 0) {
135       map.addLayer(map.noteLayer);
136     }
137
138     initializeBrowse(map);
139     if (params.layers.indexOf(map.dataLayer.options.code) >= 0) {
140       map.addLayer(map.dataLayer);
141     }
142   }
143
144   $('.leaflet-control .control-button').tooltip({placement: 'left', container: 'body'});
145
146   var expiry = new Date();
147   expiry.setYear(expiry.getFullYear() + 10);
148
149   map.on('moveend layeradd layerremove', function() {
150     updateLinks(
151       map.getCenter().wrap(),
152       map.getZoom(),
153       map.getLayersCode(),
154       map._object);
155
156     $.removeCookie("_osm_location");
157     $.cookie("_osm_location", OSM.locationCookie(map), { expires: expiry, path: "/" });
158   });
159
160   if ($.cookie('_osm_welcome') == 'hide') {
161     $('.welcome').hide();
162   }
163
164   $('.welcome .close').on('click', function() {
165     $('.welcome').hide();
166     $.cookie("_osm_welcome", 'hide', { expires: expiry });
167   });
168
169   if (OSM.PIWIK) {
170     map.on('layeradd', function (e) {
171       if (e.layer.options) {
172         var goal = OSM.PIWIK.goals[e.layer.options.keyid];
173
174         if (goal) {
175           $('body').trigger('piwikgoal', goal);
176         }
177       }
178     });
179   }
180
181   if (params.bounds) {
182     map.fitBounds(params.bounds);
183   } else {
184     map.setView([params.lat, params.lon], params.zoom);
185   }
186
187   var marker = L.marker([0, 0], {icon: getUserIcon()});
188
189   if (params.marker) {
190     marker.setLatLng([params.mlat, params.mlon]).addTo(map);
191   }
192
193   $("#homeanchor").on("click", function(e) {
194     e.preventDefault();
195
196     var data = $(this).data(),
197       center = L.latLng(data.lat, data.lon);
198
199     map.setView(center, data.zoom);
200     marker.setLatLng(center).addTo(map);
201   });
202
203   $("a[data-editor=remote]").click(function(e) {
204     var params = OSM.mapParams(this.search);
205     remoteEditHandler(map.getBounds(), params.object);
206     e.preventDefault();
207   });
208
209   if (OSM.params().edit_help) {
210     $('#editanchor')
211       .removeAttr('title')
212       .tooltip({
213         placement: 'bottom',
214         title: I18n.t('javascripts.edit_help')
215       })
216       .tooltip('show');
217
218     $('body').one('click', function() {
219       $('#editanchor').tooltip('hide');
220     });
221   }
222
223   OSM.Index = function(map) {
224     var page = {};
225
226     page.pushstate = function() {
227       $("#content").addClass("overlay-sidebar");
228       map.invalidateSize({pan: false})
229         .panBy([-350, 0], {animate: false});
230       document.title = I18n.t('layouts.project_name.title');
231     };
232
233     page.load = function() {
234       if (!("autofocus" in document.createElement("input"))) {
235         $("#sidebar .search_form input[name=query]").focus();
236       }
237       return map.getState();
238     };
239
240     page.popstate = function() {
241       $("#content").addClass("overlay-sidebar");
242       map.invalidateSize({pan: false});
243       document.title = I18n.t('layouts.project_name.title');
244     };
245
246     page.unload = function() {
247       map.panBy([350, 0], {animate: false});
248       $("#content").removeClass("overlay-sidebar");
249       map.invalidateSize({pan: false});
250     };
251
252     return page;
253   };
254
255   OSM.Browse = function(map, type) {
256     var page = {};
257
258     page.pushstate = page.popstate = function(path, id) {
259       OSM.loadSidebarContent(path, function() {
260         addObject(type, id);
261       });
262     };
263
264     page.load = function(path, id) {
265       addObject(type, id, true);
266     };
267
268     function addObject(type, id, center) {
269       var bounds = map.addObject({type: type, id: parseInt(id)}, function(bounds) {
270         if (!window.location.hash && bounds.isValid()) {
271           OSM.router.moveListenerOff();
272           map.once('moveend', OSM.router.moveListenerOn);
273           if (center || !map.getBounds().contains(bounds)) map.fitBounds(bounds);
274         }
275       });
276     }
277
278     page.unload = function() {
279       map.removeObject();
280     };
281
282     return page;
283   };
284
285   var history = OSM.History(map);
286
287   OSM.router = OSM.Router(map, {
288     "/":                           OSM.Index(map),
289     "/search":                     OSM.Search(map),
290     "/export":                     OSM.Export(map),
291     "/note/new":                   OSM.NewNote(map),
292     "/history/friends":            history,
293     "/history/nearby":             history,
294     "/history":                    history,
295     "/user/:display_name/history": history,
296     "/note/:id":                   OSM.Note(map),
297     "/node/:id(/history)":         OSM.Browse(map, 'node'),
298     "/way/:id(/history)":          OSM.Browse(map, 'way'),
299     "/relation/:id(/history)":     OSM.Browse(map, 'relation'),
300     "/changeset/:id":              OSM.Browse(map, 'changeset')
301   });
302
303   if (OSM.preferred_editor == "remote" && document.location.pathname == "/edit") {
304     remoteEditHandler(map.getBounds(), params.object);
305     OSM.router.setCurrentPath("/");
306   }
307
308   OSM.router.load();
309
310   $(document).on("click", "a", function(e) {
311     if (e.isDefaultPrevented() || e.isPropagationStopped())
312       return;
313
314     // Open links in a new tab as normal.
315     if (e.which > 1 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey)
316       return;
317
318     // Ignore cross-protocol and cross-origin links.
319     if (location.protocol !== this.protocol || location.host !== this.host)
320       return;
321
322     if (OSM.router.route(this.pathname + this.search + this.hash))
323       e.preventDefault();
324   });
325
326   $(".search_form").on("submit", function(e) {
327     e.preventDefault();
328     if ($(".query_wrapper.routing").is(":visible")) {
329       // Routing
330       OSM.routing.requestRoute(true, true);
331     } else {
332       // Search
333       $("header").addClass("closed");
334       var query = $(this).find("input[name=query]").val();
335       if (query) {
336         OSM.router.route("/search?query=" + encodeURIComponent(query) + OSM.formatHash(map));
337       } else {
338         OSM.router.route("/" + OSM.formatHash(map));
339       }
340     }
341   });
342
343   $(".describe_location").on("click", function(e) {
344     e.preventDefault();
345     var precision = OSM.zoomPrecision(map.getZoom());
346     OSM.router.route("/search?query=" + encodeURIComponent(
347       map.getCenter().lat.toFixed(precision) + "," +
348       map.getCenter().lng.toFixed(precision)));
349   });
350
351   OSM.routing = OSM.Routing(map,'OSM.routing',$('.query_wrapper.routing'));
352   OSM.routing.chooseEngine('javascripts.directions.engines.osrm_car');
353
354   $(".get_directions").on("click",function(e) {
355     e.preventDefault();
356     $(".search").hide();
357     $(".routing").show();
358     $(".query_wrapper.routing [name=route_from]").focus();
359     $("#map").on('dragend dragover',function(e) { e.preventDefault(); });
360     $("#map").on('drop',function(e) { OSM.routing.handleDrop(e); e.preventDefault(); });
361     $(".routing_marker").on('dragstart',function(e) {
362       e.originalEvent.dataTransfer.effectAllowed = 'move';
363       e.originalEvent.dataTransfer.setData('id', this.id);
364       e.originalEvent.dataTransfer.setData('offsetX', e.originalEvent.target.width/2 - (e.originalEvent.x-e.target.x));
365       e.originalEvent.dataTransfer.setData('offsetY', e.originalEvent.target.height  - (e.originalEvent.y-e.target.y));
366     });
367   });
368
369   $(".close_directions").on("click",function(e) {
370     e.preventDefault();
371     $(".search").show();
372     $(".routing").hide();
373     OSM.routing.close();
374     $("#map").off('dragend drop dragover');
375     $(".routing_marker").off('dragstart');
376     $(".query_wrapper.search [name=query]").focus();
377   });
378
379 });