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