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