]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/leaflet.map.js
Merge branch 'master' into notes-search
[rails.git] / app / assets / javascripts / leaflet.map.js
1 L.extend(L.LatLngBounds.prototype, {
2   getSize: function () {
3     return (this._northEast.lat - this._southWest.lat) *
4            (this._northEast.lng - this._southWest.lng);
5   },
6
7   wrap: function () {
8     return new L.LatLngBounds(this._southWest.wrap(), this._northEast.wrap());
9   }
10 });
11
12 L.OSM.Map = L.Map.extend({
13   initialize: function(id, options) {
14     L.Map.prototype.initialize.call(this, id, options);
15
16     var copyright = I18n.t('javascripts.map.copyright', {copyright_url: '/copyright'});
17     var donate = I18n.t('javascripts.map.donate_link_text', {donate_url: 'https://donate.openstreetmap.org'});
18
19     this.baseLayers = [];
20
21     this.baseLayers.push(new L.OSM.Mapnik({
22       attribution: copyright + " ♥ " + donate,
23       code: "M",
24       keyid: "mapnik",
25       name: I18n.t("javascripts.map.base.standard")
26     }));
27
28     if (OSM.THUNDERFOREST_KEY) {
29       this.baseLayers.push(new L.OSM.CycleMap({
30         attribution: copyright + ". Tiles courtesy of <a href='https://www.thunderforest.com/' target='_blank'>Andy Allan</a>",
31         apikey: OSM.THUNDERFOREST_KEY,
32         code: "C",
33         keyid: "cyclemap",
34         name: I18n.t("javascripts.map.base.cycle_map")
35       }));
36
37       this.baseLayers.push(new L.OSM.TransportMap({
38         attribution: copyright + ". Tiles courtesy of <a href='https://www.thunderforest.com/' target='_blank'>Andy Allan</a>",
39         apikey: OSM.THUNDERFOREST_KEY,
40         code: "T",
41         keyid: "transportmap",
42         name: I18n.t("javascripts.map.base.transport_map")
43       }));
44     }
45
46     this.baseLayers.push(new L.OSM.HOT({
47       attribution: copyright + ". Tiles style by <a href='https://www.hotosm.org/' target='_blank'>Humanitarian OpenStreetMap Team</a>" + " hosted by <a href='https://openstreetmap.fr/' target='_blank'>OpenStreetMap France</a>",
48       code: "H",
49       keyid: "hot",
50       name: I18n.t("javascripts.map.base.hot")
51     }));
52
53     this.noteLayer = new L.FeatureGroup();
54     this.noteLayer.options = {code: 'N'};
55
56     this.dataLayer = new L.OSM.DataLayer(null);
57     this.dataLayer.options.code = 'D';
58
59     this.gpsLayer = new L.OSM.GPS({
60       pane: "overlayPane",
61       code: "G",
62       name: I18n.t("javascripts.map.base.gps")
63     });
64
65     this.on("layeradd", function (event) {
66       if (this.baseLayers.indexOf(event.layer) >= 0) {
67         this.setMaxZoom(event.layer.options.maxZoom);
68       }
69     });
70   },
71
72   updateLayers: function(layerParam) {
73     layerParam = layerParam || "M";
74     var layersAdded = "";
75
76     for (var i = this.baseLayers.length - 1; i >= 0; i--) {
77       if (layerParam.indexOf(this.baseLayers[i].options.code) >= 0) {
78         this.addLayer(this.baseLayers[i]);
79         layersAdded = layersAdded + this.baseLayers[i].options.code;
80       } else if (i === 0 && layersAdded === "") {
81         this.addLayer(this.baseLayers[i]);
82       } else {
83         this.removeLayer(this.baseLayers[i]);
84       }
85     }
86   },
87
88   getLayersCode: function () {
89     var layerConfig = '';
90     for (var i in this._layers) { // TODO: map.eachLayer
91       var layer = this._layers[i];
92       if (layer.options && layer.options.code) {
93         layerConfig += layer.options.code;
94       }
95     }
96     return layerConfig;
97   },
98
99   getMapBaseLayerId: function () {
100     for (var i in this._layers) { // TODO: map.eachLayer
101       var layer = this._layers[i];
102       if (layer.options && layer.options.keyid) return layer.options.keyid;
103     }
104   },
105
106   getUrl: function(marker) {
107     var precision = OSM.zoomPrecision(this.getZoom()),
108         params = {};
109
110     if (marker && this.hasLayer(marker)) {
111       var latLng = marker.getLatLng().wrap();
112       params.mlat = latLng.lat.toFixed(precision);
113       params.mlon = latLng.lng.toFixed(precision);
114     }
115
116     var url = window.location.protocol + '//' + OSM.SERVER_URL + '/',
117       query = querystring.stringify(params),
118       hash = OSM.formatHash(this);
119
120     if (query) url += '?' + query;
121     if (hash) url += hash;
122
123     return url;
124   },
125
126   getShortUrl: function(marker) {
127     var zoom = this.getZoom(),
128       latLng = marker && this.hasLayer(marker) ? marker.getLatLng().wrap() : this.getCenter().wrap(),
129       str = window.location.hostname.match(/^www\.openstreetmap\.org/i) ?
130         window.location.protocol + '//osm.org/go/' :
131         window.location.protocol + '//' + window.location.hostname + '/go/',
132       char_array = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_~",
133       x = Math.round((latLng.lng + 180.0) * ((1 << 30) / 90.0)),
134       y = Math.round((latLng.lat + 90.0) * ((1 << 30) / 45.0)),
135       // JavaScript only has to keep 32 bits of bitwise operators, so this has to be
136       // done in two parts. each of the parts c1/c2 has 30 bits of the total in it
137       // and drops the last 4 bits of the full 64 bit Morton code.
138       c1 = interlace(x >>> 17, y >>> 17), c2 = interlace((x >>> 2) & 0x7fff, (y >>> 2) & 0x7fff),
139       digit;
140
141     for (var i = 0; i < Math.ceil((zoom + 8) / 3.0) && i < 5; ++i) {
142       digit = (c1 >> (24 - 6 * i)) & 0x3f;
143       str += char_array.charAt(digit);
144     }
145     for (i = 5; i < Math.ceil((zoom + 8) / 3.0); ++i) {
146       digit = (c2 >> (24 - 6 * (i - 5))) & 0x3f;
147       str += char_array.charAt(digit);
148     }
149     for (i = 0; i < ((zoom + 8) % 3); ++i) str += "-";
150
151     // Called to interlace the bits in x and y, making a Morton code.
152     function interlace(x, y) {
153       x = (x | (x << 8)) & 0x00ff00ff;
154       x = (x | (x << 4)) & 0x0f0f0f0f;
155       x = (x | (x << 2)) & 0x33333333;
156       x = (x | (x << 1)) & 0x55555555;
157       y = (y | (y << 8)) & 0x00ff00ff;
158       y = (y | (y << 4)) & 0x0f0f0f0f;
159       y = (y | (y << 2)) & 0x33333333;
160       y = (y | (y << 1)) & 0x55555555;
161       return (x << 1) | y;
162     }
163
164     var params = {};
165     var layers = this.getLayersCode().replace('M', '');
166
167     if (layers) {
168       params.layers = layers;
169     }
170
171     if (marker && this.hasLayer(marker)) {
172       params.m = '';
173     }
174
175     if (this._object) {
176       params[this._object.type] = this._object.id;
177     }
178
179     var query = querystring.stringify(params);
180     if (query) {
181       str += '?' + query;
182     }
183
184     return str;
185   },
186
187   getGeoUri: function(marker) {
188     var precision = OSM.zoomPrecision(this.getZoom()),
189         latLng,
190         params = {};
191
192     if (marker && this.hasLayer(marker)) {
193       latLng = marker.getLatLng().wrap();
194     } else {
195       latLng = this.getCenter();
196     }
197
198     params.lat = latLng.lat.toFixed(precision);
199     params.lon = latLng.lng.toFixed(precision);
200     params.zoom = this.getZoom();
201
202     return 'geo:' + params.lat + ',' + params.lon + '?z=' + params.zoom;
203   },
204
205   addObject: function(object, callback) {
206     var objectStyle = {
207       color: "#FF6200",
208       weight: 4,
209       opacity: 1,
210       fillOpacity: 0.5
211     };
212
213     var changesetStyle = {
214       weight: 4,
215       color: '#FF9500',
216       opacity: 1,
217       fillOpacity: 0,
218       interactive: false
219     };
220
221     this.removeObject();
222
223     var map = this;
224     this._objectLoader = $.ajax({
225       url: OSM.apiUrl(object),
226       dataType: "xml",
227       success: function (xml) {
228         map._object = object;
229
230         map._objectLayer = new L.OSM.DataLayer(null, {
231           styles: {
232             node: objectStyle,
233             way: objectStyle,
234             area: objectStyle,
235             changeset: changesetStyle
236           }
237         });
238
239         map._objectLayer.interestingNode = function (node, ways, relations) {
240           if (object.type === "node") {
241             return true;
242           } else if (object.type === "relation") {
243             for (var i = 0; i < relations.length; i++)
244               if (relations[i].members.indexOf(node) !== -1)
245                 return true;
246           } else {
247             return false;
248           }
249         };
250
251         map._objectLayer.addData(xml);
252         map._objectLayer.addTo(map);
253
254         if (callback) callback(map._objectLayer.getBounds());
255       }
256     });
257   },
258
259   removeObject: function() {
260     this._object = null;
261     if (this._objectLoader) this._objectLoader.abort();
262     if (this._objectLayer) this.removeLayer(this._objectLayer);
263   },
264
265   getState: function() {
266     return {
267       center: this.getCenter().wrap(),
268       zoom: this.getZoom(),
269       layers: this.getLayersCode()
270     };
271   },
272
273   setState: function(state, options) {
274     if (state.center) this.setView(state.center, state.zoom, options);
275     if (state.layers) this.updateLayers(state.layers);
276   },
277
278   setSidebarOverlaid: function(overlaid) {
279     if (overlaid && !$("#content").hasClass("overlay-sidebar")) {
280       $("#content").addClass("overlay-sidebar");
281       this.invalidateSize({pan: false})
282         .panBy([-350, 0], {animate: false});
283     } else if (!overlaid && $("#content").hasClass("overlay-sidebar")) {
284       this.panBy([350, 0], {animate: false});
285       $("#content").removeClass("overlay-sidebar");
286       this.invalidateSize({pan: false});
287     }
288     return this;
289   }
290 });
291
292 L.Icon.Default.imagePath = "/images/";
293
294 L.Icon.Default.imageUrls = {
295   "/images/marker-icon.png": OSM.MARKER_ICON,
296   "/images/marker-icon-2x.png": OSM.MARKER_ICON_2X,
297   "/images/marker-shadow.png": OSM.MARKER_SHADOW
298 };
299
300 L.extend(L.Icon.Default.prototype, {
301   _oldGetIconUrl: L.Icon.Default.prototype._getIconUrl,
302
303   _getIconUrl:  function (name) {
304     var url = this._oldGetIconUrl(name);
305     return L.Icon.Default.imageUrls[url];
306   }
307 });
308
309 OSM.getUserIcon = function (url) {
310   return L.icon({
311     iconUrl: url || OSM.MARKER_RED,
312     iconSize: [25, 41],
313     iconAnchor: [12, 41],
314     popupAnchor: [1, -34],
315     shadowUrl: OSM.MARKER_SHADOW,
316     shadowSize: [41, 41]
317   });
318 };