]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/leaflet.map.js
Merge remote-tracking branch 'upstream/pull/4272'
[rails.git] / app / assets / javascripts / leaflet.map.js
1 //= require qs/dist/qs
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_link = $("<a>", {
19       href: "/copyright",
20       text: I18n.t("javascripts.map.openstreetmap_contributors")
21     }).prop("outerHTML");
22     var copyright = I18n.t("javascripts.map.copyright_text", { copyright_link: copyright_link });
23
24     var donate = $("<a>", {
25       "href": "https://supporting.openstreetmap.org",
26       "class": "donate-attr",
27       "text": I18n.t("javascripts.map.make_a_donation")
28     }).prop("outerHTML");
29
30     var terms = $("<a>", {
31       href: "https://wiki.osmfoundation.org/wiki/Terms_of_Use",
32       text: I18n.t("javascripts.map.website_and_api_terms")
33     }).prop("outerHTML");
34
35     var cyclosm_link = $("<a>", {
36       href: "https://www.cyclosm.org",
37       target: "_blank",
38       text: I18n.t("javascripts.map.cyclosm_name")
39     }).prop("outerHTML");
40     var osm_france_link = $("<a>", {
41       href: "https://openstreetmap.fr/",
42       target: "_blank",
43       text: I18n.t("javascripts.map.osm_france")
44     }).prop("outerHTML");
45     var cyclosm = I18n.t("javascripts.map.cyclosm_credit", { cyclosm_link: cyclosm_link, osm_france_link: osm_france_link });
46
47     var thunderforest_link = $("<a>", {
48       href: "https://www.thunderforest.com/",
49       target: "_blank",
50       text: I18n.t("javascripts.map.andy_allan")
51     }).prop("outerHTML");
52     var thunderforest = I18n.t("javascripts.map.thunderforest_credit", { thunderforest_link: thunderforest_link });
53
54     var tracestrack_link = $("<a>", {
55       href: "https://www.tracestrack.com/",
56       target: "_blank",
57       text: I18n.t("javascripts.map.tracestrack")
58     }).prop("outerHTML");
59     var tracestrack = I18n.t("javascripts.map.tracestrack_credit", { tracestrack_link: tracestrack_link });
60
61     var hotosm_link = $("<a>", {
62       href: "https://www.hotosm.org/",
63       target: "_blank",
64       text: I18n.t("javascripts.map.hotosm_name")
65     }).prop("outerHTML");
66     var hotosm = I18n.t("javascripts.map.hotosm_credit", { hotosm_link: hotosm_link, osm_france_link: osm_france_link });
67
68     this.baseLayers = [];
69
70     this.baseLayers.push(new L.OSM.Mapnik({
71       attribution: copyright + " &hearts; " + donate + ". " + terms,
72       code: "M",
73       keyid: "mapnik",
74       name: I18n.t("javascripts.map.base.standard")
75     }));
76
77     this.baseLayers.push(new L.OSM.CyclOSM({
78       attribution: copyright + ". " + cyclosm + ". " + terms,
79       code: "Y",
80       keyid: "cyclosm",
81       name: I18n.t("javascripts.map.base.cyclosm")
82     }));
83
84     if (OSM.THUNDERFOREST_KEY) {
85       this.baseLayers.push(new L.OSM.CycleMap({
86         attribution: copyright + ". " + thunderforest + ". " + terms,
87         apikey: OSM.THUNDERFOREST_KEY,
88         code: "C",
89         keyid: "cyclemap",
90         name: I18n.t("javascripts.map.base.cycle_map")
91       }));
92
93       this.baseLayers.push(new L.OSM.TransportMap({
94         attribution: copyright + ". " + thunderforest + ". " + terms,
95         apikey: OSM.THUNDERFOREST_KEY,
96         code: "T",
97         keyid: "transportmap",
98         name: I18n.t("javascripts.map.base.transport_map")
99       }));
100     }
101
102     if (OSM.TRACESTRACK_KEY) {
103       this.baseLayers.push(new L.OSM.TracestrackTopo({
104         attribution: copyright + ". " + tracestrack + ". " + terms,
105         apikey: OSM.TRACESTRACK_KEY,
106         code: "P",
107         keyid: "tracestracktopo",
108         name: I18n.t("javascripts.map.base.tracestracktop_topo")
109       }));
110     }
111
112     this.baseLayers.push(new L.OSM.HOT({
113       attribution: copyright + ". " + hotosm + ". " + terms,
114       code: "H",
115       keyid: "hot",
116       name: I18n.t("javascripts.map.base.hot")
117     }));
118
119     this.noteLayer = new L.FeatureGroup();
120     this.noteLayer.options = { code: "N" };
121
122     this.dataLayer = new L.OSM.DataLayer(null);
123     this.dataLayer.options.code = "D";
124
125     this.gpsLayer = new L.OSM.GPS({
126       pane: "overlayPane",
127       code: "G",
128       name: I18n.t("javascripts.map.base.gps")
129     });
130
131     this.on("layeradd", function (event) {
132       if (this.baseLayers.indexOf(event.layer) >= 0) {
133         this.setMaxZoom(event.layer.options.maxZoom);
134       }
135     });
136   },
137
138   updateLayers: function (layerParam) {
139     var layers = layerParam || "M",
140         layersAdded = "";
141
142     for (var i = this.baseLayers.length - 1; i >= 0; i--) {
143       if (layers.indexOf(this.baseLayers[i].options.code) >= 0) {
144         this.addLayer(this.baseLayers[i]);
145         layersAdded = layersAdded + this.baseLayers[i].options.code;
146       } else if (i === 0 && layersAdded === "") {
147         this.addLayer(this.baseLayers[i]);
148       } else {
149         this.removeLayer(this.baseLayers[i]);
150       }
151     }
152   },
153
154   getLayersCode: function () {
155     var layerConfig = "";
156     this.eachLayer(function (layer) {
157       if (layer.options && layer.options.code) {
158         layerConfig += layer.options.code;
159       }
160     });
161     return layerConfig;
162   },
163
164   getMapBaseLayerId: function () {
165     var baseLayerId;
166     this.eachLayer(function (layer) {
167       if (layer.options && layer.options.keyid) baseLayerId = layer.options.keyid;
168     });
169     return baseLayerId;
170   },
171
172   getUrl: function (marker) {
173     var precision = OSM.zoomPrecision(this.getZoom()),
174         params = {};
175
176     if (marker && this.hasLayer(marker)) {
177       var latLng = marker.getLatLng().wrap();
178       params.mlat = latLng.lat.toFixed(precision);
179       params.mlon = latLng.lng.toFixed(precision);
180     }
181
182     var url = window.location.protocol + "//" + OSM.SERVER_URL + "/",
183         query = Qs.stringify(params),
184         hash = OSM.formatHash(this);
185
186     if (query) url += "?" + query;
187     if (hash) url += hash;
188
189     return url;
190   },
191
192   getShortUrl: function (marker) {
193     var zoom = this.getZoom(),
194         latLng = marker && this.hasLayer(marker) ? marker.getLatLng().wrap() : this.getCenter().wrap(),
195         str = window.location.hostname.match(/^www\.openstreetmap\.org/i) ?
196           window.location.protocol + "//osm.org/go/" :
197           window.location.protocol + "//" + window.location.hostname + "/go/",
198         char_array = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_~",
199         x = Math.round((latLng.lng + 180.0) * ((1 << 30) / 90.0)),
200         y = Math.round((latLng.lat + 90.0) * ((1 << 30) / 45.0)),
201         // JavaScript only has to keep 32 bits of bitwise operators, so this has to be
202         // done in two parts. each of the parts c1/c2 has 30 bits of the total in it
203         // and drops the last 4 bits of the full 64 bit Morton code.
204         c1 = interlace(x >>> 17, y >>> 17), c2 = interlace((x >>> 2) & 0x7fff, (y >>> 2) & 0x7fff),
205         digit,
206         i;
207
208     for (i = 0; i < Math.ceil((zoom + 8) / 3.0) && i < 5; ++i) {
209       digit = (c1 >> (24 - (6 * i))) & 0x3f;
210       str += char_array.charAt(digit);
211     }
212     for (i = 5; i < Math.ceil((zoom + 8) / 3.0); ++i) {
213       digit = (c2 >> (24 - (6 * (i - 5)))) & 0x3f;
214       str += char_array.charAt(digit);
215     }
216     for (i = 0; i < ((zoom + 8) % 3); ++i) str += "-";
217
218     // Called to interlace the bits in x and y, making a Morton code.
219     function interlace(x, y) {
220       var interlaced_x = x,
221           interlaced_y = y;
222       interlaced_x = (interlaced_x | (interlaced_x << 8)) & 0x00ff00ff;
223       interlaced_x = (interlaced_x | (interlaced_x << 4)) & 0x0f0f0f0f;
224       interlaced_x = (interlaced_x | (interlaced_x << 2)) & 0x33333333;
225       interlaced_x = (interlaced_x | (interlaced_x << 1)) & 0x55555555;
226       interlaced_y = (interlaced_y | (interlaced_y << 8)) & 0x00ff00ff;
227       interlaced_y = (interlaced_y | (interlaced_y << 4)) & 0x0f0f0f0f;
228       interlaced_y = (interlaced_y | (interlaced_y << 2)) & 0x33333333;
229       interlaced_y = (interlaced_y | (interlaced_y << 1)) & 0x55555555;
230       return (interlaced_x << 1) | interlaced_y;
231     }
232
233     var params = {};
234     var layers = this.getLayersCode().replace("M", "");
235
236     if (layers) {
237       params.layers = layers;
238     }
239
240     if (marker && this.hasLayer(marker)) {
241       params.m = "";
242     }
243
244     if (this._object) {
245       params[this._object.type] = this._object.id;
246     }
247
248     var query = Qs.stringify(params);
249     if (query) {
250       str += "?" + query;
251     }
252
253     return str;
254   },
255
256   getGeoUri: function (marker) {
257     var precision = OSM.zoomPrecision(this.getZoom()),
258         latLng,
259         params = {};
260
261     if (marker && this.hasLayer(marker)) {
262       latLng = marker.getLatLng().wrap();
263     } else {
264       latLng = this.getCenter();
265     }
266
267     params.lat = latLng.lat.toFixed(precision);
268     params.lon = latLng.lng.toFixed(precision);
269     params.zoom = this.getZoom();
270
271     return "geo:" + params.lat + "," + params.lon + "?z=" + params.zoom;
272   },
273
274   addObject: function (object, callback) {
275     var objectStyle = {
276       color: "#FF6200",
277       weight: 4,
278       opacity: 1,
279       fillOpacity: 0.5
280     };
281
282     var changesetStyle = {
283       weight: 4,
284       color: "#FF9500",
285       opacity: 1,
286       fillOpacity: 0,
287       interactive: false
288     };
289
290     var haloStyle = {
291       weight: 2.5,
292       radius: 20,
293       fillOpacity: 0.5,
294       color: "#FF6200"
295     };
296
297     this.removeObject();
298
299     if (object.type === "note") {
300       this._objectLoader = {
301         abort: function () {}
302       };
303
304       this._object = object;
305       this._objectLayer = L.featureGroup().addTo(this);
306
307       L.circleMarker(object.latLng, haloStyle).addTo(this._objectLayer);
308
309       if (object.icon) {
310         L.marker(object.latLng, {
311           icon: object.icon,
312           opacity: 1,
313           interactive: true
314         }).addTo(this._objectLayer);
315       }
316
317       if (callback) callback(this._objectLayer.getBounds());
318     } else { // element or changeset handled by L.OSM.DataLayer
319       var map = this;
320       this._objectLoader = $.ajax({
321         url: OSM.apiUrl(object),
322         dataType: "xml",
323         success: function (xml) {
324           map._object = object;
325
326           map._objectLayer = new L.OSM.DataLayer(null, {
327             styles: {
328               node: objectStyle,
329               way: objectStyle,
330               area: objectStyle,
331               changeset: changesetStyle
332             }
333           });
334
335           map._objectLayer.interestingNode = function (node, ways, relations) {
336             if (object.type === "node") {
337               return true;
338             } else if (object.type === "relation") {
339               for (var i = 0; i < relations.length; i++) {
340                 if (relations[i].members.indexOf(node) !== -1) return true;
341               }
342             } else {
343               return false;
344             }
345           };
346
347           map._objectLayer.addData(xml);
348           map._objectLayer.addTo(map);
349
350           if (callback) callback(map._objectLayer.getBounds());
351         }
352       });
353     }
354   },
355
356   removeObject: function () {
357     this._object = null;
358     if (this._objectLoader) this._objectLoader.abort();
359     if (this._objectLayer) this.removeLayer(this._objectLayer);
360   },
361
362   getState: function () {
363     return {
364       center: this.getCenter().wrap(),
365       zoom: this.getZoom(),
366       layers: this.getLayersCode()
367     };
368   },
369
370   setState: function (state, options) {
371     if (state.center) this.setView(state.center, state.zoom, options);
372     if (state.layers) this.updateLayers(state.layers);
373   },
374
375   setSidebarOverlaid: function (overlaid) {
376     var sidebarWidth = 350;
377     if (overlaid && !$("#content").hasClass("overlay-sidebar")) {
378       $("#content").addClass("overlay-sidebar");
379       this.invalidateSize({ pan: false });
380       if ($("html").attr("dir") !== "rtl") {
381         this.panBy([-sidebarWidth, 0], { animate: false });
382       }
383     } else if (!overlaid && $("#content").hasClass("overlay-sidebar")) {
384       if ($("html").attr("dir") !== "rtl") {
385         this.panBy([sidebarWidth, 0], { animate: false });
386       }
387       $("#content").removeClass("overlay-sidebar");
388       this.invalidateSize({ pan: false });
389     }
390     return this;
391   }
392 });
393
394 L.Icon.Default.imagePath = "/images/";
395
396 L.Icon.Default.imageUrls = {
397   "/images/marker-icon.png": OSM.MARKER_ICON,
398   "/images/marker-icon-2x.png": OSM.MARKER_ICON_2X,
399   "/images/marker-shadow.png": OSM.MARKER_SHADOW
400 };
401
402 L.extend(L.Icon.Default.prototype, {
403   _oldGetIconUrl: L.Icon.Default.prototype._getIconUrl,
404
405   _getIconUrl: function (name) {
406     var url = this._oldGetIconUrl(name);
407     return L.Icon.Default.imageUrls[url];
408   }
409 });
410
411 OSM.getUserIcon = function (url) {
412   return L.icon({
413     iconUrl: url || OSM.MARKER_RED,
414     iconSize: [25, 41],
415     iconAnchor: [12, 41],
416     popupAnchor: [1, -34],
417     shadowUrl: OSM.MARKER_SHADOW,
418     shadowSize: [41, 41]
419   });
420 };