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