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