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