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