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