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