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