]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index.js
Merge remote-tracking branch 'upstream/master' into routing
[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 index/directions
17 //= require index/changeset
18 //= require router
19
20 $(document).ready(function () {
21   var loaderTimeout;
22
23   OSM.loadSidebarContent = function(path, callback) {
24     map.setSidebarOverlaid(false);
25
26     clearTimeout(loaderTimeout);
27
28     loaderTimeout = setTimeout(function() {
29       $('#sidebar_loader').show();
30     }, 200);
31
32     // IE<10 doesn't respect Vary: X-Requested-With header, so
33     // prevent caching the XHR response as a full-page URL.
34     if (path.indexOf('?') >= 0) {
35       path += '&xhr=1'
36     } else {
37       path += '?xhr=1'
38     }
39
40     $('#sidebar_content')
41       .empty();
42
43     $.ajax({
44       url: path,
45       dataType: "html",
46       complete: function(xhr) {
47         clearTimeout(loaderTimeout);
48         $('#flash').empty();
49         $('#sidebar_loader').hide();
50
51         var content = $(xhr.responseText);
52
53         if (xhr.getResponseHeader('X-Page-Title')) {
54           var title = xhr.getResponseHeader('X-Page-Title');
55           document.title = decodeURIComponent(escape(title));
56         }
57
58         $('head')
59           .find('link[type="application/atom+xml"]')
60           .remove();
61
62         $('head')
63           .append(content.filter('link[type="application/atom+xml"]'));
64
65         $('#sidebar_content').html(content.not('link[type="application/atom+xml"]'));
66
67         if (callback) {
68           callback();
69         }
70       }
71     });
72   };
73
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_sotm') == 'hide') {
161     $('#sotm').hide();
162   }
163
164   $('#sotm .close').on('click', function() {
165     $('#sotm').hide();
166     $.cookie("_osm_sotm", 'hide', { expires: expiry });
167   });
168
169   if ($.cookie('_osm_welcome') == 'hide') {
170     $('.welcome').hide();
171   }
172
173   $('.welcome .close').on('click', function() {
174     $('.welcome').hide();
175     $.cookie("_osm_welcome", 'hide', { expires: expiry });
176   });
177
178   if (OSM.PIWIK) {
179     map.on('layeradd', function (e) {
180       if (e.layer.options) {
181         var goal = OSM.PIWIK.goals[e.layer.options.keyid];
182
183         if (goal) {
184           $('body').trigger('piwikgoal', goal);
185         }
186       }
187     });
188   }
189
190   if (params.bounds) {
191     map.fitBounds(params.bounds);
192   } else {
193     map.setView([params.lat, params.lon], params.zoom);
194   }
195
196   var marker = L.marker([0, 0], {icon: getUserIcon()});
197
198   if (params.marker) {
199     marker.setLatLng([params.mlat, params.mlon]).addTo(map);
200   }
201
202   $("#homeanchor").on("click", function(e) {
203     e.preventDefault();
204
205     var data = $(this).data(),
206       center = L.latLng(data.lat, data.lon);
207
208     map.setView(center, data.zoom);
209     marker.setLatLng(center).addTo(map);
210   });
211
212   $("a[data-editor=remote]").click(function(e) {
213     var params = OSM.mapParams(this.search);
214     remoteEditHandler(map.getBounds(), params.object);
215     e.preventDefault();
216   });
217
218   if (OSM.params().edit_help) {
219     $('#editanchor')
220       .removeAttr('title')
221       .tooltip({
222         placement: 'bottom',
223         title: I18n.t('javascripts.edit_help')
224       })
225       .tooltip('show');
226
227     $('body').one('click', function() {
228       $('#editanchor').tooltip('hide');
229     });
230   }
231
232   OSM.Index = function(map) {
233     var page = {};
234
235     page.pushstate = page.popstate = function() {
236       map.setSidebarOverlaid(true);
237       document.title = I18n.t('layouts.project_name.title');
238     };
239
240     page.load = function() {
241       if (!("autofocus" in document.createElement("input"))) {
242         $("#sidebar .search_form input[name=query]").focus();
243       }
244       return map.getState();
245     };
246
247     return page;
248   };
249
250   OSM.Browse = function(map, type) {
251     var page = {};
252
253     page.pushstate = page.popstate = function(path, id) {
254       OSM.loadSidebarContent(path, function() {
255         addObject(type, id);
256       });
257     };
258
259     page.load = function(path, id) {
260       addObject(type, id, true);
261     };
262
263     function addObject(type, id, center) {
264       var bounds = map.addObject({type: type, id: parseInt(id)}, function(bounds) {
265         if (!window.location.hash && bounds.isValid() &&
266             (center || !map.getBounds().contains(bounds))) {
267           OSM.router.withoutMoveListener(function () {
268             map.fitBounds(bounds);
269           });
270         }
271       });
272     }
273
274     page.unload = function() {
275       map.removeObject();
276     };
277
278     return page;
279   };
280
281   var history = OSM.History(map);
282
283   OSM.router = OSM.Router(map, {
284     "/":                           OSM.Index(map),
285     "/search":                     OSM.Search(map),
286     "/directions":                 OSM.Directions(map),
287     "/export":                     OSM.Export(map),
288     "/note/new":                   OSM.NewNote(map),
289     "/history/friends":            history,
290     "/history/nearby":             history,
291     "/history":                    history,
292     "/user/:display_name/history": history,
293     "/note/:id":                   OSM.Note(map),
294     "/node/:id(/history)":         OSM.Browse(map, 'node'),
295     "/way/:id(/history)":          OSM.Browse(map, 'way'),
296     "/relation/:id(/history)":     OSM.Browse(map, 'relation'),
297     "/changeset/:id":              OSM.Changeset(map)
298   });
299
300   if (OSM.preferred_editor == "remote" && document.location.pathname == "/edit") {
301     remoteEditHandler(map.getBounds(), params.object);
302     OSM.router.setCurrentPath("/");
303   }
304
305   OSM.router.load();
306
307   $(document).on("click", "a", function(e) {
308     if (e.isDefaultPrevented() || e.isPropagationStopped())
309       return;
310
311     // Open links in a new tab as normal.
312     if (e.which > 1 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey)
313       return;
314
315     // Ignore cross-protocol and cross-origin links.
316     if (location.protocol !== this.protocol || location.host !== this.host)
317       return;
318
319     if (OSM.router.route(this.pathname + this.search + this.hash))
320       e.preventDefault();
321   });
322
323   $(".search_form").on("submit", function(e) {
324     e.preventDefault();
325     $("header").addClass("closed");
326     var query = $(this).find("input[name=query]").val();
327     if (query) {
328       OSM.router.route("/search?query=" + encodeURIComponent(query) + OSM.formatHash(map));
329     } else {
330       OSM.router.route("/");
331     }
332   });
333
334   $(".describe_location").on("click", function(e) {
335     e.preventDefault();
336     var center = map.getCenter().wrap(),
337       precision = OSM.zoomPrecision(map.getZoom());
338     OSM.router.route("/search?query=" + encodeURIComponent(
339       center.lat.toFixed(precision) + "," + center.lng.toFixed(precision)
340     ));
341   });
342 });