@npm9912/v-map 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +192 -96
- package/dist/cjs/{cesium-provider-BiFFyAl9.js → cesium-provider-CTtu9eTD.js} +6 -5
- package/dist/cjs/{deck-provider-Ctq3Q8a1.js → deck-provider-fNa818HH.js} +9 -9
- package/dist/cjs/events-BMG7RKne.js +11 -0
- package/dist/cjs/{geotiff-source-RaNzzWkC.js → geotiff-source-B9ARUE9z.js} +1 -1
- package/dist/cjs/{index-ISOEpMC3.js → index-9APmzoa2.js} +6 -6
- package/dist/cjs/{index-CbVT-Con.js → index-BJg0ncfC.js} +4 -4
- package/dist/cjs/{index-CJvvX4yx.js → index-C1ubapwF.js} +4 -4
- package/dist/cjs/{index-B8LHqjyg.js → index-ChrKyU6i.js} +4 -4
- package/dist/cjs/{index-JSwBbvGA.js → index-DmGHwivM.js} +1 -0
- package/dist/cjs/{layer-extension-B_olS0rc.js → layer-extension-D3a-1DFI.js} +1 -1
- package/dist/cjs/{leaflet-provider-DOqfs7g5.js → leaflet-provider-7Nw-AdV_.js} +6 -5
- package/dist/cjs/loader.cjs.js +2 -2
- package/dist/cjs/{messages-D7h4m8Tx.js → messages-CFCxeG8p.js} +0 -9
- package/dist/cjs/{openlayers-provider-Dfeg6L4n.js → openlayers-provider-DMxYtFkS.js} +5 -4
- package/dist/cjs/{polygon-layer-B9PrN7vr.js → polygon-layer-Dx1ZWZP0.js} +1 -1
- package/dist/cjs/{scenegraph-layer-DwNoxQdi.js → scenegraph-layer-ctLehP0q.js} +1 -1
- package/dist/cjs/v-map-builder.cjs.entry.js +4 -3
- package/dist/cjs/v-map-error.cjs.entry.js +121 -0
- package/dist/cjs/v-map-layer-geojson_12.cjs.entry.js +11 -10
- package/dist/cjs/{v-map-layer-helper-iAzxAg9I.js → v-map-layer-helper-DnWpjZ_Q.js} +7 -6
- package/dist/cjs/v-map-layer-terrain-geotiff.cjs.entry.js +5 -4
- package/dist/cjs/v-map-layercontrol.cjs.entry.js +1 -1
- package/dist/cjs/v-map.cjs.js +2 -2
- package/dist/cjs/{v-map.v-map-layer-osm.v-map-layergroup-BsXp3BoL.js → v-map.v-map-layer-osm.v-map-layergroup-BJ3_NqAj.js} +16 -15
- package/dist/cjs/v-map_3.cjs.entry.js +5 -4
- package/dist/collection/collection-manifest.json +1 -0
- package/dist/collection/components/v-map/v-map.css +3 -0
- package/dist/collection/components/v-map-error/v-map-error.css +136 -0
- package/dist/collection/components/v-map-error/v-map-error.js +277 -0
- package/dist/collection/components/v-map-layer-geojson/v-map-layer-geojson.js +1 -1
- package/dist/collection/components/v-map-layer-terrain/v-map-layer-terrain.js +1 -1
- package/dist/collection/components/v-map-layer-terrain-geotiff/v-map-layer-terrain-geotiff.js +1 -1
- package/dist/collection/components/v-map-layer-tile3d/v-map-layer-tile3d.js +1 -1
- package/dist/collection/components/v-map-layer-wcs/v-map-layer-wcs.js +1 -1
- package/dist/collection/components/v-map-layer-wfs/v-map-layer-wfs.js +1 -1
- package/dist/collection/components/v-map-layergroup/v-map-layergroup.js +1 -1
- package/dist/collection/components/v-map-style/v-map-style.js +1 -1
- package/dist/components/cesium-provider.js +1 -1
- package/dist/components/deck-provider.js +1 -1
- package/dist/components/events.js +1 -1
- package/dist/components/geotiff-source.js +1 -1
- package/dist/components/leaflet-provider.js +1 -1
- package/dist/components/logger.js +1 -0
- package/dist/components/openlayers-provider.js +1 -1
- package/dist/components/v-map-builder.js +2 -2
- package/dist/components/v-map-error.d.ts +11 -0
- package/dist/components/v-map-error.js +1 -0
- package/dist/components/v-map-layer-geojson2.js +1 -1
- package/dist/components/v-map-layer-geotiff2.js +1 -1
- package/dist/components/v-map-layer-google2.js +1 -1
- package/dist/components/v-map-layer-helper.js +1 -1
- package/dist/components/v-map-layer-osm2.js +1 -1
- package/dist/components/v-map-layer-scatterplot2.js +1 -1
- package/dist/components/v-map-layer-terrain-geotiff.js +1 -1
- package/dist/components/v-map-layer-terrain2.js +1 -1
- package/dist/components/v-map-layer-tile3d2.js +1 -1
- package/dist/components/v-map-layer-wcs2.js +1 -1
- package/dist/components/v-map-layer-wfs2.js +1 -1
- package/dist/components/v-map-layer-wkt2.js +1 -1
- package/dist/components/v-map-layer-wms2.js +1 -1
- package/dist/components/v-map-layer-xyz2.js +1 -1
- package/dist/components/v-map-layergroup2.js +1 -1
- package/dist/components/v-map-style2.js +2 -2
- package/dist/components/v-map2.js +1 -1
- package/dist/esm/{cesium-provider-BJfAup3w.js → cesium-provider-Bh__cBGf.js} +6 -5
- package/dist/esm/{deck-provider-C7U9VDEq.js → deck-provider-DxIpS4lY.js} +9 -9
- package/dist/esm/events-CrV_misM.js +9 -0
- package/dist/esm/{geotiff-source-esnDnC-u.js → geotiff-source-BRjO-Dvr.js} +1 -1
- package/dist/esm/{index-BIEmlzCf.js → index-Bh2gBu9u.js} +5 -5
- package/dist/esm/{index-jzneDarq.js → index-BoNyIrdq.js} +1 -1
- package/dist/esm/{index-jN06TXUp.js → index-C3mnOs0I.js} +4 -4
- package/dist/esm/{index-B1zwA4IC.js → index-C63kfbil.js} +6 -6
- package/dist/esm/{index-DbSdn93t.js → index-DxbztwCv.js} +7 -7
- package/dist/esm/{layer-extension-CZXK5goK.js → layer-extension-C5Y2UES3.js} +1 -1
- package/dist/esm/{leaflet-provider-Q41TB6ku.js → leaflet-provider-k6JSYiYX.js} +6 -5
- package/dist/esm/loader.js +3 -3
- package/dist/esm/{messages-CMKJzsgL.js → messages-QJHuuz0g.js} +1 -9
- package/dist/esm/{openlayers-provider-CMsDsQTQ.js → openlayers-provider-DIquf3Tx.js} +5 -4
- package/dist/esm/{polygon-layer-ByhxGhWC.js → polygon-layer-ZIT5mJy5.js} +1 -1
- package/dist/esm/{scenegraph-layer-09K_B6DT.js → scenegraph-layer-CNIRd2uu.js} +1 -1
- package/dist/esm/v-map-builder.entry.js +3 -2
- package/dist/esm/v-map-error.entry.js +119 -0
- package/dist/esm/v-map-layer-geojson_12.entry.js +10 -9
- package/dist/esm/{v-map-layer-helper-Dys44Cgo.js → v-map-layer-helper-CuHYsU9f.js} +2 -1
- package/dist/esm/v-map-layer-terrain-geotiff.entry.js +5 -4
- package/dist/esm/v-map-layercontrol.entry.js +1 -1
- package/dist/esm/v-map.js +3 -3
- package/dist/esm/{v-map.v-map-layer-osm.v-map-layergroup-B4pFHuSf.js → v-map.v-map-layer-osm.v-map-layergroup-Zwdvm9PG.js} +10 -9
- package/dist/esm/v-map_3.entry.js +5 -4
- package/dist/types/components/v-map-error/v-map-error.d.ts +79 -0
- package/dist/types/components.d.ts +128 -0
- package/dist/v-map/p-05ee633f.entry.js +1 -0
- package/dist/v-map/p-08ad1392.entry.js +1 -0
- package/dist/v-map/p-2-mR3oVa.js +1 -0
- package/dist/v-map/{p-c21c93fe.entry.js → p-3a57b64a.entry.js} +1 -1
- package/dist/v-map/p-58dda864.entry.js +1 -0
- package/dist/v-map/p-915314c0.entry.js +10 -0
- package/dist/v-map/{p-MyTSFnEk.js → p-9Rt23jlQ.js} +1 -1
- package/dist/v-map/p-BSsFEMZP.js +1 -0
- package/dist/v-map/{p-jzneDarq.js → p-BoNyIrdq.js} +2 -2
- package/dist/v-map/p-BpE6L1g0.js +1 -0
- package/dist/v-map/{p-DvHXtWUg.js → p-C0M0-Kvt.js} +1 -1
- package/dist/v-map/p-CbiLpFhO.js +1 -0
- package/dist/v-map/p-Ci70E1EM.js +1 -0
- package/dist/v-map/p-CrV_misM.js +1 -0
- package/dist/v-map/{p-DrOQ9V4h.js → p-DAf4itFZ.js} +1 -1
- package/dist/v-map/p-DVBtCUtQ.js +1 -0
- package/dist/v-map/{p-CZqY0yW4.js → p-DuJ_mTaq.js} +1 -1
- package/dist/v-map/p-G6iftXUC.js +1 -0
- package/dist/v-map/{p-CMKJzsgL.js → p-QJHuuz0g.js} +1 -1
- package/dist/v-map/{p-aa410e64.entry.js → p-e21ea0ce.entry.js} +2 -2
- package/dist/v-map/{p-DmICdG34.js → p-rCyRSFJb.js} +2 -2
- package/dist/v-map/{p-CafTHT9i.js → p-vhbi5XXi.js} +1 -1
- package/dist/v-map/{p-Dckgonw8.js → p-yXLNXXx-.js} +1 -1
- package/dist/v-map/v-map.esm.js +1 -1
- package/package.json +29 -5
- package/dist/v-map/p--vVleK-M.js +0 -1
- package/dist/v-map/p-09d10db0.entry.js +0 -1
- package/dist/v-map/p-5eba6058.entry.js +0 -10
- package/dist/v-map/p-6b102336.entry.js +0 -1
- package/dist/v-map/p-BdijL4Av.js +0 -1
- package/dist/v-map/p-BeFu0ap4.js +0 -1
- package/dist/v-map/p-BxFJezdK.js +0 -1
- package/dist/v-map/p-DCTHyf58.js +0 -1
- package/dist/v-map/p-WaMDUuAz.js +0 -1
- package/dist/v-map/p-uiIP-taz.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
const r={Error:"vmap-error",MapProviderReady:"map-provider-ready",MapProviderWillShutdown:"map-provider-will-shutdown",MapMouseMove:"map-mousemove"};export{r as V}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{w as t,l as e}from"./events.js";const r={grayscale:[{value:0,color:[0,0,0]},{value:1,color:[255,255,255]}],viridis:[{value:0,color:[68,1,84]},{value:.25,color:[59,82,139]},{value:.5,color:[33,145,140]},{value:.75,color:[94,201,98]},{value:1,color:[253,231,37]}],terrain:[{value:0,color:[0,128,0]},{value:.25,color:[139,195,74]},{value:.5,color:[255,235,59]},{value:.75,color:[255,152,0]},{value:1,color:[255,255,255]}],turbo:[{value:0,color:[48,18,59]},{value:.2,color:[33,102,172]},{value:.4,color:[68,190,112]},{value:.6,color:[253,231,37]},{value:.8,color:[234,51,35]},{value:1,color:[122,4,3]}],rainbow:[{value:0,color:[148,0,211]},{value:.2,color:[0,0,255]},{value:.4,color:[0,255,0]},{value:.6,color:[255,255,0]},{value:.8,color:[255,127,0]},{value:1,color:[255,0,0]}]};function n(t,e){const r=Math.max(0,Math.min(1,t));if(0===e.length)return[0,0,0];if(1===e.length)return e[0].color;let n=0,a=e.length-1;if(r<=e[n].value)return e[n].color;if(r>=e[a].value)return e[a].color;for(;a-n>1;){const t=Math.floor((n+a)/2);e[t].value<=r?n=t:a=t}const i=e[n],o=e[a],s=(r-i.value)/(o.value-i.value);return[Math.round(i.color[0]+s*(o.color[0]-i.color[0])),Math.round(i.color[1]+s*(o.color[1]-i.color[1])),Math.round(i.color[2]+s*(o.color[2]-i.color[2]))]}function a(e,n){if("string"==typeof e){const n=r[e];return n?{stops:n}:(t(`Unknown colormap: ${e}, using grayscale`),{stops:r.grayscale})}return function(e,n){const a=e.colorMapEntries||[];if(0===a.length)return t("GeoStyler ColorMap has no entries, using grayscale"),{stops:r.grayscale};const i=a.map((t=>t.quantity)).filter((t=>"number"==typeof t));let o,s;n?[o,s]=n:i.length>0?(o=Math.min(...i),s=Math.max(...i)):(o=0,s=1),s===o&&(s=o+1);const l=a.map((e=>{const r=(("number"==typeof e.quantity?e.quantity:0)-o)/(s-o),n=function(e){let r=e.trim();if(r.startsWith("#")&&(r=r.slice(1)),3===r.length&&(r=r.split("").map((t=>t+t)).join("")),6!==r.length)return t(`Invalid hex color: ${e}, using black`),[0,0,0];const n=parseInt(r.slice(0,2),16),a=parseInt(r.slice(2,4),16),i=parseInt(r.slice(4,6),16);return isNaN(n)||isNaN(a)||isNaN(i)?(t(`Invalid hex color: ${e}, using black`),[0,0,0]):[n,a,i]}("string"==typeof e.color?e.color:String(e.color));return{value:Math.max(0,Math.min(1,r)),color:n}}));return l.sort(((t,e)=>t.value-e.value)),{stops:l,computedRange:n?void 0:[o,s]}}(e,n)}class i{min;max;constructor(t,e){this.min=t,this.max=e}contains(t){return t.x>=this.min.x&&t.x<=this.max.x&&t.y>=this.min.y&&t.y<=this.max.y}static fromTriangle(t){const e=Math.min(t.a.x,t.b.x,t.c.x),r=Math.min(t.a.y,t.b.y,t.c.y),n=Math.max(t.a.x,t.b.x,t.c.x),a=Math.max(t.a.y,t.b.y,t.c.y);return new i({x:e,y:r},{x:n,y:a})}static union(t,e){return new i({x:Math.min(t.min.x,e.min.x),y:Math.min(t.min.y,e.min.y)},{x:Math.max(t.max.x,e.max.x),y:Math.max(t.max.y,e.max.y)})}}class o{bbox;triangles;left;right;constructor(t,e=[],r=null,n=null){this.bbox=t,this.triangles=e,this.left=r,this.right=n}static build(t,e=0,r=10){if(t.length<=2||e>=r){let e=i.fromTriangle(t[0]);for(let r=1;r<t.length;r++)e=i.union(e,i.fromTriangle(t[r]));return new o(e,t)}const n=t.map((t=>({x:(t.a.x+t.b.x+t.c.x)/3,y:(t.a.y+t.b.y+t.c.y)/3}))),{min:a,max:s}=n.reduce(((t,e)=>({min:{x:Math.min(t.min.x,e.x),y:Math.min(t.min.y,e.y)},max:{x:Math.max(t.max.x,e.x),y:Math.max(t.max.y,e.y)}})),{min:n[0],max:n[0]}),l=s.x-a.x>s.y-a.y?"x":"y";n.sort(((t,e)=>t[l]-e[l]));const h=Math.floor(n.length/2),u=[],c=[];for(let e=0;e<t.length;e++)(e<h?u:c).push(t[e]);const f=o.build(u,e+1,r),d=o.build(c,e+1,r),M=i.union(f.bbox,d.bbox);return new o(M,[],f,d)}findContainingTriangle(t){if(!this.bbox.contains(t))return null;if(this.triangles.length>0){for(const e of this.triangles)if(o.punktInDreieck2D(t,e))return e;return null}return this.left?.findContainingTriangle(t)||this.right?.findContainingTriangle(t)||null}static punktInDreieck2D(t,e){const{a:r,b:n,c:a}=e,i=a.x-r.x,o=a.y-r.y,s=n.x-r.x,l=n.y-r.y,h=t.x-r.x,u=t.y-r.y,c=i*i+o*o,f=i*s+o*l,d=i*h+o*u,M=s*s+l*l,m=s*h+l*u,g=1/(c*M-f*f),p=(M*d-f*m)*g,y=(c*m-f*d)*g;return p>=0&&y>=0&&p+y<=1}static toTriangle2D(t){return{a:{x:t.target[0][0],y:t.target[0][1]},b:{x:t.target[1][0],y:t.target[1][1]},c:{x:t.target[2][0],y:t.target[2][1]},triangle:t,transform:null}}toString(t=""){const e=this.triangles.length>0;let r=`${t}${e?"LEAF":"NODE"} bbox=[${this.bbox.min.x.toFixed(2)}, ${this.bbox.min.y.toFixed(2)}, ${this.bbox.max.x.toFixed(2)}, ${this.bbox.max.y.toFixed(2)}]`;if(e){const t=this.triangles.map((t=>t.a.x.toFixed(2)+","+t.a.y.toFixed(2)+" "+t.b.x.toFixed(2)+","+t.b.y.toFixed(2)+" "+t.c.x.toFixed(2)+","+t.c.y.toFixed(2))).toString();r+=` triangles=${this.triangles.length} - ${t}`}else r+="\n",this.left&&(r+=`${t}├─ left:\n${this.left.toString(t+"│ ")}`),this.right&&(r+=`${t}└─ right:\n${this.right.toString(t+" ")}`);return r}getStats(){const t={depth:1,nodeCount:1,leafCount:0,triangleCount:this.triangles.length,minTrianglesPerLeaf:1/0,maxTrianglesPerLeaf:0};if(this.triangles.length>0)t.leafCount=1,t.minTrianglesPerLeaf=this.triangles.length,t.maxTrianglesPerLeaf=this.triangles.length;else{if(this.left){const e=this.left.getStats();t.depth=Math.max(t.depth,e.depth+1),t.nodeCount+=e.nodeCount,t.leafCount+=e.leafCount,t.triangleCount+=e.triangleCount,t.minTrianglesPerLeaf=Math.min(t.minTrianglesPerLeaf,e.minTrianglesPerLeaf),t.maxTrianglesPerLeaf=Math.max(t.maxTrianglesPerLeaf,e.maxTrianglesPerLeaf)}if(this.right){const e=this.right.getStats();t.depth=Math.max(t.depth,e.depth+1),t.nodeCount+=e.nodeCount,t.leafCount+=e.leafCount,t.triangleCount+=e.triangleCount,t.minTrianglesPerLeaf=Math.min(t.minTrianglesPerLeaf,e.minTrianglesPerLeaf),t.maxTrianglesPerLeaf=Math.max(t.maxTrianglesPerLeaf,e.maxTrianglesPerLeaf)}}return t}}function s(t,e,r,n,a=10){const[i,o,s,l]=r;let h=1/0,u=1/0,c=-1/0,f=-1/0,d=[0,0],M=[0,0],m=[0,0],g=[0,0];const p=(t,e,r)=>{for(let a=0;a<=r;a++){const i=a/r,o=[t[0]+(e[0]-t[0])*i,t[1]+(e[1]-t[1])*i],[s,l]=n(o);s<h&&(h=s,d=o),l<u&&(u=l,M=o),s>c&&(c=s,m=o),l>f&&(f=l,g=o)}};if(p([i,l],[s,l],a),p([s,l],[s,o],a),p([s,o],[i,o],a),p([i,o],[i,l],a),null!=t&&null!=e){const r=Math.floor((h-t[0])/e);h=t[0]+r*e;const n=Math.floor((u-t[1])/e);u=t[1]+n*e;const a=Math.ceil((c-t[0])/e);c=t[0]+a*e;const i=Math.ceil((f-t[1])/e);f=t[1]+i*e}return{source:{minX:h,minY:u,maxX:c,maxY:f},target:{minX:d[0],minY:M[1],maxX:m[0],maxY:g[1]}}}class l{triangles_=[];transformFn_;errorThresholdSquared_;bvh_=null;bounds;constructor(t,e,r=.5,n=null,a=null,i=10){this.transformFn_=t,this.errorThresholdSquared_=r*r;const[o,l,h,u]=e,c=[o,u],f=[h,u],d=[h,l],M=[o,l],m=s(n,a,e,this.transformFn_,i),g=[m.source.minX,m.source.maxY],p=[m.source.maxX,m.source.maxY],y=[m.source.maxX,m.source.minY],b=[m.source.minX,m.source.minY];this.bounds=m.source,this.addQuad_(c,f,d,M,g,p,y,b,10)}getBounds(){return this.bounds}addQuad_(t,e,r,n,a,i,o,s,l){let h=!1;if(l>0){const l=[(e[0]+r[0])/2,(e[1]+r[1])/2],u=[(r[0]+n[0])/2,(r[1]+n[1])/2],c=[(n[0]+t[0])/2,(n[1]+t[1])/2],f=this.transformFn_([(t[0]+e[0])/2,(t[1]+e[1])/2]),d=this.transformFn_(l),M=this.transformFn_(u),m=this.transformFn_(c),g=[(i[0]+o[0])/2,(i[1]+o[1])/2],p=[(o[0]+s[0])/2,(o[1]+s[1])/2],y=[(s[0]+a[0])/2,(s[1]+a[1])/2],b=this.getSquaredError_(f,[(a[0]+i[0])/2,(a[1]+i[1])/2]),v=this.getSquaredError_(d,g),w=this.getSquaredError_(M,p),S=this.getSquaredError_(m,y);(b>this.errorThresholdSquared_||v>this.errorThresholdSquared_||w>this.errorThresholdSquared_||S>this.errorThresholdSquared_)&&(h=!0)}if(h){const h=[(t[0]+e[0]+r[0]+n[0])/4,(t[1]+e[1]+r[1]+n[1])/4],u=this.transformFn_(h),c=[(t[0]+e[0])/2,(t[1]+e[1])/2],f=[(e[0]+r[0])/2,(e[1]+r[1])/2],d=[(r[0]+n[0])/2,(r[1]+n[1])/2],M=[(n[0]+t[0])/2,(n[1]+t[1])/2],m=this.transformFn_(c),g=this.transformFn_(f),p=this.transformFn_(d),y=this.transformFn_(M),b=l-1;this.addQuad_(t,c,h,M,a,m,u,y,b),this.addQuad_(c,e,f,h,m,i,g,u,b),this.addQuad_(h,f,r,d,u,g,o,p,b),this.addQuad_(M,h,d,n,y,u,p,s,b)}else this.addTriangle_(t,e,n,a,i,s),this.addTriangle_(e,r,n,i,o,s)}addTriangle_(t,e,r,n,a,i){isFinite(n[0])&&isFinite(n[1])&&isFinite(a[0])&&isFinite(a[1])&&isFinite(i[0])&&isFinite(i[1])&&this.triangles_.push({source:[n,a,i],target:[t,e,r]})}getSquaredError_(t,e){const r=t[0]-e[0],n=t[1]-e[1];return r*r+n*n}getTriangles(){return this.triangles_}calculateSourceExtent(){if(0===this.triangles_.length)return null;let t=1/0,e=1/0,r=-1/0,n=-1/0;for(const a of this.triangles_)for(const[i,o]of a.source)i<t&&(t=i),i>r&&(r=i),o<e&&(e=o),o>n&&(n=o);return[t,e,r,n]}buildBVH(){const t=this.triangles_.map(o.toTriangle2D);this.bvh_=o.build(t)}findSourceTriangleForTargetPoint(t,e=null){this.bvh_||this.buildBVH();const r={x:t[0],y:t[1]};if(e?.tri&&o.punktInDreieck2D(r,o.toTriangle2D(e.tri)))return e;const n=this.bvh_.findContainingTriangle(r);return n&&!n.transform&&(n.transform=this.calculateAffineTransform(n.triangle)),n?{tri:n.triangle,transform:n.transform}:null}calculateAffineTransform(t){const[[e,r],[n,a],[i,o]]=t.target,[[s,l],[h,u],[c,f]]=t.source,d=(n-e)*(o-r)-(i-e)*(a-r);if(Math.abs(d)<1e-10)return{a:1,b:0,c:s,d:0,e:1,f:l};const M=((h-s)*(o-r)-(c-s)*(a-r))/d,m=((c-s)*(n-e)-(h-s)*(i-e))/d,g=((u-l)*(o-r)-(f-l)*(a-r))/d,p=((f-l)*(n-e)-(u-l)*(i-e))/d;return{a:M,b:m,c:s-M*e-m*r,d:g,e:p,f:l-g*e-p*r}}applyAffineTransform(t,e,r){return[r.a*t+r.b*e+r.c,r.d*t+r.e*e+r.f]}}function h(e,r){switch(r){case"Uint8Array":return e;case"Uint16Array":return Math.round(e/65535*255);case"Int16Array":return Math.round((e+32768)/65535*255);case"Uint32Array":return Math.round(e/4294967295*255);case"Int32Array":return Math.round((e+2147483648)/4294967295*255);case"Float32Array":case"Float64Array":const n=Math.max(0,Math.min(1,e));return Math.round(255*n);default:return t(`Unknown array type: ${r}, treating as Uint8`),e}}function u(t){return Math.max(0,Math.min(1,t))}function c(t,e,r,a,i,o,s,l,c){const f=Math.round(t)-s,d=Math.round(e)-l;if(f<0||f>=i||d<0||d>=o)return null;const M=d*i+f,m=r.length;if(1===m){const t=r[0][M];if(c){const e=u(t),[r,a,i]=n(e,c);return[r,a,i,255]}{const e=h(t,a);return[e,e,e,255]}}return 3===m?[h(r[0][M],a),h(r[1][M],a),h(r[2][M],a),255]:m>=4?[h(r[0][M],a),h(r[1][M],a),h(r[2][M],a),h(r[3][M],a)]:null}function f(t,e,r,a,i,o,s,l,c){const f=t-s,d=e-l;if(f<0||f>=i-1||d<0||d>=o-1)return null;const M=Math.floor(f),m=Math.ceil(f),g=Math.floor(d),p=Math.ceil(d),y=f-M,b=d-g,v=r.length,w=[0,0,0,255];if(1===v){const t=r[0],e=(t[g*i+M]*(1-y)+t[g*i+m]*y)*(1-b)+(t[p*i+M]*(1-y)+t[p*i+m]*y)*b;if(c){const t=u(e),[r,a,i]=n(t,c);return[r,a,i,255]}{const t=h(e,a);return[t,t,t,255]}}{const t=Math.min(v,4);for(let e=0;e<t;e++){const t=r[e];w[e]=h((t[g*i+M]*(1-y)+t[g*i+m]*y)*(1-b)+(t[p*i+M]*(1-y)+t[p*i+m]*y)*b,a)}}return w}class d{config;worldSize=40075016.686;globalTriangulation;constructor(t){this.config=t,t.worldSize&&(this.worldSize=t.worldSize)}createGlobalTriangulation(){const t=performance.now(),[r,n,a,i]=this.config.sourceBounds,{source:o}=s(null,null,[r,n,a,i],(t=>this.config.transformSourceMapToViewFn(t))),h=[o.minX,o.minY,o.maxX,o.maxY];e("Creating global triangulation for bounds:",{source:this.config.sourceBounds,mercator:h});const u=this.config.resolution/2,c=Math.min(10,Math.max(this.config.imageWidth,this.config.imageHeight)/256);this.globalTriangulation=new l((t=>this.config.transformViewToSourceMapFn(t)),h,u,this.config.sourceRef,this.config.resolution,c),this.globalTriangulation.findSourceTriangleForTargetPoint([0,0]);const f=this.globalTriangulation.getTriangles();e(`Global triangulation created: ${f.length} triangles in ${(performance.now()-t).toFixed(2)}ms`)}getGlobalTriangulation(){return this.globalTriangulation}sanitizeElevationValue(t){return Number.isFinite(t)?void 0!==this.config.noDataValue&&t===this.config.noDataValue?0:t:0}getTileSizeInMeter(t){return this.worldSize/Math.pow(2,t)}getTileBounds(t,e,r){const n=this.getTileSizeInMeter(r),a=-this.worldSize/2+t*n,i=this.worldSize/2-e*n;return[a,i-n,a+n,i]}selectOverviewImage(t,e){const r=this.config.baseImage.getResolution()[0];if(!this.config.overviewImages||0===this.config.overviewImages.length)return{bestImage:this.config.baseImage,bestResolution:r,imageLevel:0};const n=this.getTileSizeInMeter(t)/e,a=[this.config.baseImage,...this.config.overviewImages],i=a[this.config.overviewImages.length],o=r*Math.pow(2,this.config.overviewImages.length);let s=this.config.overviewImages.length,l=o,h=i,u=0,c=r;for(const t of a){if(n/(2*c)<=1){h=t,l=c,s=u;break}u++,c*=2}return{bestImage:h,bestResolution:l,imageLevel:s}}calculateTileSourceBounds(t){const[e,r,n,a]=t,{source:i}=s(this.config.sourceRef,this.config.resolution,[e,r,n,a],this.config.transformViewToSourceMapFn),o=this.config.transformViewToSourceMapFn([e,r]),l=this.config.transformViewToSourceMapFn([n,a]),h=this.config.transformViewToSourceMapFn([e,a]),u=this.config.transformViewToSourceMapFn([n,r]);return{tileSrcWest:Math.min(i.minX,o[0],l[0],h[0],u[0]),tileSrcEast:Math.max(i.maxX,o[0],l[0],h[0],u[0]),tileSrcSouth:Math.min(i.minY,o[1],l[1],h[1],u[1]),tileSrcNorth:Math.max(i.maxY,o[1],l[1],h[1],u[1])}}calculateReadWindow(e,r,n){const[a,i,o,s]=this.config.sourceBounds,l=o-a,h=s-i,{tileSrcWest:u,tileSrcEast:c,tileSrcSouth:f,tileSrcNorth:d}=e,M=Math.floor((u-a)/l*r),m=Math.ceil((c-a)/l*r),g=Math.floor((s-d)/h*n),p=Math.ceil((s-f)/h*n),y=Math.min(r,Math.max(0,M-2)),b=Math.max(0,Math.min(r,m+2)),v=Math.min(n,Math.max(0,g-2)),w=Math.max(0,Math.min(n,p+2)),S=b-y,x=w-v;return S<=0||x<=0?(t("Invalid read window for tile",{readXMin:y,readXMax:b,readYMin:v,readYMax:w,ovWidth:r,ovHeight:n}),null):{readXMin:y,readXMax:b,readYMin:v,readYMax:w,readWidth:S,readHeight:x}}async loadAndConvertRasterData(r,n){const{readXMin:a,readYMin:i,readXMax:o,readYMax:s}=n;let l=null,h=null;for(let t=0;t<=2;t++){try{l=await r.readRasters({window:[a,i,o,s]})}catch(t){h=t}if(null!=l){h=null;break}}if(null!=h)throw e(h),t("Error - readRasters - read window: ",n),h;const u=[];let c="";for(let e=0;e<l.length;e++){const r=l[e];"number"!=typeof r?(u.push(r),0===e&&(c=r.constructor.name)):t("Unexpected number in rasters array")}return{rasterBands:u,arrayType:c}}renderTilePixels(t){const{sampleSize:e,mercatorBounds:r,triangulation:n,rasterBands:a,arrayType:i,readWindow:o,ovWidth:s,ovHeight:l,resampleMethod:h,colorStops:u}=t,[d,M,m,g]=r,[p,y,b,v]=this.config.sourceBounds,w=b-p,S=v-y,x=new Uint8ClampedArray(e*e*4);let $=null;for(let t=0;t<e;t++)for(let r=0;r<e;r++){const T=4*(t*e+r),P=d+r/e*(m-d),j=g-t/e*(g-M);if($=n.findSourceTriangleForTargetPoint([P,j],$),$){const[t,e]=n.applyAffineTransform(P,j,$.transform);if(t<p||t>b||e<y||e>v)x[T]=0,x[T+1]=0,x[T+2]=0,x[T+3]=0;else{const r=(t-p)/w*s,n=(v-e)/S*l,d="near"===h?c(r,n,a,i,o.readWidth,o.readHeight,o.readXMin,o.readYMin,u):f(r,n,a,i,o.readWidth,o.readHeight,o.readXMin,o.readYMin,u);d?(x[T]=d[0],x[T+1]=d[1],x[T+2]=d[2],x[T+3]=d[3]):(x[T]=0,x[T+1]=0,x[T+2]=0,x[T+3]=0)}}else x[T]=0,x[T+1]=0,x[T+2]=0,x[T+3]=0}return x}tileIntersectsSource(t){const[e,r,n,a]=t,[i,o,s,l]=this.config.sourceBounds,h=this.config.transformViewToSourceMapFn([e,r]),u=this.config.transformViewToSourceMapFn([n,a]),c=this.config.transformViewToSourceMapFn([e,a]),f=this.config.transformViewToSourceMapFn([n,r]),d=Math.min(h[0],u[0],c[0],f[0]),M=Math.max(h[0],u[0],c[0],f[0]),m=Math.min(h[1],u[1],c[1],f[1]),g=Math.max(h[1],u[1],c[1],f[1]);return M>=i&&d<=s&&g>=o&&m<=l}async getTileData(r){const{x:n,y:a,z:i,tileSize:o,resolution:s,resampleMethod:h,colorStops:u}=r,c=this.getTileBounds(n,a,i);if(e(`v-map - geotiff - getTileData(${n},${a},${i}): viewBounds=[${c.map((t=>t.toFixed(0))).join(",")}], sourceBounds=[${this.config.sourceBounds.map((t=>t.toFixed(0))).join(",")}], toProjection=${this.config.toProjection}`),!this.tileIntersectsSource(c)){e(`v-map - geotiff - getTileData(${n},${a},${i}): no intersection, returning transparent`);const t=Math.ceil(o*s);return new Uint8ClampedArray(t*t*4)}const f=Math.ceil(o*s);let d;this.globalTriangulation?d=this.globalTriangulation:(t("Global triangulation not available, creating fallback for tile"),d=new l(this.config.transformViewToSourceMapFn,c,.5));const M=this.calculateTileSourceBounds(c),{bestImage:m,bestResolution:g,imageLevel:p}=this.selectOverviewImage(i,o),y=m.getWidth(),b=m.getHeight(),v=this.calculateReadWindow(M,y,b);if(!v)return new Uint8ClampedArray(f*f*4);const{rasterBands:w,arrayType:S}=await this.loadAndConvertRasterData(m,v);return e(`Read window: [${v.readXMin}, ${v.readYMin}, ${v.readXMax}, ${v.readYMax}] (${v.readWidth}x${v.readHeight} pixels), ${w.length} bands, type: ${S}, imageLevel: ${p}, resolution: ${g}`),this.renderTilePixels({sampleSize:f,mercatorBounds:c,triangulation:d,rasterBands:w,arrayType:S,readWindow:v,ovWidth:y,ovHeight:b,resampleMethod:h,colorStops:u})}async getElevationData(e){const{x:r,y:n,z:a,tileSize:i}=e,o=i+1,s=this.getTileBounds(r,n,a);if(!this.tileIntersectsSource(s))return new Float32Array(o*o);let h;this.globalTriangulation?h=this.globalTriangulation:(t("Global triangulation not available, creating fallback for elevation tile"),h=new l(this.config.transformViewToSourceMapFn,s,.5));const u=this.calculateTileSourceBounds(s),{bestImage:c}=this.selectOverviewImage(a,i),f=c.getWidth(),d=c.getHeight(),M=this.calculateReadWindow(u,f,d);if(!M)return new Float32Array(o*o);const{rasterBands:m}=await this.loadAndConvertRasterData(c,M),[g,p,y,b]=s,[v,w,S,x]=this.config.sourceBounds,$=S-v,T=x-w,P=new Float32Array(o*o);let j=null;for(let t=0;t<i;t++)for(let e=0;e<i;e++){const r=g+e/i*(y-g),n=b-t/i*(b-p);if(j=h.findSourceTriangleForTargetPoint([r,n],j),j){const[a,i]=h.applyAffineTransform(r,n,j.transform);if(a>=v&&a<=S&&i>=w&&i<=x){const r=(x-i)/T*d,n=Math.round((a-v)/$*f)-M.readXMin,s=Math.round(r)-M.readYMin;if(n>=0&&n<M.readWidth&&s>=0&&s<M.readHeight){const r=Number(m[0][s*M.readWidth+n]);P[t*o+e]=this.sanitizeElevationValue(r)}}}}for(let t=0;t<i;t++)P[t*o+i]=P[t*o+i-1];for(let t=0;t<=i;t++)P[i*o+t]=P[(i-1)*o+t];return P}}async function M(t,e){const{default:r}=await import("./index4.js");return{transformViewToSourceMapFn:n=>{const a=r(e,t.fromProjection,n);return[Number(a[0]),Number(a[1])]},transformSourceMapToViewFn:n=>{const a=r(t.fromProjection,e,n);return[Number(a[0]),Number(a[1])]},sourceBounds:t.sourceBounds,sourceRef:t.sourceRef,resolution:t.resolution,imageWidth:t.width,imageHeight:t.height,fromProjection:t.fromProjection,toProjection:e,baseImage:t.baseImage,overviewImages:t.overviewImages??[],noDataValue:t.noDataValue}}async function m(r,n,a){const{geotiff:i,proj4:o,geokeysToProj4:s}=a,{fromUrl:l}=i,{toProj4:h}=s;let u=null,c=null;for(let t=0;t<=2;t++){try{u=await l(r,{allowFullFile:!0,blockSize:1048576,cacheSize:100})}catch(t){c=t}if(null!=u){c=null;break}}if(null!=c)throw e(c),t("Error - loadGeoTIFFSource - fromUrl: ",r),c;const f=await u.getImage(0),d=await u.getImageCount(),M=[];for(let t=1;t<d;t++)M.push(await u.getImage(t));const m=f.getWidth(),g=f.getHeight(),p=Math.max(1,f.getSamplesPerPixel?.()??1);let y=n.forceProjection&&n.projection?n.projection:n.projection??"EPSG:4326",b=null;if(!n.forceProjection){const e="function"==typeof f.getGeoKeys?f.getGeoKeys()??null:null;if(e)try{const t=h(e),r=e.ProjectedCSTypeGeoKey??e.GeographicTypeGeoKey;if(r&&(y=`EPSG:${r}`),t?.proj4){b=t.proj4;const e=String(r);r&&!o.defs(y)&&o.defs(y,t.proj4),r&&!o.defs(e)&&o.defs(e,t.proj4)}}catch(e){t("v-map - geotiff - failed to parse GeoKeys",e)}}if(!b)switch(y){case"EPSG:4326":b="+proj=longlat +datum=WGS84 +no_defs";break;case"EPSG:3857":b="+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs";break;case"EPSG:32632":b="+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs"}y&&""!==y.trim()||(y="EPSG:4326"),b&&!o.defs(y)&&o.defs(y,b);const v=f.getBoundingBox(),w=[v[0],v[1]],S=f.getResolution()[0],x=null!=n.nodata?Number(n.nodata):"function"==typeof f.getGDALNoData?f.getGDALNoData():void 0,$=null!=x?Number(x):void 0,T=t=>Math.max(-180,Math.min(180,Number.isFinite(t)?t:0)),P=t=>Math.max(-90,Math.min(90,Number.isFinite(t)?t:0));let j;j=y&&"EPSG:4326"!==y?e=>{try{const t=o(y,"EPSG:4326",e);return[Number(t[0]),Number(t[1])]}catch(r){return t("v-map - geotiff - transform to WGS84 failed, falling back",r),e}}:t=>t;const[I,N,F,G]=v,k=[j([I,N]),j([F,N]),j([F,G]),j([I,G])],E=T(Math.min(...k.map((t=>t[0])))),A=T(Math.max(...k.map((t=>t[0])))),B=P(Math.min(...k.map((t=>t[1])))),W=P(Math.max(...k.map((t=>t[1]))));return e("v-map - geotiff - loaded source",{url:r,width:m,height:g,samplesPerPixel:p,fromProjection:y,bounds:v}),{tiff:u,baseImage:f,overviewImages:M,width:m,height:g,samplesPerPixel:p,fromProjection:y,sourceBounds:v,sourceRef:w,resolution:S,proj4:o,noDataValue:$,wgs84Bounds:[E,B,A,W],transformToWgs84:j}}async function g(t,e,r,n){const[a,{default:i},o]=await Promise.all([import("./geotiff.js").then((function(t){return t.g})),import("./index4.js"),import("./main-dist.js").then((function(t){return t.m}))]);return await m(t,{projection:e,forceProjection:r,nodata:n},{geotiff:a,proj4:i,geokeysToProj4:o})}export{d as G,g as a,M as b,a as g,m as l}
|
|
1
|
+
import{w as t,l as e}from"./logger.js";const r={grayscale:[{value:0,color:[0,0,0]},{value:1,color:[255,255,255]}],viridis:[{value:0,color:[68,1,84]},{value:.25,color:[59,82,139]},{value:.5,color:[33,145,140]},{value:.75,color:[94,201,98]},{value:1,color:[253,231,37]}],terrain:[{value:0,color:[0,128,0]},{value:.25,color:[139,195,74]},{value:.5,color:[255,235,59]},{value:.75,color:[255,152,0]},{value:1,color:[255,255,255]}],turbo:[{value:0,color:[48,18,59]},{value:.2,color:[33,102,172]},{value:.4,color:[68,190,112]},{value:.6,color:[253,231,37]},{value:.8,color:[234,51,35]},{value:1,color:[122,4,3]}],rainbow:[{value:0,color:[148,0,211]},{value:.2,color:[0,0,255]},{value:.4,color:[0,255,0]},{value:.6,color:[255,255,0]},{value:.8,color:[255,127,0]},{value:1,color:[255,0,0]}]};function n(t,e){const r=Math.max(0,Math.min(1,t));if(0===e.length)return[0,0,0];if(1===e.length)return e[0].color;let n=0,a=e.length-1;if(r<=e[n].value)return e[n].color;if(r>=e[a].value)return e[a].color;for(;a-n>1;){const t=Math.floor((n+a)/2);e[t].value<=r?n=t:a=t}const i=e[n],o=e[a],s=(r-i.value)/(o.value-i.value);return[Math.round(i.color[0]+s*(o.color[0]-i.color[0])),Math.round(i.color[1]+s*(o.color[1]-i.color[1])),Math.round(i.color[2]+s*(o.color[2]-i.color[2]))]}function a(e,n){if("string"==typeof e){const n=r[e];return n?{stops:n}:(t(`Unknown colormap: ${e}, using grayscale`),{stops:r.grayscale})}return function(e,n){const a=e.colorMapEntries||[];if(0===a.length)return t("GeoStyler ColorMap has no entries, using grayscale"),{stops:r.grayscale};const i=a.map((t=>t.quantity)).filter((t=>"number"==typeof t));let o,s;n?[o,s]=n:i.length>0?(o=Math.min(...i),s=Math.max(...i)):(o=0,s=1),s===o&&(s=o+1);const l=a.map((e=>{const r=(("number"==typeof e.quantity?e.quantity:0)-o)/(s-o),n=function(e){let r=e.trim();if(r.startsWith("#")&&(r=r.slice(1)),3===r.length&&(r=r.split("").map((t=>t+t)).join("")),6!==r.length)return t(`Invalid hex color: ${e}, using black`),[0,0,0];const n=parseInt(r.slice(0,2),16),a=parseInt(r.slice(2,4),16),i=parseInt(r.slice(4,6),16);return isNaN(n)||isNaN(a)||isNaN(i)?(t(`Invalid hex color: ${e}, using black`),[0,0,0]):[n,a,i]}("string"==typeof e.color?e.color:String(e.color));return{value:Math.max(0,Math.min(1,r)),color:n}}));return l.sort(((t,e)=>t.value-e.value)),{stops:l,computedRange:n?void 0:[o,s]}}(e,n)}class i{min;max;constructor(t,e){this.min=t,this.max=e}contains(t){return t.x>=this.min.x&&t.x<=this.max.x&&t.y>=this.min.y&&t.y<=this.max.y}static fromTriangle(t){const e=Math.min(t.a.x,t.b.x,t.c.x),r=Math.min(t.a.y,t.b.y,t.c.y),n=Math.max(t.a.x,t.b.x,t.c.x),a=Math.max(t.a.y,t.b.y,t.c.y);return new i({x:e,y:r},{x:n,y:a})}static union(t,e){return new i({x:Math.min(t.min.x,e.min.x),y:Math.min(t.min.y,e.min.y)},{x:Math.max(t.max.x,e.max.x),y:Math.max(t.max.y,e.max.y)})}}class o{bbox;triangles;left;right;constructor(t,e=[],r=null,n=null){this.bbox=t,this.triangles=e,this.left=r,this.right=n}static build(t,e=0,r=10){if(t.length<=2||e>=r){let e=i.fromTriangle(t[0]);for(let r=1;r<t.length;r++)e=i.union(e,i.fromTriangle(t[r]));return new o(e,t)}const n=t.map((t=>({x:(t.a.x+t.b.x+t.c.x)/3,y:(t.a.y+t.b.y+t.c.y)/3}))),{min:a,max:s}=n.reduce(((t,e)=>({min:{x:Math.min(t.min.x,e.x),y:Math.min(t.min.y,e.y)},max:{x:Math.max(t.max.x,e.x),y:Math.max(t.max.y,e.y)}})),{min:n[0],max:n[0]}),l=s.x-a.x>s.y-a.y?"x":"y";n.sort(((t,e)=>t[l]-e[l]));const h=Math.floor(n.length/2),u=[],c=[];for(let e=0;e<t.length;e++)(e<h?u:c).push(t[e]);const f=o.build(u,e+1,r),d=o.build(c,e+1,r),M=i.union(f.bbox,d.bbox);return new o(M,[],f,d)}findContainingTriangle(t){if(!this.bbox.contains(t))return null;if(this.triangles.length>0){for(const e of this.triangles)if(o.punktInDreieck2D(t,e))return e;return null}return this.left?.findContainingTriangle(t)||this.right?.findContainingTriangle(t)||null}static punktInDreieck2D(t,e){const{a:r,b:n,c:a}=e,i=a.x-r.x,o=a.y-r.y,s=n.x-r.x,l=n.y-r.y,h=t.x-r.x,u=t.y-r.y,c=i*i+o*o,f=i*s+o*l,d=i*h+o*u,M=s*s+l*l,g=s*h+l*u,m=1/(c*M-f*f),p=(M*d-f*g)*m,y=(c*g-f*d)*m;return p>=0&&y>=0&&p+y<=1}static toTriangle2D(t){return{a:{x:t.target[0][0],y:t.target[0][1]},b:{x:t.target[1][0],y:t.target[1][1]},c:{x:t.target[2][0],y:t.target[2][1]},triangle:t,transform:null}}toString(t=""){const e=this.triangles.length>0;let r=`${t}${e?"LEAF":"NODE"} bbox=[${this.bbox.min.x.toFixed(2)}, ${this.bbox.min.y.toFixed(2)}, ${this.bbox.max.x.toFixed(2)}, ${this.bbox.max.y.toFixed(2)}]`;if(e){const t=this.triangles.map((t=>t.a.x.toFixed(2)+","+t.a.y.toFixed(2)+" "+t.b.x.toFixed(2)+","+t.b.y.toFixed(2)+" "+t.c.x.toFixed(2)+","+t.c.y.toFixed(2))).toString();r+=` triangles=${this.triangles.length} - ${t}`}else r+="\n",this.left&&(r+=`${t}├─ left:\n${this.left.toString(t+"│ ")}`),this.right&&(r+=`${t}└─ right:\n${this.right.toString(t+" ")}`);return r}getStats(){const t={depth:1,nodeCount:1,leafCount:0,triangleCount:this.triangles.length,minTrianglesPerLeaf:1/0,maxTrianglesPerLeaf:0};if(this.triangles.length>0)t.leafCount=1,t.minTrianglesPerLeaf=this.triangles.length,t.maxTrianglesPerLeaf=this.triangles.length;else{if(this.left){const e=this.left.getStats();t.depth=Math.max(t.depth,e.depth+1),t.nodeCount+=e.nodeCount,t.leafCount+=e.leafCount,t.triangleCount+=e.triangleCount,t.minTrianglesPerLeaf=Math.min(t.minTrianglesPerLeaf,e.minTrianglesPerLeaf),t.maxTrianglesPerLeaf=Math.max(t.maxTrianglesPerLeaf,e.maxTrianglesPerLeaf)}if(this.right){const e=this.right.getStats();t.depth=Math.max(t.depth,e.depth+1),t.nodeCount+=e.nodeCount,t.leafCount+=e.leafCount,t.triangleCount+=e.triangleCount,t.minTrianglesPerLeaf=Math.min(t.minTrianglesPerLeaf,e.minTrianglesPerLeaf),t.maxTrianglesPerLeaf=Math.max(t.maxTrianglesPerLeaf,e.maxTrianglesPerLeaf)}}return t}}function s(t,e,r,n,a=10){const[i,o,s,l]=r;let h=1/0,u=1/0,c=-1/0,f=-1/0,d=[0,0],M=[0,0],g=[0,0],m=[0,0];const p=(t,e,r)=>{for(let a=0;a<=r;a++){const i=a/r,o=[t[0]+(e[0]-t[0])*i,t[1]+(e[1]-t[1])*i],[s,l]=n(o);s<h&&(h=s,d=o),l<u&&(u=l,M=o),s>c&&(c=s,g=o),l>f&&(f=l,m=o)}};if(p([i,l],[s,l],a),p([s,l],[s,o],a),p([s,o],[i,o],a),p([i,o],[i,l],a),null!=t&&null!=e){const r=Math.floor((h-t[0])/e);h=t[0]+r*e;const n=Math.floor((u-t[1])/e);u=t[1]+n*e;const a=Math.ceil((c-t[0])/e);c=t[0]+a*e;const i=Math.ceil((f-t[1])/e);f=t[1]+i*e}return{source:{minX:h,minY:u,maxX:c,maxY:f},target:{minX:d[0],minY:M[1],maxX:g[0],maxY:m[1]}}}class l{triangles_=[];transformFn_;errorThresholdSquared_;bvh_=null;bounds;constructor(t,e,r=.5,n=null,a=null,i=10){this.transformFn_=t,this.errorThresholdSquared_=r*r;const[o,l,h,u]=e,c=[o,u],f=[h,u],d=[h,l],M=[o,l],g=s(n,a,e,this.transformFn_,i),m=[g.source.minX,g.source.maxY],p=[g.source.maxX,g.source.maxY],y=[g.source.maxX,g.source.minY],b=[g.source.minX,g.source.minY];this.bounds=g.source,this.addQuad_(c,f,d,M,m,p,y,b,10)}getBounds(){return this.bounds}addQuad_(t,e,r,n,a,i,o,s,l){let h=!1;if(l>0){const l=[(e[0]+r[0])/2,(e[1]+r[1])/2],u=[(r[0]+n[0])/2,(r[1]+n[1])/2],c=[(n[0]+t[0])/2,(n[1]+t[1])/2],f=this.transformFn_([(t[0]+e[0])/2,(t[1]+e[1])/2]),d=this.transformFn_(l),M=this.transformFn_(u),g=this.transformFn_(c),m=[(i[0]+o[0])/2,(i[1]+o[1])/2],p=[(o[0]+s[0])/2,(o[1]+s[1])/2],y=[(s[0]+a[0])/2,(s[1]+a[1])/2],b=this.getSquaredError_(f,[(a[0]+i[0])/2,(a[1]+i[1])/2]),v=this.getSquaredError_(d,m),w=this.getSquaredError_(M,p),S=this.getSquaredError_(g,y);(b>this.errorThresholdSquared_||v>this.errorThresholdSquared_||w>this.errorThresholdSquared_||S>this.errorThresholdSquared_)&&(h=!0)}if(h){const h=[(t[0]+e[0]+r[0]+n[0])/4,(t[1]+e[1]+r[1]+n[1])/4],u=this.transformFn_(h),c=[(t[0]+e[0])/2,(t[1]+e[1])/2],f=[(e[0]+r[0])/2,(e[1]+r[1])/2],d=[(r[0]+n[0])/2,(r[1]+n[1])/2],M=[(n[0]+t[0])/2,(n[1]+t[1])/2],g=this.transformFn_(c),m=this.transformFn_(f),p=this.transformFn_(d),y=this.transformFn_(M),b=l-1;this.addQuad_(t,c,h,M,a,g,u,y,b),this.addQuad_(c,e,f,h,g,i,m,u,b),this.addQuad_(h,f,r,d,u,m,o,p,b),this.addQuad_(M,h,d,n,y,u,p,s,b)}else this.addTriangle_(t,e,n,a,i,s),this.addTriangle_(e,r,n,i,o,s)}addTriangle_(t,e,r,n,a,i){isFinite(n[0])&&isFinite(n[1])&&isFinite(a[0])&&isFinite(a[1])&&isFinite(i[0])&&isFinite(i[1])&&this.triangles_.push({source:[n,a,i],target:[t,e,r]})}getSquaredError_(t,e){const r=t[0]-e[0],n=t[1]-e[1];return r*r+n*n}getTriangles(){return this.triangles_}calculateSourceExtent(){if(0===this.triangles_.length)return null;let t=1/0,e=1/0,r=-1/0,n=-1/0;for(const a of this.triangles_)for(const[i,o]of a.source)i<t&&(t=i),i>r&&(r=i),o<e&&(e=o),o>n&&(n=o);return[t,e,r,n]}buildBVH(){const t=this.triangles_.map(o.toTriangle2D);this.bvh_=o.build(t)}findSourceTriangleForTargetPoint(t,e=null){this.bvh_||this.buildBVH();const r={x:t[0],y:t[1]};if(e?.tri&&o.punktInDreieck2D(r,o.toTriangle2D(e.tri)))return e;const n=this.bvh_.findContainingTriangle(r);return n&&!n.transform&&(n.transform=this.calculateAffineTransform(n.triangle)),n?{tri:n.triangle,transform:n.transform}:null}calculateAffineTransform(t){const[[e,r],[n,a],[i,o]]=t.target,[[s,l],[h,u],[c,f]]=t.source,d=(n-e)*(o-r)-(i-e)*(a-r);if(Math.abs(d)<1e-10)return{a:1,b:0,c:s,d:0,e:1,f:l};const M=((h-s)*(o-r)-(c-s)*(a-r))/d,g=((c-s)*(n-e)-(h-s)*(i-e))/d,m=((u-l)*(o-r)-(f-l)*(a-r))/d,p=((f-l)*(n-e)-(u-l)*(i-e))/d;return{a:M,b:g,c:s-M*e-g*r,d:m,e:p,f:l-m*e-p*r}}applyAffineTransform(t,e,r){return[r.a*t+r.b*e+r.c,r.d*t+r.e*e+r.f]}}function h(e,r){switch(r){case"Uint8Array":return e;case"Uint16Array":return Math.round(e/65535*255);case"Int16Array":return Math.round((e+32768)/65535*255);case"Uint32Array":return Math.round(e/4294967295*255);case"Int32Array":return Math.round((e+2147483648)/4294967295*255);case"Float32Array":case"Float64Array":const n=Math.max(0,Math.min(1,e));return Math.round(255*n);default:return t(`Unknown array type: ${r}, treating as Uint8`),e}}function u(t){return Math.max(0,Math.min(1,t))}function c(t,e,r,a,i,o,s,l,c){const f=Math.round(t)-s,d=Math.round(e)-l;if(f<0||f>=i||d<0||d>=o)return null;const M=d*i+f,g=r.length;if(1===g){const t=r[0][M];if(c){const e=u(t),[r,a,i]=n(e,c);return[r,a,i,255]}{const e=h(t,a);return[e,e,e,255]}}return 3===g?[h(r[0][M],a),h(r[1][M],a),h(r[2][M],a),255]:g>=4?[h(r[0][M],a),h(r[1][M],a),h(r[2][M],a),h(r[3][M],a)]:null}function f(t,e,r,a,i,o,s,l,c){const f=t-s,d=e-l;if(f<0||f>=i-1||d<0||d>=o-1)return null;const M=Math.floor(f),g=Math.ceil(f),m=Math.floor(d),p=Math.ceil(d),y=f-M,b=d-m,v=r.length,w=[0,0,0,255];if(1===v){const t=r[0],e=(t[m*i+M]*(1-y)+t[m*i+g]*y)*(1-b)+(t[p*i+M]*(1-y)+t[p*i+g]*y)*b;if(c){const t=u(e),[r,a,i]=n(t,c);return[r,a,i,255]}{const t=h(e,a);return[t,t,t,255]}}{const t=Math.min(v,4);for(let e=0;e<t;e++){const t=r[e];w[e]=h((t[m*i+M]*(1-y)+t[m*i+g]*y)*(1-b)+(t[p*i+M]*(1-y)+t[p*i+g]*y)*b,a)}}return w}class d{config;worldSize=40075016.686;globalTriangulation;constructor(t){this.config=t,t.worldSize&&(this.worldSize=t.worldSize)}createGlobalTriangulation(){const t=performance.now(),[r,n,a,i]=this.config.sourceBounds,{source:o}=s(null,null,[r,n,a,i],(t=>this.config.transformSourceMapToViewFn(t))),h=[o.minX,o.minY,o.maxX,o.maxY];e("Creating global triangulation for bounds:",{source:this.config.sourceBounds,mercator:h});const u=this.config.resolution/2,c=Math.min(10,Math.max(this.config.imageWidth,this.config.imageHeight)/256);this.globalTriangulation=new l((t=>this.config.transformViewToSourceMapFn(t)),h,u,this.config.sourceRef,this.config.resolution,c),this.globalTriangulation.findSourceTriangleForTargetPoint([0,0]);const f=this.globalTriangulation.getTriangles();e(`Global triangulation created: ${f.length} triangles in ${(performance.now()-t).toFixed(2)}ms`)}getGlobalTriangulation(){return this.globalTriangulation}sanitizeElevationValue(t){return Number.isFinite(t)?void 0!==this.config.noDataValue&&t===this.config.noDataValue?0:t:0}getTileSizeInMeter(t){return this.worldSize/Math.pow(2,t)}getTileBounds(t,e,r){const n=this.getTileSizeInMeter(r),a=-this.worldSize/2+t*n,i=this.worldSize/2-e*n;return[a,i-n,a+n,i]}selectOverviewImage(t,e){const r=this.config.baseImage.getResolution()[0];if(!this.config.overviewImages||0===this.config.overviewImages.length)return{bestImage:this.config.baseImage,bestResolution:r,imageLevel:0};const n=this.getTileSizeInMeter(t)/e,a=[this.config.baseImage,...this.config.overviewImages],i=a[this.config.overviewImages.length],o=r*Math.pow(2,this.config.overviewImages.length);let s=this.config.overviewImages.length,l=o,h=i,u=0,c=r;for(const t of a){if(n/(2*c)<=1){h=t,l=c,s=u;break}u++,c*=2}return{bestImage:h,bestResolution:l,imageLevel:s}}calculateTileSourceBounds(t){const[e,r,n,a]=t,{source:i}=s(this.config.sourceRef,this.config.resolution,[e,r,n,a],this.config.transformViewToSourceMapFn),o=this.config.transformViewToSourceMapFn([e,r]),l=this.config.transformViewToSourceMapFn([n,a]),h=this.config.transformViewToSourceMapFn([e,a]),u=this.config.transformViewToSourceMapFn([n,r]);return{tileSrcWest:Math.min(i.minX,o[0],l[0],h[0],u[0]),tileSrcEast:Math.max(i.maxX,o[0],l[0],h[0],u[0]),tileSrcSouth:Math.min(i.minY,o[1],l[1],h[1],u[1]),tileSrcNorth:Math.max(i.maxY,o[1],l[1],h[1],u[1])}}calculateReadWindow(e,r,n){const[a,i,o,s]=this.config.sourceBounds,l=o-a,h=s-i,{tileSrcWest:u,tileSrcEast:c,tileSrcSouth:f,tileSrcNorth:d}=e,M=Math.floor((u-a)/l*r),g=Math.ceil((c-a)/l*r),m=Math.floor((s-d)/h*n),p=Math.ceil((s-f)/h*n),y=Math.min(r,Math.max(0,M-2)),b=Math.max(0,Math.min(r,g+2)),v=Math.min(n,Math.max(0,m-2)),w=Math.max(0,Math.min(n,p+2)),S=b-y,x=w-v;return S<=0||x<=0?(t("Invalid read window for tile",{readXMin:y,readXMax:b,readYMin:v,readYMax:w,ovWidth:r,ovHeight:n}),null):{readXMin:y,readXMax:b,readYMin:v,readYMax:w,readWidth:S,readHeight:x}}async loadAndConvertRasterData(r,n){const{readXMin:a,readYMin:i,readXMax:o,readYMax:s}=n;let l=null,h=null;for(let t=0;t<=2;t++){try{l=await r.readRasters({window:[a,i,o,s]})}catch(t){h=t}if(null!=l){h=null;break}}if(null!=h)throw e(h),t("Error - readRasters - read window: ",n),h;const u=[];let c="";for(let e=0;e<l.length;e++){const r=l[e];"number"!=typeof r?(u.push(r),0===e&&(c=r.constructor.name)):t("Unexpected number in rasters array")}return{rasterBands:u,arrayType:c}}renderTilePixels(t){const{sampleSize:e,mercatorBounds:r,triangulation:n,rasterBands:a,arrayType:i,readWindow:o,ovWidth:s,ovHeight:l,resampleMethod:h,colorStops:u}=t,[d,M,g,m]=r,[p,y,b,v]=this.config.sourceBounds,w=b-p,S=v-y,x=new Uint8ClampedArray(e*e*4);let $=null;for(let t=0;t<e;t++)for(let r=0;r<e;r++){const T=4*(t*e+r),P=d+r/e*(g-d),j=m-t/e*(m-M);if($=n.findSourceTriangleForTargetPoint([P,j],$),$){const[t,e]=n.applyAffineTransform(P,j,$.transform);if(t<p||t>b||e<y||e>v)x[T]=0,x[T+1]=0,x[T+2]=0,x[T+3]=0;else{const r=(t-p)/w*s,n=(v-e)/S*l,d="near"===h?c(r,n,a,i,o.readWidth,o.readHeight,o.readXMin,o.readYMin,u):f(r,n,a,i,o.readWidth,o.readHeight,o.readXMin,o.readYMin,u);d?(x[T]=d[0],x[T+1]=d[1],x[T+2]=d[2],x[T+3]=d[3]):(x[T]=0,x[T+1]=0,x[T+2]=0,x[T+3]=0)}}else x[T]=0,x[T+1]=0,x[T+2]=0,x[T+3]=0}return x}tileIntersectsSource(t){const[e,r,n,a]=t,[i,o,s,l]=this.config.sourceBounds,h=this.config.transformViewToSourceMapFn([e,r]),u=this.config.transformViewToSourceMapFn([n,a]),c=this.config.transformViewToSourceMapFn([e,a]),f=this.config.transformViewToSourceMapFn([n,r]),d=Math.min(h[0],u[0],c[0],f[0]),M=Math.max(h[0],u[0],c[0],f[0]),g=Math.min(h[1],u[1],c[1],f[1]),m=Math.max(h[1],u[1],c[1],f[1]);return M>=i&&d<=s&&m>=o&&g<=l}async getTileData(r){const{x:n,y:a,z:i,tileSize:o,resolution:s,resampleMethod:h,colorStops:u}=r,c=this.getTileBounds(n,a,i);if(e(`v-map - geotiff - getTileData(${n},${a},${i}): viewBounds=[${c.map((t=>t.toFixed(0))).join(",")}], sourceBounds=[${this.config.sourceBounds.map((t=>t.toFixed(0))).join(",")}], toProjection=${this.config.toProjection}`),!this.tileIntersectsSource(c)){e(`v-map - geotiff - getTileData(${n},${a},${i}): no intersection, returning transparent`);const t=Math.ceil(o*s);return new Uint8ClampedArray(t*t*4)}const f=Math.ceil(o*s);let d;this.globalTriangulation?d=this.globalTriangulation:(t("Global triangulation not available, creating fallback for tile"),d=new l(this.config.transformViewToSourceMapFn,c,.5));const M=this.calculateTileSourceBounds(c),{bestImage:g,bestResolution:m,imageLevel:p}=this.selectOverviewImage(i,o),y=g.getWidth(),b=g.getHeight(),v=this.calculateReadWindow(M,y,b);if(!v)return new Uint8ClampedArray(f*f*4);const{rasterBands:w,arrayType:S}=await this.loadAndConvertRasterData(g,v);return e(`Read window: [${v.readXMin}, ${v.readYMin}, ${v.readXMax}, ${v.readYMax}] (${v.readWidth}x${v.readHeight} pixels), ${w.length} bands, type: ${S}, imageLevel: ${p}, resolution: ${m}`),this.renderTilePixels({sampleSize:f,mercatorBounds:c,triangulation:d,rasterBands:w,arrayType:S,readWindow:v,ovWidth:y,ovHeight:b,resampleMethod:h,colorStops:u})}async getElevationData(e){const{x:r,y:n,z:a,tileSize:i}=e,o=i+1,s=this.getTileBounds(r,n,a);if(!this.tileIntersectsSource(s))return new Float32Array(o*o);let h;this.globalTriangulation?h=this.globalTriangulation:(t("Global triangulation not available, creating fallback for elevation tile"),h=new l(this.config.transformViewToSourceMapFn,s,.5));const u=this.calculateTileSourceBounds(s),{bestImage:c}=this.selectOverviewImage(a,i),f=c.getWidth(),d=c.getHeight(),M=this.calculateReadWindow(u,f,d);if(!M)return new Float32Array(o*o);const{rasterBands:g}=await this.loadAndConvertRasterData(c,M),[m,p,y,b]=s,[v,w,S,x]=this.config.sourceBounds,$=S-v,T=x-w,P=new Float32Array(o*o);let j=null;for(let t=0;t<i;t++)for(let e=0;e<i;e++){const r=m+e/i*(y-m),n=b-t/i*(b-p);if(j=h.findSourceTriangleForTargetPoint([r,n],j),j){const[a,i]=h.applyAffineTransform(r,n,j.transform);if(a>=v&&a<=S&&i>=w&&i<=x){const r=(x-i)/T*d,n=Math.round((a-v)/$*f)-M.readXMin,s=Math.round(r)-M.readYMin;if(n>=0&&n<M.readWidth&&s>=0&&s<M.readHeight){const r=Number(g[0][s*M.readWidth+n]);P[t*o+e]=this.sanitizeElevationValue(r)}}}}for(let t=0;t<i;t++)P[t*o+i]=P[t*o+i-1];for(let t=0;t<=i;t++)P[i*o+t]=P[(i-1)*o+t];return P}}async function M(t,e){const{default:r}=await import("./index4.js");return{transformViewToSourceMapFn:n=>{const a=r(e,t.fromProjection,n);return[Number(a[0]),Number(a[1])]},transformSourceMapToViewFn:n=>{const a=r(t.fromProjection,e,n);return[Number(a[0]),Number(a[1])]},sourceBounds:t.sourceBounds,sourceRef:t.sourceRef,resolution:t.resolution,imageWidth:t.width,imageHeight:t.height,fromProjection:t.fromProjection,toProjection:e,baseImage:t.baseImage,overviewImages:t.overviewImages??[],noDataValue:t.noDataValue}}async function g(r,n,a){const{geotiff:i,proj4:o,geokeysToProj4:s}=a,{fromUrl:l}=i,{toProj4:h}=s;let u=null,c=null;for(let t=0;t<=2;t++){try{u=await l(r,{allowFullFile:!0,blockSize:1048576,cacheSize:100})}catch(t){c=t}if(null!=u){c=null;break}}if(null!=c)throw e(c),t("Error - loadGeoTIFFSource - fromUrl: ",r),c;const f=await u.getImage(0),d=await u.getImageCount(),M=[];for(let t=1;t<d;t++)M.push(await u.getImage(t));const g=f.getWidth(),m=f.getHeight(),p=Math.max(1,f.getSamplesPerPixel?.()??1);let y=n.forceProjection&&n.projection?n.projection:n.projection??"EPSG:4326",b=null;if(!n.forceProjection){const e="function"==typeof f.getGeoKeys?f.getGeoKeys()??null:null;if(e)try{const t=h(e),r=e.ProjectedCSTypeGeoKey??e.GeographicTypeGeoKey;if(r&&(y=`EPSG:${r}`),t?.proj4){b=t.proj4;const e=String(r);r&&!o.defs(y)&&o.defs(y,t.proj4),r&&!o.defs(e)&&o.defs(e,t.proj4)}}catch(e){t("v-map - geotiff - failed to parse GeoKeys",e)}}if(!b)switch(y){case"EPSG:4326":b="+proj=longlat +datum=WGS84 +no_defs";break;case"EPSG:3857":b="+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs";break;case"EPSG:32632":b="+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs"}y&&""!==y.trim()||(y="EPSG:4326"),b&&!o.defs(y)&&o.defs(y,b);const v=f.getBoundingBox(),w=[v[0],v[1]],S=f.getResolution()[0],x=null!=n.nodata?Number(n.nodata):"function"==typeof f.getGDALNoData?f.getGDALNoData():void 0,$=null!=x?Number(x):void 0,T=t=>Math.max(-180,Math.min(180,Number.isFinite(t)?t:0)),P=t=>Math.max(-90,Math.min(90,Number.isFinite(t)?t:0));let j;j=y&&"EPSG:4326"!==y?e=>{try{const t=o(y,"EPSG:4326",e);return[Number(t[0]),Number(t[1])]}catch(r){return t("v-map - geotiff - transform to WGS84 failed, falling back",r),e}}:t=>t;const[I,N,F,G]=v,k=[j([I,N]),j([F,N]),j([F,G]),j([I,G])],E=T(Math.min(...k.map((t=>t[0])))),A=T(Math.max(...k.map((t=>t[0])))),B=P(Math.min(...k.map((t=>t[1])))),W=P(Math.max(...k.map((t=>t[1]))));return e("v-map - geotiff - loaded source",{url:r,width:g,height:m,samplesPerPixel:p,fromProjection:y,bounds:v}),{tiff:u,baseImage:f,overviewImages:M,width:g,height:m,samplesPerPixel:p,fromProjection:y,sourceBounds:v,sourceRef:w,resolution:S,proj4:o,noDataValue:$,wgs84Bounds:[E,B,A,W],transformToWgs84:j}}async function m(t,e,r,n){const[a,{default:i},o]=await Promise.all([import("./geotiff.js").then((function(t){return t.g})),import("./index4.js"),import("./main-dist.js").then((function(t){return t.m}))]);return await g(t,{projection:e,forceProjection:r,nodata:n},{geotiff:a,proj4:i,geokeysToProj4:o})}export{d as G,m as a,M as b,a as g,g as l}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{i as t,L as e,s,w as i}from"./v-map2.js";import*as r from"leaflet";import{e as o,l as a}from"./events.js";import{D as n}from"./styleconfig.js";import{l as c,G as l,g as h}from"./geotiff-source.js";import{w as u}from"./index5.js";import{GmlParser as f}from"./index.browser.js";const p=256;class y extends r.GridLayer{apiKey;highDpi;sessionRequest;scaleFactor;sessionToken;sessionPromise;sessionRefreshId;previousViewport;currentAttribution;mapInstance;onMoveEnd;constructor(t){super(),this.applyInitialGridOptions(t);const{apiKey:e,mapType:s,language:i,region:r,imageFormat:o,scale:a,highDpi:n,layerTypes:c,overlay:l,styles:h,apiOptions:u}=t;if(!e)throw new Error("Google Map Tiles layer requires an apiKey");this.apiKey=e,this.highDpi=n??(void 0===a||"scaleFactor1x"!==a),this.scaleFactor=this.mapScaleToFactor(a,this.highDpi);const f={mapType:s??"roadmap",language:i??"en-US",region:r??"US"};o&&(f.imageFormat=o),c?.length&&(f.layerTypes=c),u?.length&&(f.apiOptions=u),Array.isArray(h)&&h.length>0&&(f.styles=h),!0===l&&(f.overlay=!0);const p=a??(this.scaleFactor>1?this.factorToScale(this.scaleFactor):void 0);p&&(f.scale=p),this.highDpi&&(f.highDpi=!0),this.sessionRequest=f,this.onMoveEnd=()=>{this.updateAttribution()},this.sessionPromise=this.startSessionFetch()}onAdd(t){return this.mapInstance=t,t.on("moveend",this.onMoveEnd),t.on("zoomend",this.onMoveEnd),this.ensureSession().then((()=>this.updateAttribution())),super.onAdd(t)}onRemove(t){return t.off("moveend",this.onMoveEnd),t.off("zoomend",this.onMoveEnd),this.clearSessionRefresh(),this.removeCurrentAttribution(),this.mapInstance=void 0,super.onRemove(t)}createTile(t,e){const s=document.createElement("img");s.decoding="async",s.alt="",s.crossOrigin="anonymous";const i=this.resolveTileSize();s.width=i.x,s.height=i.y;const r=t=>{const i=t instanceof Error?t.message:"Google tile load error";e(new Error(i),s)};return s.onload=()=>e(null,s),s.onerror=t=>{const e=t instanceof ErrorEvent?t.error??new Error(t.message):new Error("Google tile failed to load");r(e)},this.ensureSession().then((()=>{this.sessionToken?s.src=this.buildTileUrl(t):r(new Error("Google Maps session unavailable"))})).catch((t=>{r(t)})),s}ensureSession(){return this.sessionToken?Promise.resolve():(this.sessionPromise||(this.sessionPromise=this.startSessionFetch()),this.sessionPromise)}startSessionFetch(t=!1){if(this.sessionPromise&&!t)return this.sessionPromise;const e=this.fetchAndApplySession().catch((t=>{const e=t instanceof Error?t:new Error("Failed to create Google Maps session");throw o("Google Map Tiles session error",e),this.sessionToken=void 0,e})).finally((()=>{this.sessionPromise===e&&(this.sessionPromise=void 0)}));return this.sessionPromise=e,e}async fetchAndApplySession(){const t=`https://tile.googleapis.com/v1/createSession?key=${this.apiKey}`,e=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(this.sessionRequest)});if(!e.ok){let t;try{const s=await e.json();t=s?.error?.message}catch{}throw new Error(t??`Google Maps session request failed (${e.status})`)}const s=await e.json();this.sessionToken=s.session,this.applyTileSize(s),this.scheduleSessionRefresh(this.parseExpiry(s.expiry)),this.mapInstance&&(this.updateAttribution(),this.redrawLayer()),a("Google Map Tiles session established")}scheduleSessionRefresh(t){if(!isFinite(t))return;const e=Math.max(t-Date.now()-6e4,1e3);this.clearSessionRefresh(),this.sessionRefreshId=setTimeout((()=>{this.startSessionFetch(!0).then((()=>{this.mapInstance&&(this.updateAttribution(),this.redrawLayer())}))}),e)}clearSessionRefresh(){void 0!==this.sessionRefreshId&&(clearTimeout(this.sessionRefreshId),this.sessionRefreshId=void 0)}async updateAttribution(){if(!this.mapInstance||!this.sessionToken)return;const t=this.mapInstance.getBounds();if(!t?.isValid())return;const e=`zoom=${this.mapInstance.getZoom()}&north=${t.getNorth()}&south=${t.getSouth()}&east=${t.getEast()}&west=${t.getWest()}`;if(this.previousViewport!==e){this.previousViewport=e;try{const t=await fetch(`https://tile.googleapis.com/tile/v1/viewport?session=${this.sessionToken}&key=${this.apiKey}&${e}`);if(!t.ok)throw new Error(`Attribution request failed (${t.status})`);const s=await t.json(),i=s?.copyright;"string"==typeof i&&i.length>0&&this.applyAttribution(i)}catch(t){o("Failed to fetch Google attribution",t)}}}applyAttribution(t){const e=this.mapInstance;e?.attributionControl&&(this.currentAttribution&&this.currentAttribution!==t&&e.attributionControl.removeAttribution(this.currentAttribution),this.currentAttribution&&this.currentAttribution===t||(e.attributionControl.addAttribution(t),this.currentAttribution=t))}removeCurrentAttribution(){const t=this.mapInstance;t?.attributionControl&&this.currentAttribution&&(t.attributionControl.removeAttribution(this.currentAttribution),this.currentAttribution=void 0)}applyTileSize(t){const e=Math.max(1,Math.round(t.tileWidth/this.scaleFactor)),s=Math.max(1,Math.round(t.tileHeight/this.scaleFactor)),i=r.point(e,s);this.setGridOptions({tileSize:i})}parseExpiry(t){const e=parseInt(t,10);return Number.isFinite(e)?1e3*e:Number.NaN}buildTileUrl(t){if(!this.sessionToken)throw new Error("Google Maps session missing");return`https://tile.googleapis.com/v1/2dtiles/${t.z}/${t.x}/${t.y}?session=${this.sessionToken}&key=${this.apiKey}`}mapScaleToFactor(t,e){switch(t){case"scaleFactor4x":return 4;case"scaleFactor2x":return 2;case"scaleFactor1x":return 1;default:return e?2:1}}factorToScale(t){switch(t){case 4:return"scaleFactor4x";case 2:return"scaleFactor2x";case 1:return"scaleFactor1x";default:return}}applyInitialGridOptions(t){const e={},s=["attribution","bounds","className","detectRetina","errorTileUrl","keepBuffer","maxNativeZoom","maxZoom","minNativeZoom","minZoom","noWrap","opacity","pane","reuseTiles","subdomains","tileSize","tms","updateInterval","updateWhenIdle","updateWhenZooming","zIndex","zoomOffset"];for(const i of s){const s=t[i];void 0!==s&&(e[i]=s)}void 0===e.maxZoom&&(e.maxZoom=22),this.setGridOptions(e)}setGridOptions(t){const e=r.Util?.setOptions;if("function"==typeof e)e(this,t);else{const e=this;e.options={...e.options,...t}}}resolveTileSize(){const t=this.options?.tileSize;if(t&&"object"==typeof t){if(Array.isArray(t)&&2===t.length){const[e,s]=t;return r.point(Number(e)||p,Number(s)||p)}if("x"in t&&"y"in t){const e=t;return r.point(Number(e.x)||p,Number(e.y)||p)}}return"number"==typeof t&&Number.isFinite(t)?r.point(t,t):r.point(p,p)}redrawLayer(){this.redraw()}}class d extends r.GridLayer{geotiffOptions;tileProcessor=null;colorStops;loadingPromise;defaultResolution=1;defaultResample="bilinear";constructor(t){super(t),this.geotiffOptions={...t}}onAdd(t){return super.onAdd(t),this.ensureReady().then((()=>this.redraw())),this}createTile(t,e){const s=this.getTileSize(),i=r.DomUtil.create("canvas","leaflet-tile");return i.width=s.x,i.height=s.y,this.ensureReady().then((async()=>{if(this.tileProcessor)try{const r=await this.tileProcessor.getTileData({x:t.x,y:t.y,z:t.z,tileSize:s.x,resolution:this.geotiffOptions.resolution??this.defaultResolution,resampleMethod:this.geotiffOptions.resampleMethod??this.defaultResample,colorStops:this.colorStops});if(!r)return void e(null,i);const o=i.getContext("2d");if(o){const t=o.createImageData(s.x,s.y);t.data.set(r),o.putImageData(t,0,0)}e(null,i)}catch(t){e(t,i)}else e(null,i)})).catch((t=>{e(t,i)})),i}async ensureReady(){return this.loadingPromise||(this.loadingPromise=this.initializeProcessor()),this.loadingPromise}async updateSource(t){Object.assign(this.geotiffOptions,t),this.tileProcessor=null,this.colorStops=void 0,this.loadingPromise=void 0,await this.ensureReady(),this.redraw()}async initializeProcessor(){if(this.tileProcessor)return;const[t,{default:e},s]=await Promise.all([import("./geotiff.js").then((function(t){return t.g})),import("./index4.js"),import("./main-dist.js").then((function(t){return t.m}))]),i=await c(this.geotiffOptions.url,{projection:void 0,forceProjection:!1,nodata:this.geotiffOptions.nodata},{geotiff:t,proj4:e,geokeysToProj4:s}),r=t=>{const e=i.proj4(i.fromProjection,this.geotiffOptions.viewProjection,t);return[Number(e[0]),Number(e[1])]};if(this.tileProcessor=new l({transformViewToSourceMapFn:t=>{const e=i.proj4(this.geotiffOptions.viewProjection,i.fromProjection,t);return[Number(e[0]),Number(e[1])]},transformSourceMapToViewFn:r,sourceBounds:i.sourceBounds,sourceRef:i.sourceRef,resolution:i.resolution,imageWidth:i.width,imageHeight:i.height,fromProjection:i.fromProjection,toProjection:this.geotiffOptions.viewProjection,baseImage:i.baseImage,overviewImages:i.overviewImages??[]}),this.tileProcessor.createGlobalTriangulation(),this.setViewBounds(i.sourceBounds,r),this.geotiffOptions.colorMap){const{stops:t}=h(this.geotiffOptions.colorMap,this.geotiffOptions.valueRange);this.colorStops=t}}setViewBounds(t,e){const[s,i,o,a]=t,n=e([s,i]),c=e([o,i]),l=e([s,a]),h=e([o,a]),u=Math.min(n[0],c[0],l[0],h[0]),f=Math.max(n[0],c[0],l[0],h[0]),p=Math.min(n[1],c[1],l[1],h[1]),y=Math.max(n[1],c[1],l[1],h[1]),d=r.CRS.EPSG3857.unproject(r.point(u,y)),m=r.CRS.EPSG3857.unproject(r.point(f,p));this.options.bounds=r.latLngBounds(d,m)}}const m="v-map - leaflet - wcs - tile - ";class w extends r.GridLayer{wcsOptions;constructor(t){super(t),this.wcsOptions={...t,version:t.version??"2.0.1",format:t.format??"image/tiff",projection:t.projection??"EPSG:4326"}}buildWCSUrl(t){const{url:e,coverageName:s,version:i,format:r,projection:o,params:a}=this.wcsOptions,n=this._tileCoordsToBounds(t),c=n.getSouthWest(),l=n.getNorthEast(),h=c.lng,u=c.lat,f=l.lng,p=l.lat,y={SERVICE:"WCS",REQUEST:"GetCoverage",VERSION:i,FORMAT:r};if(i.startsWith("2.0")){y.coverageId=s;const t=a?{...a}:{},i={...y,...t};(r.includes("tiff")||r.includes("geotiff"))&&(i["geotiff:compression"]="LZW");const o=new URLSearchParams;Object.entries(i).forEach((([t,e])=>{null!=e&&o.set(t,String(e))}));const n=o.toString(),c=`subset=X(${h},${f})`,l=`subset=Y(${u},${p})`;return`${e}${e.includes("?")?"&":"?"}${n}&${c}&${l}`}{y.COVERAGE=s,y.BBOX=`${h},${u},${f},${p}`,y.CRS=o;const t=this.getTileSize();y.WIDTH="number"==typeof t?t:t.x,y.HEIGHT="number"==typeof t?t:t.y;const i=a?{...a}:{},r={...y,...i},n=new URLSearchParams;return Object.entries(r).forEach((([t,e])=>{null!=e&&n.set(t,String(e))})),`${e}${e.includes("?")?"&":"?"}${n.toString()}`}}createTile(t,e){const s=document.createElement("img"),i=this.buildWCSUrl(t);return a(`${m}load: coords=(${t.x},${t.y},${t.z})`),a(`${m}url: ${i}`),s.onload=()=>{e(null,s)},s.onerror=t=>{o(`${m}failed to load tile:`,t),e(t instanceof Error?t:new Error(String(t)),s)},s.crossOrigin="anonymous",s.src=i,s}updateOptions(t){this.wcsOptions={...this.wcsOptions,...t},this.redraw()}}class g{map;layers=[];baseLayers=[];hiddenLayerGroups=[];googleLogoAdded=!1;unsubscribeResize;shadowRoot;injectedStyle;layerErrorCallbacks=new Map;layerErrorCleanups=new Map;async init(o){if(!t())return;this.shadowRoot=o.shadowRoot,this.injectedStyle=function(i,o){if(t()){switch(i){case"cdn":return function(s,i=e,o="jsdelivr"){if(!t())return;const a="unpkg"===o?`https://unpkg.com/leaflet@${i}/dist/leaflet.css`:`https://cdn.jsdelivr.net/npm/leaflet@${i}/dist/leaflet.css`;r.Icon.Default.imagePath="unpkg"===o?`https://unpkg.com/npm/leaflet@${i}/dist/images/`:`https://cdn.jsdelivr.net/npm/leaflet@${i}/dist/images/`;const n=s??document;if(n.querySelector?.(`link[rel="stylesheet"][href="${a}"]`)||document.head.querySelector(`link[rel="stylesheet"][href="${a}"]`))return null;const c=document.createElement("link");return c.rel="stylesheet",c.href=a,(s??document.head).appendChild(c),c}(o);case"inline-min":return function(e){if(!t())return;const i="\n :host { display:block; }\n #map { width:100%; height:100%; display:block; }\n ";if(s()){const t=new CSSStyleSheet;t.replaceSync(i);const s=e??document;return s.adoptedStyleSheets=[...s.adoptedStyleSheets??[],t],null}{const t=document.createElement("style");return t.textContent=i,(e??document.head).appendChild(t),t}}(o)}return null}}(o.cssMode,this.shadowRoot);const[a,n]=o?.mapInitOptions?.center??[0,0];this.map=r.map(o.target,{zoomControl:!0,attributionControl:!0}).setView([n,a],o?.mapInitOptions?.zoom??2),this.unsubscribeResize=i(o.target,(()=>{this.map?.invalidateSize()}),{attributes:!0,attributeFilter:["style","class"]})}async updateLayer(t,e){const s=await this._getLayerById(t);switch(e.type){case"geojson":await this.updateGeoJSONLayer(s,e.data);break;case"osm":await this.updateOSMLayer(s,e.data);break;case"arcgis":await this.updateArcGISLayer(s,e.data);break;case"wkt":await this.updateWKTLayer(s,e.data);break;case"geotiff":await this.updateGeoTIFFLayer(s,e.data);break;case"wcs":await this.updateWCSLayer(s,e.data);break;case"wfs":s instanceof r.GeoJSON&&await this.updateWFSLayer(s,e.data)}}async addLayerToGroup(t){const e=await this._ensureGroup(t.groupId,t.groupVisible),s=await this.createLayer(t);if(null==s)return null;e.addLayer(s);const i=this.getLayerId(s);return s.vmapVisible=!0,s.vmapOpacity=1,void 0!==t.opacity&&this.setOpacityByLayer(s,t.opacity),void 0!==t.zIndex&&s.setZIndex?.(t.zIndex),t.visible?this.setVisibleByLayer(s,!0):!1===t.visible&&this.setVisibleByLayer(s,!1),i}async addBaseLayer(t,e,s){if(null==s)return a("leaflet - addBaseLayer - layerElementId not set."),null;null==e&&a("leaflet - addBaseLayer - basemapid not set.");const i=await this._ensureGroup(t.groupId,t.groupVisible);i.basemap=!0;const r=await this.createLayer(t);if(this.baseLayers.push(r),null==r)return null;r.layerElementId=s;const o=this.getLayerId(r);if(r.vmapVisible=!0,r.vmapOpacity=1,void 0!==t.opacity&&this.setOpacityByLayer(r,t.opacity),void 0!==t.zIndex&&r.setZIndex?.(t.zIndex),t.visible?this.setVisibleByLayer(r,!0):!1===t.visible&&this.setVisibleByLayer(r,!1),e===s){const t=i.getLayers()[0];t&&(this.map.removeLayer(t),i.clearLayers()),i.addLayer(r),i.visible&&r.addTo(this.map)}return o}async setBaseLayer(t,e){if(null===e)return void a("leaflet - setBaseLayer - layerElementId is null.");const s=this.layers.find((e=>e._groupId===t)),i=this.baseLayers.find((t=>t.layerElementId===e));if(void 0===i)return void a("leaflet - setBaseLayer - layer not found. layerElementId: "+e);if(!s)return;const r=s.getLayers()[0];r&&(this.map.removeLayer(r),s.clearLayers()),s.addLayer(i)}getLayerId(t){return String(r.Util.stamp(t))}normalizeAttribution(t){return Array.isArray(t)?t.join(", "):t}async _getLayerById(t){let e=null;return this.map?.eachLayer((s=>{this.getLayerId(s)===t&&(e=s)})),e||(e=this.baseLayers.find((e=>this.getLayerId(e)===t))??null,void 0===e?null:e)}async createLayer(t){switch(t.type){case"geojson":return this.createGeoJSONLayer(t);case"xyz":return this.createXYZLayer(t);case"osm":return this.createOSMLayer(t);case"wms":return this.createWMSLayer(t);case"wcs":return this.createWCSLayer(t);case"wfs":return this.createWFSLayer(t);case"arcgis":return this.createArcGISLayer(t);case"google":return this.createGoogleLayer(t);case"wkt":return this.createWKTLayer(t);case"geotiff":return this.createGeoTIFFLayer(t);default:throw new Error(`Unsupported layer type: ${t.type}`)}}async updateGeoJSONLayer(t,e){if(!(t instanceof r.GeoJSON))return;let s=null;if(e.geojson)s=JSON.parse(e.geojson);else if(e.url){const t=await fetch(e.url);if(!t.ok)throw new Error(`GeoJSON fetch failed: ${t.status} ${t.statusText}`);s=await t.json()}t.clearLayers(),t.addData(s)}async createGeoJSONLayer(t){let e=null;if(t.geojson)e=JSON.parse(t.geojson);else if(t.url){const s=await fetch(t.url);if(!s.ok)throw new Error(`GeoJSON fetch failed: ${s.status} ${s.statusText}`);e=await s.json()}if(e){let s={};if(t.geostylerStyle)s=await this.createGeostylerLeafletOptions(t.geostylerStyle);else{const e=t.style?{...n,...t.style}:n;s={style:this.createLeafletStyle(e),pointToLayer:(t,s)=>this.createLeafletPoint(t,s,e),onEachFeature:(t,s)=>this.bindLeafletPopup(t,s,e)}}return r.geoJSON(e,s)}return null}async createXYZLayer(t){return r.tileLayer(t.url,{attribution:this.normalizeAttribution(t.attributions),maxZoom:t.maxZoom??19,...t.options??{}})}async updateOSMLayer(t,e){if(!("setUrl"in t)||"function"!=typeof t.setUrl)return;let s="https://tile.openstreetmap.org/{z}/{x}/{y}.png";e.url&&(s=e.url+"/{z}/{x}/{y}.png"),t.setUrl(s)}async createOSMLayer(t){let e="https://tile.openstreetmap.org/{z}/{x}/{y}.png";return t.url&&(e=t.url+"/{z}/{x}/{y}.png"),r.tileLayer(e,{attribution:"© OpenStreetMap contributors",maxZoom:19})}async createWMSLayer(t){return r.tileLayer.wms(t.url,{layers:t.layers,format:t.format??"image/png",transparent:t.transparent??!0,...t.extraParams??{}})}buildArcGISUrl(t,e){if(!e||0===Object.keys(e).length)return t;const s=new URLSearchParams;return Object.entries(e).forEach((([t,e])=>{null!=e&&s.set(t,String(e))})),0===s.toString().length?t:`${t}${t.includes("?")?"&":"?"}${s.toString()}`}async createArcGISLayer(t){const e={...t.params??{}};t.token&&(e.token=t.token);const s=this.buildArcGISUrl(t.url,e),i={attribution:this.normalizeAttribution(t.attributions),minZoom:t.minZoom,maxZoom:t.maxZoom,...t.options??{}};return r.tileLayer(s,i)}async updateArcGISLayer(t,e){const s={...e?.params??{}};e?.token&&(s.token=e.token);const i=t,r=this.buildArcGISUrl(e?.url??i.options?.url??"",s);"setUrl"in i&&"function"==typeof i.setUrl&&i.setUrl(r)}async createGoogleLayer(t){if(!this.map)throw new Error("Map not initialized");if(!t.apiKey)throw new Error("Google-Layer benötigt 'apiKey' (Google Maps Platform).");const e="string"==typeof t.styles?this.tryParseStyles(t.styles):t.styles,s=new y({apiKey:t.apiKey,mapType:t.mapType??"roadmap",language:t.language,region:t.region,scale:t.scale,highDpi:t.highDpi,layerTypes:t.layerTypes,overlay:t.overlay,styles:Array.isArray(e)?e:void 0,imageFormat:t.imageFormat,apiOptions:t.apiOptions,maxZoom:t.maxZoom??22});return o=()=>{this.googleLogoAdded=!0,a("v-map - provider - leaflet - googleLogoAdded: ",this.googleLogoAdded)},(i=this.map)._googleLogoAdded||(new(r.Control.extend({onAdd(){const t=r.DomUtil.create("img");return t.src="https://developers.google.com/static/maps/documentation/images/google_on_white.png",t.alt="Google",t.style.pointerEvents="none",t.style.height="18px",t.style.margin="0 0 6px 6px",t},onRemove(){}}))({position:"bottomleft"}).addTo(i),i._googleLogoAdded=!0,o()),s;var i,o}tryParseStyles(t){try{const e=JSON.parse(t);return Array.isArray(e)?e:void 0}catch{return void o("Failed to parse Google styles JSON")}}async destroy(){var t;this.unsubscribeResize?.(),t=this.injectedStyle,this.shadowRoot&&t&&t.remove();for(const t of this.layers)this.map?.removeLayer(t);this.layers=[],this.map?.remove(),this.map=void 0}async setView([t,e],s){this.map?.setView([e,t],s,{animate:!1})}onLayerError(t,e){this.layerErrorCallbacks.set(t,e),this._getLayerById(t).then((s=>{if(!s)return;const i=()=>{e({type:"network",message:"Tile load error"})};s.on("tileerror",i),this.layerErrorCleanups.set(t,(()=>s.off("tileerror",i)))}))}offLayerError(t){this.layerErrorCleanups.get(t)?.(),this.layerErrorCleanups.delete(t),this.layerErrorCallbacks.delete(t)}async removeLayer(t){if(!t)return;this.offLayerError(t);const e=await this._getLayerById(t);e&&this.map.removeLayer(e)}async setZIndex(t,e){if(!t)return;const s=await this._getLayerById(t);s&&"function"==typeof s.setZIndex&&s.setZIndex(e)}async setOpacity(t,e){if(!t)return;const s=await this._getLayerById(t);this.setOpacityByLayer(s,e)}setOpacityByLayer(t,e){t&&(t.vmapOpacity=e,void 0===t.vmapVisible&&(t.vmapVisible=!0),!1!==t.vmapVisible&&this.setLayerOpacity(t,e))}async setVisible(t,e){if(!t)return;const s=await this._getLayerById(t);this.setVisibleByLayer(s,e)}setVisibleByLayer(t,e){t&&(t.vmapVisible=e,void 0===t.vmapOpacity&&(t.vmapOpacity=1),this.setLayerOpacity(t,e?t.vmapOpacity:0))}setLayerOpacity(t,e){if(!t)return;const s="number"==typeof e?e:e.opacity??1,i="number"==typeof e?e:e.fillOpacity??s,o=(t,e)=>{if(!(e in r))return!1;const s=r[e];return"function"==typeof s&&t instanceof s};var a;o(a=t,"GeoJSON")||o(a,"LayerGroup")?t.eachLayer((t=>this.setLayerOpacity(t,e))):(t=>o(t,"Path"))(t)?t.setStyle({opacity:s,fillOpacity:i}):((t=>o(t,"Marker"))(t)||"setOpacity"in t)&&t.setOpacity(s)}async ensureGroup(t,e,s){await this._ensureGroup(t,e)}async _ensureGroup(t,e){let s=await this._getLayerGroupById(t);return s||(s=r.layerGroup(),s._groupId=t,s.visible=!0,s.addTo(this.map),this.layers.push(s)),this.setGroupVisible(t,void 0===e||e),s}async _getLayerGroupById(t){if(!this.map)return null;let e=this.layers.find((e=>e instanceof r.LayerGroup&&e._groupId===t));return e||(e=this.hiddenLayerGroups.find((e=>e._groupId===t)),e)?e:null}async setGroupVisible(t,e){const s=await this._getLayerGroupById(t);if(s){if(s.visible===e)return;!1===s.visible?(s.addTo(this.map),this.hiddenLayerGroups=this.hiddenLayerGroups.filter((e=>e._groupId!==t)),s.visible=e):!0===s.visible&&(this.map.removeLayer(s),s.visible=e,this.hiddenLayerGroups.push(s))}}async updateWKTLayer(t,e){if(!(t instanceof r.GeoJSON))return;let s=null;if(e.wkt)s=await this.wktToGeoJSON(e.wkt);else if(e.url)try{const t=await fetch(e.url);if(!t.ok)throw new Error(`Failed to fetch WKT: ${t.status}`);const i=await t.text();s=await this.wktToGeoJSON(i)}catch(t){return void o("Failed to load WKT from URL:",t)}if(s){t.clearLayers();const i=t;i.options.style=this.createLeafletStyle(e.style),i.options.pointToLayer=(t,s)=>this.createLeafletPoint(t,s,e.style),i.options.onEachFeature=(t,s)=>this.bindLeafletPopup(t,s,e.style),i.addData(s)}}async createWKTLayer(t){let e=null;const s={type:"FeatureCollection",features:[]};if(t.wkt)e=await this.wktToGeoJSON(t.wkt);else if(t.url)try{const s=await fetch(t.url);if(!s.ok)throw new Error(`Failed to fetch WKT: ${s.status}`);const i=await s.text();e=await this.wktToGeoJSON(i)}catch(t){o("Failed to load WKT from URL:",t),e=s}else e=s;a("[Leaflet WKT] Creating layer with GeoJSON data:",e),a("[Leaflet WKT] Config:",t);let i={};if(t.geostylerStyle)i=await this.createGeostylerLeafletOptions(t.geostylerStyle);else{const e=t.style?{...n,...t.style}:n;i={style:this.createLeafletStyle(e),pointToLayer:(t,s)=>this.createLeafletPoint(t,s,e),onEachFeature:(t,s)=>this.bindLeafletPopup(t,s,e)}}a("[Leaflet WKT] Layer options:",i);const c=r.geoJSON(e,i);return a("[Leaflet WKT] Created layer:",c),"function"==typeof c.getBounds&&a("[Leaflet WKT] Layer bounds:",c.getBounds()),c}async wktToGeoJSON(t){try{const e=u.wellknown.parse(t);if(!e)throw new Error("Failed to parse WKT - returned null");const s={type:"Feature",geometry:e,properties:{}};return a("[Leaflet WKT] Input WKT:",t),a("[Leaflet WKT] Generated GeoJSON:",JSON.stringify(s,null,2)),{type:"FeatureCollection",features:[s]}}catch(e){return o("[Leaflet WKT] Failed to parse WKT:",t,e),{type:"FeatureCollection",features:[]}}}async createGeoTIFFLayer(t){if(!t.url)throw new Error("GeoTIFF layer requires a URL");try{const e=new d({url:t.url,tileSize:256,colorMap:t.colorMap,valueRange:t.valueRange,nodata:t.nodata,resolution:t.resolution,resampleMethod:t.resampleMethod,viewProjection:this.map.options.crs.code});return void 0!==t.opacity&&e.setOpacity?.(t.opacity),void 0!==t.zIndex&&e.setZIndex?.(t.zIndex),e}catch(t){return o("Failed to create GeoTIFF layer:",t),r.layerGroup([])}}async updateGeoTIFFLayer(t,e){if(!e.url)throw new Error("GeoTIFF update requires a URL");if(!t)return;if(!(t instanceof d))return;const s=e;await t.updateSource({url:e.url,colorMap:e.colorMap,valueRange:e.valueRange,nodata:e.nodata,resolution:s.resolution,resampleMethod:s.resampleMethod})}async createWCSLayer(t){if(!t.url)throw new Error("WCS layer requires a URL");if(!t.coverageName)throw new Error("WCS layer requires a coverageName");try{const e={url:t.url,coverageName:t.coverageName,version:t.version??"2.0.1",format:t.format??"image/tiff",projection:t.projection??"EPSG:4326",params:t.params};t.tileSize&&(e.tileSize=t.tileSize),void 0!==t.minZoom&&(e.minZoom=t.minZoom),void 0!==t.maxZoom&&(e.maxZoom=t.maxZoom);const s=new w(e);return void 0!==t.opacity&&s.setOpacity?.(t.opacity),void 0!==t.zIndex&&s.setZIndex?.(t.zIndex),s}catch(t){return o("[Leaflet WCS] Failed to create WCS layer:",t),r.layerGroup([])}}async updateWCSLayer(t,e){if(t&&t instanceof w){const s={};e.url&&(s.url=e.url),e.coverageName&&(s.coverageName=e.coverageName),e.version&&(s.version=e.version),e.format&&(s.format=e.format),e.projection&&(s.projection=e.projection),e.params&&(s.params=e.params),t.updateOptions(s)}}async createGeostylerLeafletOptions(t){const e=(t,e)=>null==t||"object"==typeof t&&t.name?e:t;return{style:s=>{const i=s?.geometry?.type;let r={};if(t.rules)for(const s of t.rules)if(s.symbolizers)for(const t of s.symbolizers)switch(t.kind){case"Fill":if("Polygon"===i||"MultiPolygon"===i){const s=e(t.color,"rgba(0,100,255,0.3)"),i=e(t.opacity,.3),o=e(t.outlineColor,"rgba(0,100,255,1)"),a=e(t.outlineWidth,1);r={...r,fillColor:s,fillOpacity:i,color:o,weight:a}}break;case"Line":const s=e(t.color,"rgba(0,100,255,1)"),o=e(t.width,2),a=t.dasharray&&Array.isArray(t.dasharray)?t.dasharray.map((t=>e(t,0))).join(","):void 0;r={...r,color:s,weight:o,dashArray:a}}return r},pointToLayer:(s,i)=>{if(t.rules)for(const s of t.rules)if(s.symbolizers)for(const t of s.symbolizers)switch(t.kind){case"Mark":const s=e(t.color,"rgba(0,100,255,1)"),o=e(t.radius,6),a=e(t.strokeColor,"rgba(0,100,255,1)"),n=e(t.strokeWidth,2);return r.circleMarker(i,{radius:o,fillColor:s,fillOpacity:1,color:a,weight:n});case"Icon":const c=e(t.image),l=e(t.size,32);if(c&&"string"==typeof c){const t=r.icon({iconUrl:c,iconSize:[l,l],iconAnchor:[l/2,l]});return r.marker(i,{icon:t})}}return r.circleMarker(i,{radius:6,fillColor:"rgba(0,100,255,1)",fillOpacity:1,color:"rgba(0,100,255,1)",weight:2})},onEachFeature:(s,i)=>{if(t.rules)for(const r of t.rules)if(r.symbolizers)for(const t of r.symbolizers)if("Text"===t.kind){const r=t.label;if(r&&"string"==typeof r&&s.properties&&s.properties[r]){const o=String(s.properties[r]),a=e(t.color,"#000000"),n=e(t.size,12);i.bindTooltip(`<div style="color: ${a}; font-size: ${n}px; font-family: Arial, sans-serif;">${o}</div>`,{permanent:!0,direction:"center",className:"leaflet-tooltip-custom"})}}}}}createLeafletStyle(t){return e=>{const s=e?.geometry?.type,i=t?.fillColor??"rgba(0,100,255,0.3)",r=t?.fillOpacity??.3,o=t?.strokeColor??"rgba(0,100,255,1)",a=t?.strokeOpacity??1,n=t?.strokeWidth??2;return"Polygon"===s||"MultiPolygon"===s?{fillColor:i,fillOpacity:r,color:o,opacity:a,weight:n,dashArray:t?.strokeDashArray?t.strokeDashArray.join(","):void 0}:"LineString"===s||"MultiLineString"===s?{color:o,opacity:a,weight:n,dashArray:t?.strokeDashArray?t.strokeDashArray.join(","):void 0}:{}}}createLeafletPoint(t,e,s){let i={...s??{}};if(s?.styleFunction){const e=s.styleFunction(t);e&&(i={...s,...e})}if(i?.iconUrl){const t=i.iconSize||[32,32],s=r.icon({iconUrl:i.iconUrl,iconSize:t,iconAnchor:i.iconAnchor||[t[0]/2,t[1]]});return r.marker(e,{icon:s})}{const t=i?.pointColor??"rgba(0,100,255,1)",s=i?.pointOpacity??1;return r.circleMarker(e,{radius:i?.pointRadius??6,fillColor:t,fillOpacity:s,color:i?.strokeColor??"rgba(0,100,255,1)",opacity:i?.strokeOpacity??1,weight:i?.strokeWidth??2})}}bindLeafletPopup(t,e,s){if(s?.textProperty&&t.properties&&t.properties[s.textProperty]){const i=String(t.properties[s.textProperty]);e.bindTooltip(`<div style="color: ${s?.textColor??"#000000"}; font-size: ${s?.textSize??12}px; font-family: Arial, sans-serif;">${i}</div>`,{permanent:!0,direction:"center",className:"leaflet-tooltip-custom"})}}async createWFSLayer(t){const e=await this.fetchWFSFromUrl(t);let s={};if(t.geostylerStyle)s=await this.createGeostylerLeafletOptions(t.geostylerStyle);else{const e=t.style?{...n,...t.style}:n;s={style:this.createLeafletStyle(e),pointToLayer:(t,s)=>this.createLeafletPoint(t,s,e),onEachFeature:(t,s)=>this.bindLeafletPopup(t,s,e)}}return r.geoJSON(e,s)}async updateWFSLayer(t,e){const s=await this.fetchWFSFromUrl(e);t.clearLayers(),t.addData(s)}async fetchWFSFromUrl(t){const e={service:"WFS",request:"GetFeature",version:t.version??"1.1.0",typeName:t.typeName,outputFormat:t.outputFormat??"application/json",srsName:t.srsName??"EPSG:4326",...t.params??{}},s=this.appendParams(t.url,e),i=await fetch(s);if(!i.ok)throw new Error(`WFS request failed (${i.status} ${i.statusText})`);const r=(t.outputFormat??"application/json").toLowerCase();if(r.includes("json")||r.includes("geojson")||"application/json"===r)return await i.json();if(r.includes("gml")||r.includes("xml")){const t=await i.text(),e=new f;return await e.parse(t)}return await i.json()}appendParams(t,e){const s=new URLSearchParams;return Object.entries(e).forEach((([t,e])=>{null!=e&&s.set(t,String(e))})),s.toString()?`${t}${t.includes("?")?"&":"?"}${s.toString()}`:t}getMap(){return this.map}}export{g as LeafletProvider}
|
|
1
|
+
import{i as t,L as e,s,w as i}from"./v-map2.js";import*as r from"leaflet";import{e as o,l as a}from"./logger.js";import{D as n}from"./styleconfig.js";import{l as c,G as l,g as h}from"./geotiff-source.js";import{w as u}from"./index5.js";import{GmlParser as f}from"./index.browser.js";const p=256;class y extends r.GridLayer{apiKey;highDpi;sessionRequest;scaleFactor;sessionToken;sessionPromise;sessionRefreshId;previousViewport;currentAttribution;mapInstance;onMoveEnd;constructor(t){super(),this.applyInitialGridOptions(t);const{apiKey:e,mapType:s,language:i,region:r,imageFormat:o,scale:a,highDpi:n,layerTypes:c,overlay:l,styles:h,apiOptions:u}=t;if(!e)throw new Error("Google Map Tiles layer requires an apiKey");this.apiKey=e,this.highDpi=n??(void 0===a||"scaleFactor1x"!==a),this.scaleFactor=this.mapScaleToFactor(a,this.highDpi);const f={mapType:s??"roadmap",language:i??"en-US",region:r??"US"};o&&(f.imageFormat=o),c?.length&&(f.layerTypes=c),u?.length&&(f.apiOptions=u),Array.isArray(h)&&h.length>0&&(f.styles=h),!0===l&&(f.overlay=!0);const p=a??(this.scaleFactor>1?this.factorToScale(this.scaleFactor):void 0);p&&(f.scale=p),this.highDpi&&(f.highDpi=!0),this.sessionRequest=f,this.onMoveEnd=()=>{this.updateAttribution()},this.sessionPromise=this.startSessionFetch()}onAdd(t){return this.mapInstance=t,t.on("moveend",this.onMoveEnd),t.on("zoomend",this.onMoveEnd),this.ensureSession().then((()=>this.updateAttribution())),super.onAdd(t)}onRemove(t){return t.off("moveend",this.onMoveEnd),t.off("zoomend",this.onMoveEnd),this.clearSessionRefresh(),this.removeCurrentAttribution(),this.mapInstance=void 0,super.onRemove(t)}createTile(t,e){const s=document.createElement("img");s.decoding="async",s.alt="",s.crossOrigin="anonymous";const i=this.resolveTileSize();s.width=i.x,s.height=i.y;const r=t=>{const i=t instanceof Error?t.message:"Google tile load error";e(new Error(i),s)};return s.onload=()=>e(null,s),s.onerror=t=>{const e=t instanceof ErrorEvent?t.error??new Error(t.message):new Error("Google tile failed to load");r(e)},this.ensureSession().then((()=>{this.sessionToken?s.src=this.buildTileUrl(t):r(new Error("Google Maps session unavailable"))})).catch((t=>{r(t)})),s}ensureSession(){return this.sessionToken?Promise.resolve():(this.sessionPromise||(this.sessionPromise=this.startSessionFetch()),this.sessionPromise)}startSessionFetch(t=!1){if(this.sessionPromise&&!t)return this.sessionPromise;const e=this.fetchAndApplySession().catch((t=>{const e=t instanceof Error?t:new Error("Failed to create Google Maps session");throw o("Google Map Tiles session error",e),this.sessionToken=void 0,e})).finally((()=>{this.sessionPromise===e&&(this.sessionPromise=void 0)}));return this.sessionPromise=e,e}async fetchAndApplySession(){const t=`https://tile.googleapis.com/v1/createSession?key=${this.apiKey}`,e=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(this.sessionRequest)});if(!e.ok){let t;try{const s=await e.json();t=s?.error?.message}catch{}throw new Error(t??`Google Maps session request failed (${e.status})`)}const s=await e.json();this.sessionToken=s.session,this.applyTileSize(s),this.scheduleSessionRefresh(this.parseExpiry(s.expiry)),this.mapInstance&&(this.updateAttribution(),this.redrawLayer()),a("Google Map Tiles session established")}scheduleSessionRefresh(t){if(!isFinite(t))return;const e=Math.max(t-Date.now()-6e4,1e3);this.clearSessionRefresh(),this.sessionRefreshId=setTimeout((()=>{this.startSessionFetch(!0).then((()=>{this.mapInstance&&(this.updateAttribution(),this.redrawLayer())}))}),e)}clearSessionRefresh(){void 0!==this.sessionRefreshId&&(clearTimeout(this.sessionRefreshId),this.sessionRefreshId=void 0)}async updateAttribution(){if(!this.mapInstance||!this.sessionToken)return;const t=this.mapInstance.getBounds();if(!t?.isValid())return;const e=`zoom=${this.mapInstance.getZoom()}&north=${t.getNorth()}&south=${t.getSouth()}&east=${t.getEast()}&west=${t.getWest()}`;if(this.previousViewport!==e){this.previousViewport=e;try{const t=await fetch(`https://tile.googleapis.com/tile/v1/viewport?session=${this.sessionToken}&key=${this.apiKey}&${e}`);if(!t.ok)throw new Error(`Attribution request failed (${t.status})`);const s=await t.json(),i=s?.copyright;"string"==typeof i&&i.length>0&&this.applyAttribution(i)}catch(t){o("Failed to fetch Google attribution",t)}}}applyAttribution(t){const e=this.mapInstance;e?.attributionControl&&(this.currentAttribution&&this.currentAttribution!==t&&e.attributionControl.removeAttribution(this.currentAttribution),this.currentAttribution&&this.currentAttribution===t||(e.attributionControl.addAttribution(t),this.currentAttribution=t))}removeCurrentAttribution(){const t=this.mapInstance;t?.attributionControl&&this.currentAttribution&&(t.attributionControl.removeAttribution(this.currentAttribution),this.currentAttribution=void 0)}applyTileSize(t){const e=Math.max(1,Math.round(t.tileWidth/this.scaleFactor)),s=Math.max(1,Math.round(t.tileHeight/this.scaleFactor)),i=r.point(e,s);this.setGridOptions({tileSize:i})}parseExpiry(t){const e=parseInt(t,10);return Number.isFinite(e)?1e3*e:Number.NaN}buildTileUrl(t){if(!this.sessionToken)throw new Error("Google Maps session missing");return`https://tile.googleapis.com/v1/2dtiles/${t.z}/${t.x}/${t.y}?session=${this.sessionToken}&key=${this.apiKey}`}mapScaleToFactor(t,e){switch(t){case"scaleFactor4x":return 4;case"scaleFactor2x":return 2;case"scaleFactor1x":return 1;default:return e?2:1}}factorToScale(t){switch(t){case 4:return"scaleFactor4x";case 2:return"scaleFactor2x";case 1:return"scaleFactor1x";default:return}}applyInitialGridOptions(t){const e={},s=["attribution","bounds","className","detectRetina","errorTileUrl","keepBuffer","maxNativeZoom","maxZoom","minNativeZoom","minZoom","noWrap","opacity","pane","reuseTiles","subdomains","tileSize","tms","updateInterval","updateWhenIdle","updateWhenZooming","zIndex","zoomOffset"];for(const i of s){const s=t[i];void 0!==s&&(e[i]=s)}void 0===e.maxZoom&&(e.maxZoom=22),this.setGridOptions(e)}setGridOptions(t){const e=r.Util?.setOptions;if("function"==typeof e)e(this,t);else{const e=this;e.options={...e.options,...t}}}resolveTileSize(){const t=this.options?.tileSize;if(t&&"object"==typeof t){if(Array.isArray(t)&&2===t.length){const[e,s]=t;return r.point(Number(e)||p,Number(s)||p)}if("x"in t&&"y"in t){const e=t;return r.point(Number(e.x)||p,Number(e.y)||p)}}return"number"==typeof t&&Number.isFinite(t)?r.point(t,t):r.point(p,p)}redrawLayer(){this.redraw()}}class d extends r.GridLayer{geotiffOptions;tileProcessor=null;colorStops;loadingPromise;defaultResolution=1;defaultResample="bilinear";constructor(t){super(t),this.geotiffOptions={...t}}onAdd(t){return super.onAdd(t),this.ensureReady().then((()=>this.redraw())),this}createTile(t,e){const s=this.getTileSize(),i=r.DomUtil.create("canvas","leaflet-tile");return i.width=s.x,i.height=s.y,this.ensureReady().then((async()=>{if(this.tileProcessor)try{const r=await this.tileProcessor.getTileData({x:t.x,y:t.y,z:t.z,tileSize:s.x,resolution:this.geotiffOptions.resolution??this.defaultResolution,resampleMethod:this.geotiffOptions.resampleMethod??this.defaultResample,colorStops:this.colorStops});if(!r)return void e(null,i);const o=i.getContext("2d");if(o){const t=o.createImageData(s.x,s.y);t.data.set(r),o.putImageData(t,0,0)}e(null,i)}catch(t){e(t,i)}else e(null,i)})).catch((t=>{e(t,i)})),i}async ensureReady(){return this.loadingPromise||(this.loadingPromise=this.initializeProcessor()),this.loadingPromise}async updateSource(t){Object.assign(this.geotiffOptions,t),this.tileProcessor=null,this.colorStops=void 0,this.loadingPromise=void 0,await this.ensureReady(),this.redraw()}async initializeProcessor(){if(this.tileProcessor)return;const[t,{default:e},s]=await Promise.all([import("./geotiff.js").then((function(t){return t.g})),import("./index4.js"),import("./main-dist.js").then((function(t){return t.m}))]),i=await c(this.geotiffOptions.url,{projection:void 0,forceProjection:!1,nodata:this.geotiffOptions.nodata},{geotiff:t,proj4:e,geokeysToProj4:s}),r=t=>{const e=i.proj4(i.fromProjection,this.geotiffOptions.viewProjection,t);return[Number(e[0]),Number(e[1])]};if(this.tileProcessor=new l({transformViewToSourceMapFn:t=>{const e=i.proj4(this.geotiffOptions.viewProjection,i.fromProjection,t);return[Number(e[0]),Number(e[1])]},transformSourceMapToViewFn:r,sourceBounds:i.sourceBounds,sourceRef:i.sourceRef,resolution:i.resolution,imageWidth:i.width,imageHeight:i.height,fromProjection:i.fromProjection,toProjection:this.geotiffOptions.viewProjection,baseImage:i.baseImage,overviewImages:i.overviewImages??[]}),this.tileProcessor.createGlobalTriangulation(),this.setViewBounds(i.sourceBounds,r),this.geotiffOptions.colorMap){const{stops:t}=h(this.geotiffOptions.colorMap,this.geotiffOptions.valueRange);this.colorStops=t}}setViewBounds(t,e){const[s,i,o,a]=t,n=e([s,i]),c=e([o,i]),l=e([s,a]),h=e([o,a]),u=Math.min(n[0],c[0],l[0],h[0]),f=Math.max(n[0],c[0],l[0],h[0]),p=Math.min(n[1],c[1],l[1],h[1]),y=Math.max(n[1],c[1],l[1],h[1]),d=r.CRS.EPSG3857.unproject(r.point(u,y)),m=r.CRS.EPSG3857.unproject(r.point(f,p));this.options.bounds=r.latLngBounds(d,m)}}const m="v-map - leaflet - wcs - tile - ";class w extends r.GridLayer{wcsOptions;constructor(t){super(t),this.wcsOptions={...t,version:t.version??"2.0.1",format:t.format??"image/tiff",projection:t.projection??"EPSG:4326"}}buildWCSUrl(t){const{url:e,coverageName:s,version:i,format:r,projection:o,params:a}=this.wcsOptions,n=this._tileCoordsToBounds(t),c=n.getSouthWest(),l=n.getNorthEast(),h=c.lng,u=c.lat,f=l.lng,p=l.lat,y={SERVICE:"WCS",REQUEST:"GetCoverage",VERSION:i,FORMAT:r};if(i.startsWith("2.0")){y.coverageId=s;const t=a?{...a}:{},i={...y,...t};(r.includes("tiff")||r.includes("geotiff"))&&(i["geotiff:compression"]="LZW");const o=new URLSearchParams;Object.entries(i).forEach((([t,e])=>{null!=e&&o.set(t,String(e))}));const n=o.toString(),c=`subset=X(${h},${f})`,l=`subset=Y(${u},${p})`;return`${e}${e.includes("?")?"&":"?"}${n}&${c}&${l}`}{y.COVERAGE=s,y.BBOX=`${h},${u},${f},${p}`,y.CRS=o;const t=this.getTileSize();y.WIDTH="number"==typeof t?t:t.x,y.HEIGHT="number"==typeof t?t:t.y;const i=a?{...a}:{},r={...y,...i},n=new URLSearchParams;return Object.entries(r).forEach((([t,e])=>{null!=e&&n.set(t,String(e))})),`${e}${e.includes("?")?"&":"?"}${n.toString()}`}}createTile(t,e){const s=document.createElement("img"),i=this.buildWCSUrl(t);return a(`${m}load: coords=(${t.x},${t.y},${t.z})`),a(`${m}url: ${i}`),s.onload=()=>{e(null,s)},s.onerror=t=>{o(`${m}failed to load tile:`,t),e(t instanceof Error?t:new Error(String(t)),s)},s.crossOrigin="anonymous",s.src=i,s}updateOptions(t){this.wcsOptions={...this.wcsOptions,...t},this.redraw()}}class g{map;layers=[];baseLayers=[];hiddenLayerGroups=[];googleLogoAdded=!1;unsubscribeResize;shadowRoot;injectedStyle;layerErrorCallbacks=new Map;layerErrorCleanups=new Map;async init(o){if(!t())return;this.shadowRoot=o.shadowRoot,this.injectedStyle=function(i,o){if(t()){switch(i){case"cdn":return function(s,i=e,o="jsdelivr"){if(!t())return;const a="unpkg"===o?`https://unpkg.com/leaflet@${i}/dist/leaflet.css`:`https://cdn.jsdelivr.net/npm/leaflet@${i}/dist/leaflet.css`;r.Icon.Default.imagePath="unpkg"===o?`https://unpkg.com/npm/leaflet@${i}/dist/images/`:`https://cdn.jsdelivr.net/npm/leaflet@${i}/dist/images/`;const n=s??document;if(n.querySelector?.(`link[rel="stylesheet"][href="${a}"]`)||document.head.querySelector(`link[rel="stylesheet"][href="${a}"]`))return null;const c=document.createElement("link");return c.rel="stylesheet",c.href=a,(s??document.head).appendChild(c),c}(o);case"inline-min":return function(e){if(!t())return;const i="\n :host { display:block; }\n #map { width:100%; height:100%; display:block; }\n ";if(s()){const t=new CSSStyleSheet;t.replaceSync(i);const s=e??document;return s.adoptedStyleSheets=[...s.adoptedStyleSheets??[],t],null}{const t=document.createElement("style");return t.textContent=i,(e??document.head).appendChild(t),t}}(o)}return null}}(o.cssMode,this.shadowRoot);const[a,n]=o?.mapInitOptions?.center??[0,0];this.map=r.map(o.target,{zoomControl:!0,attributionControl:!0}).setView([n,a],o?.mapInitOptions?.zoom??2),this.unsubscribeResize=i(o.target,(()=>{this.map?.invalidateSize()}),{attributes:!0,attributeFilter:["style","class"]})}async updateLayer(t,e){const s=await this._getLayerById(t);switch(e.type){case"geojson":await this.updateGeoJSONLayer(s,e.data);break;case"osm":await this.updateOSMLayer(s,e.data);break;case"arcgis":await this.updateArcGISLayer(s,e.data);break;case"wkt":await this.updateWKTLayer(s,e.data);break;case"geotiff":await this.updateGeoTIFFLayer(s,e.data);break;case"wcs":await this.updateWCSLayer(s,e.data);break;case"wfs":s instanceof r.GeoJSON&&await this.updateWFSLayer(s,e.data)}}async addLayerToGroup(t){const e=await this._ensureGroup(t.groupId,t.groupVisible),s=await this.createLayer(t);if(null==s)return null;e.addLayer(s);const i=this.getLayerId(s);return s.vmapVisible=!0,s.vmapOpacity=1,void 0!==t.opacity&&this.setOpacityByLayer(s,t.opacity),void 0!==t.zIndex&&s.setZIndex?.(t.zIndex),t.visible?this.setVisibleByLayer(s,!0):!1===t.visible&&this.setVisibleByLayer(s,!1),i}async addBaseLayer(t,e,s){if(null==s)return a("leaflet - addBaseLayer - layerElementId not set."),null;null==e&&a("leaflet - addBaseLayer - basemapid not set.");const i=await this._ensureGroup(t.groupId,t.groupVisible);i.basemap=!0;const r=await this.createLayer(t);if(this.baseLayers.push(r),null==r)return null;r.layerElementId=s;const o=this.getLayerId(r);if(r.vmapVisible=!0,r.vmapOpacity=1,void 0!==t.opacity&&this.setOpacityByLayer(r,t.opacity),void 0!==t.zIndex&&r.setZIndex?.(t.zIndex),t.visible?this.setVisibleByLayer(r,!0):!1===t.visible&&this.setVisibleByLayer(r,!1),e===s){const t=i.getLayers()[0];t&&(this.map.removeLayer(t),i.clearLayers()),i.addLayer(r),i.visible&&r.addTo(this.map)}return o}async setBaseLayer(t,e){if(null===e)return void a("leaflet - setBaseLayer - layerElementId is null.");const s=this.layers.find((e=>e._groupId===t)),i=this.baseLayers.find((t=>t.layerElementId===e));if(void 0===i)return void a("leaflet - setBaseLayer - layer not found. layerElementId: "+e);if(!s)return;const r=s.getLayers()[0];r&&(this.map.removeLayer(r),s.clearLayers()),s.addLayer(i)}getLayerId(t){return String(r.Util.stamp(t))}normalizeAttribution(t){return Array.isArray(t)?t.join(", "):t}async _getLayerById(t){let e=null;return this.map?.eachLayer((s=>{this.getLayerId(s)===t&&(e=s)})),e||(e=this.baseLayers.find((e=>this.getLayerId(e)===t))??null,void 0===e?null:e)}async createLayer(t){switch(t.type){case"geojson":return this.createGeoJSONLayer(t);case"xyz":return this.createXYZLayer(t);case"osm":return this.createOSMLayer(t);case"wms":return this.createWMSLayer(t);case"wcs":return this.createWCSLayer(t);case"wfs":return this.createWFSLayer(t);case"arcgis":return this.createArcGISLayer(t);case"google":return this.createGoogleLayer(t);case"wkt":return this.createWKTLayer(t);case"geotiff":return this.createGeoTIFFLayer(t);default:throw new Error(`Unsupported layer type: ${t.type}`)}}async updateGeoJSONLayer(t,e){if(!(t instanceof r.GeoJSON))return;let s=null;if(e.geojson)s=JSON.parse(e.geojson);else if(e.url){const t=await fetch(e.url);if(!t.ok)throw new Error(`GeoJSON fetch failed: ${t.status} ${t.statusText}`);s=await t.json()}t.clearLayers(),t.addData(s)}async createGeoJSONLayer(t){let e=null;if(t.geojson)e=JSON.parse(t.geojson);else if(t.url){const s=await fetch(t.url);if(!s.ok)throw new Error(`GeoJSON fetch failed: ${s.status} ${s.statusText}`);e=await s.json()}if(e){let s={};if(t.geostylerStyle)s=await this.createGeostylerLeafletOptions(t.geostylerStyle);else{const e=t.style?{...n,...t.style}:n;s={style:this.createLeafletStyle(e),pointToLayer:(t,s)=>this.createLeafletPoint(t,s,e),onEachFeature:(t,s)=>this.bindLeafletPopup(t,s,e)}}return r.geoJSON(e,s)}return null}async createXYZLayer(t){return r.tileLayer(t.url,{attribution:this.normalizeAttribution(t.attributions),maxZoom:t.maxZoom??19,...t.options??{}})}async updateOSMLayer(t,e){if(!("setUrl"in t)||"function"!=typeof t.setUrl)return;let s="https://tile.openstreetmap.org/{z}/{x}/{y}.png";e.url&&(s=e.url+"/{z}/{x}/{y}.png"),t.setUrl(s)}async createOSMLayer(t){let e="https://tile.openstreetmap.org/{z}/{x}/{y}.png";return t.url&&(e=t.url+"/{z}/{x}/{y}.png"),r.tileLayer(e,{attribution:"© OpenStreetMap contributors",maxZoom:19})}async createWMSLayer(t){return r.tileLayer.wms(t.url,{layers:t.layers,format:t.format??"image/png",transparent:t.transparent??!0,...t.extraParams??{}})}buildArcGISUrl(t,e){if(!e||0===Object.keys(e).length)return t;const s=new URLSearchParams;return Object.entries(e).forEach((([t,e])=>{null!=e&&s.set(t,String(e))})),0===s.toString().length?t:`${t}${t.includes("?")?"&":"?"}${s.toString()}`}async createArcGISLayer(t){const e={...t.params??{}};t.token&&(e.token=t.token);const s=this.buildArcGISUrl(t.url,e),i={attribution:this.normalizeAttribution(t.attributions),minZoom:t.minZoom,maxZoom:t.maxZoom,...t.options??{}};return r.tileLayer(s,i)}async updateArcGISLayer(t,e){const s={...e?.params??{}};e?.token&&(s.token=e.token);const i=t,r=this.buildArcGISUrl(e?.url??i.options?.url??"",s);"setUrl"in i&&"function"==typeof i.setUrl&&i.setUrl(r)}async createGoogleLayer(t){if(!this.map)throw new Error("Map not initialized");if(!t.apiKey)throw new Error("Google-Layer benötigt 'apiKey' (Google Maps Platform).");const e="string"==typeof t.styles?this.tryParseStyles(t.styles):t.styles,s=new y({apiKey:t.apiKey,mapType:t.mapType??"roadmap",language:t.language,region:t.region,scale:t.scale,highDpi:t.highDpi,layerTypes:t.layerTypes,overlay:t.overlay,styles:Array.isArray(e)?e:void 0,imageFormat:t.imageFormat,apiOptions:t.apiOptions,maxZoom:t.maxZoom??22});return o=()=>{this.googleLogoAdded=!0,a("v-map - provider - leaflet - googleLogoAdded: ",this.googleLogoAdded)},(i=this.map)._googleLogoAdded||(new(r.Control.extend({onAdd(){const t=r.DomUtil.create("img");return t.src="https://developers.google.com/static/maps/documentation/images/google_on_white.png",t.alt="Google",t.style.pointerEvents="none",t.style.height="18px",t.style.margin="0 0 6px 6px",t},onRemove(){}}))({position:"bottomleft"}).addTo(i),i._googleLogoAdded=!0,o()),s;var i,o}tryParseStyles(t){try{const e=JSON.parse(t);return Array.isArray(e)?e:void 0}catch{return void o("Failed to parse Google styles JSON")}}async destroy(){var t;this.unsubscribeResize?.(),t=this.injectedStyle,this.shadowRoot&&t&&t.remove();for(const t of this.layers)this.map?.removeLayer(t);this.layers=[],this.map?.remove(),this.map=void 0}async setView([t,e],s){this.map?.setView([e,t],s,{animate:!1})}onLayerError(t,e){this.layerErrorCallbacks.set(t,e),this._getLayerById(t).then((s=>{if(!s)return;const i=()=>{e({type:"network",message:"Tile load error"})};s.on("tileerror",i),this.layerErrorCleanups.set(t,(()=>s.off("tileerror",i)))}))}offLayerError(t){this.layerErrorCleanups.get(t)?.(),this.layerErrorCleanups.delete(t),this.layerErrorCallbacks.delete(t)}async removeLayer(t){if(!t)return;this.offLayerError(t);const e=await this._getLayerById(t);e&&this.map.removeLayer(e)}async setZIndex(t,e){if(!t)return;const s=await this._getLayerById(t);s&&"function"==typeof s.setZIndex&&s.setZIndex(e)}async setOpacity(t,e){if(!t)return;const s=await this._getLayerById(t);this.setOpacityByLayer(s,e)}setOpacityByLayer(t,e){t&&(t.vmapOpacity=e,void 0===t.vmapVisible&&(t.vmapVisible=!0),!1!==t.vmapVisible&&this.setLayerOpacity(t,e))}async setVisible(t,e){if(!t)return;const s=await this._getLayerById(t);this.setVisibleByLayer(s,e)}setVisibleByLayer(t,e){t&&(t.vmapVisible=e,void 0===t.vmapOpacity&&(t.vmapOpacity=1),this.setLayerOpacity(t,e?t.vmapOpacity:0))}setLayerOpacity(t,e){if(!t)return;const s="number"==typeof e?e:e.opacity??1,i="number"==typeof e?e:e.fillOpacity??s,o=(t,e)=>{if(!(e in r))return!1;const s=r[e];return"function"==typeof s&&t instanceof s};var a;o(a=t,"GeoJSON")||o(a,"LayerGroup")?t.eachLayer((t=>this.setLayerOpacity(t,e))):(t=>o(t,"Path"))(t)?t.setStyle({opacity:s,fillOpacity:i}):((t=>o(t,"Marker"))(t)||"setOpacity"in t)&&t.setOpacity(s)}async ensureGroup(t,e,s){await this._ensureGroup(t,e)}async _ensureGroup(t,e){let s=await this._getLayerGroupById(t);return s||(s=r.layerGroup(),s._groupId=t,s.visible=!0,s.addTo(this.map),this.layers.push(s)),this.setGroupVisible(t,void 0===e||e),s}async _getLayerGroupById(t){if(!this.map)return null;let e=this.layers.find((e=>e instanceof r.LayerGroup&&e._groupId===t));return e||(e=this.hiddenLayerGroups.find((e=>e._groupId===t)),e)?e:null}async setGroupVisible(t,e){const s=await this._getLayerGroupById(t);if(s){if(s.visible===e)return;!1===s.visible?(s.addTo(this.map),this.hiddenLayerGroups=this.hiddenLayerGroups.filter((e=>e._groupId!==t)),s.visible=e):!0===s.visible&&(this.map.removeLayer(s),s.visible=e,this.hiddenLayerGroups.push(s))}}async updateWKTLayer(t,e){if(!(t instanceof r.GeoJSON))return;let s=null;if(e.wkt)s=await this.wktToGeoJSON(e.wkt);else if(e.url)try{const t=await fetch(e.url);if(!t.ok)throw new Error(`Failed to fetch WKT: ${t.status}`);const i=await t.text();s=await this.wktToGeoJSON(i)}catch(t){return void o("Failed to load WKT from URL:",t)}if(s){t.clearLayers();const i=t;i.options.style=this.createLeafletStyle(e.style),i.options.pointToLayer=(t,s)=>this.createLeafletPoint(t,s,e.style),i.options.onEachFeature=(t,s)=>this.bindLeafletPopup(t,s,e.style),i.addData(s)}}async createWKTLayer(t){let e=null;const s={type:"FeatureCollection",features:[]};if(t.wkt)e=await this.wktToGeoJSON(t.wkt);else if(t.url)try{const s=await fetch(t.url);if(!s.ok)throw new Error(`Failed to fetch WKT: ${s.status}`);const i=await s.text();e=await this.wktToGeoJSON(i)}catch(t){o("Failed to load WKT from URL:",t),e=s}else e=s;a("[Leaflet WKT] Creating layer with GeoJSON data:",e),a("[Leaflet WKT] Config:",t);let i={};if(t.geostylerStyle)i=await this.createGeostylerLeafletOptions(t.geostylerStyle);else{const e=t.style?{...n,...t.style}:n;i={style:this.createLeafletStyle(e),pointToLayer:(t,s)=>this.createLeafletPoint(t,s,e),onEachFeature:(t,s)=>this.bindLeafletPopup(t,s,e)}}a("[Leaflet WKT] Layer options:",i);const c=r.geoJSON(e,i);return a("[Leaflet WKT] Created layer:",c),"function"==typeof c.getBounds&&a("[Leaflet WKT] Layer bounds:",c.getBounds()),c}async wktToGeoJSON(t){try{const e=u.wellknown.parse(t);if(!e)throw new Error("Failed to parse WKT - returned null");const s={type:"Feature",geometry:e,properties:{}};return a("[Leaflet WKT] Input WKT:",t),a("[Leaflet WKT] Generated GeoJSON:",JSON.stringify(s,null,2)),{type:"FeatureCollection",features:[s]}}catch(e){return o("[Leaflet WKT] Failed to parse WKT:",t,e),{type:"FeatureCollection",features:[]}}}async createGeoTIFFLayer(t){if(!t.url)throw new Error("GeoTIFF layer requires a URL");try{const e=new d({url:t.url,tileSize:256,colorMap:t.colorMap,valueRange:t.valueRange,nodata:t.nodata,resolution:t.resolution,resampleMethod:t.resampleMethod,viewProjection:this.map.options.crs.code});return void 0!==t.opacity&&e.setOpacity?.(t.opacity),void 0!==t.zIndex&&e.setZIndex?.(t.zIndex),e}catch(t){return o("Failed to create GeoTIFF layer:",t),r.layerGroup([])}}async updateGeoTIFFLayer(t,e){if(!e.url)throw new Error("GeoTIFF update requires a URL");if(!t)return;if(!(t instanceof d))return;const s=e;await t.updateSource({url:e.url,colorMap:e.colorMap,valueRange:e.valueRange,nodata:e.nodata,resolution:s.resolution,resampleMethod:s.resampleMethod})}async createWCSLayer(t){if(!t.url)throw new Error("WCS layer requires a URL");if(!t.coverageName)throw new Error("WCS layer requires a coverageName");try{const e={url:t.url,coverageName:t.coverageName,version:t.version??"2.0.1",format:t.format??"image/tiff",projection:t.projection??"EPSG:4326",params:t.params};t.tileSize&&(e.tileSize=t.tileSize),void 0!==t.minZoom&&(e.minZoom=t.minZoom),void 0!==t.maxZoom&&(e.maxZoom=t.maxZoom);const s=new w(e);return void 0!==t.opacity&&s.setOpacity?.(t.opacity),void 0!==t.zIndex&&s.setZIndex?.(t.zIndex),s}catch(t){return o("[Leaflet WCS] Failed to create WCS layer:",t),r.layerGroup([])}}async updateWCSLayer(t,e){if(t&&t instanceof w){const s={};e.url&&(s.url=e.url),e.coverageName&&(s.coverageName=e.coverageName),e.version&&(s.version=e.version),e.format&&(s.format=e.format),e.projection&&(s.projection=e.projection),e.params&&(s.params=e.params),t.updateOptions(s)}}async createGeostylerLeafletOptions(t){const e=(t,e)=>null==t||"object"==typeof t&&t.name?e:t;return{style:s=>{const i=s?.geometry?.type;let r={};if(t.rules)for(const s of t.rules)if(s.symbolizers)for(const t of s.symbolizers)switch(t.kind){case"Fill":if("Polygon"===i||"MultiPolygon"===i){const s=e(t.color,"rgba(0,100,255,0.3)"),i=e(t.opacity,.3),o=e(t.outlineColor,"rgba(0,100,255,1)"),a=e(t.outlineWidth,1);r={...r,fillColor:s,fillOpacity:i,color:o,weight:a}}break;case"Line":const s=e(t.color,"rgba(0,100,255,1)"),o=e(t.width,2),a=t.dasharray&&Array.isArray(t.dasharray)?t.dasharray.map((t=>e(t,0))).join(","):void 0;r={...r,color:s,weight:o,dashArray:a}}return r},pointToLayer:(s,i)=>{if(t.rules)for(const s of t.rules)if(s.symbolizers)for(const t of s.symbolizers)switch(t.kind){case"Mark":const s=e(t.color,"rgba(0,100,255,1)"),o=e(t.radius,6),a=e(t.strokeColor,"rgba(0,100,255,1)"),n=e(t.strokeWidth,2);return r.circleMarker(i,{radius:o,fillColor:s,fillOpacity:1,color:a,weight:n});case"Icon":const c=e(t.image),l=e(t.size,32);if(c&&"string"==typeof c){const t=r.icon({iconUrl:c,iconSize:[l,l],iconAnchor:[l/2,l]});return r.marker(i,{icon:t})}}return r.circleMarker(i,{radius:6,fillColor:"rgba(0,100,255,1)",fillOpacity:1,color:"rgba(0,100,255,1)",weight:2})},onEachFeature:(s,i)=>{if(t.rules)for(const r of t.rules)if(r.symbolizers)for(const t of r.symbolizers)if("Text"===t.kind){const r=t.label;if(r&&"string"==typeof r&&s.properties&&s.properties[r]){const o=String(s.properties[r]),a=e(t.color,"#000000"),n=e(t.size,12);i.bindTooltip(`<div style="color: ${a}; font-size: ${n}px; font-family: Arial, sans-serif;">${o}</div>`,{permanent:!0,direction:"center",className:"leaflet-tooltip-custom"})}}}}}createLeafletStyle(t){return e=>{const s=e?.geometry?.type,i=t?.fillColor??"rgba(0,100,255,0.3)",r=t?.fillOpacity??.3,o=t?.strokeColor??"rgba(0,100,255,1)",a=t?.strokeOpacity??1,n=t?.strokeWidth??2;return"Polygon"===s||"MultiPolygon"===s?{fillColor:i,fillOpacity:r,color:o,opacity:a,weight:n,dashArray:t?.strokeDashArray?t.strokeDashArray.join(","):void 0}:"LineString"===s||"MultiLineString"===s?{color:o,opacity:a,weight:n,dashArray:t?.strokeDashArray?t.strokeDashArray.join(","):void 0}:{}}}createLeafletPoint(t,e,s){let i={...s??{}};if(s?.styleFunction){const e=s.styleFunction(t);e&&(i={...s,...e})}if(i?.iconUrl){const t=i.iconSize||[32,32],s=r.icon({iconUrl:i.iconUrl,iconSize:t,iconAnchor:i.iconAnchor||[t[0]/2,t[1]]});return r.marker(e,{icon:s})}{const t=i?.pointColor??"rgba(0,100,255,1)",s=i?.pointOpacity??1;return r.circleMarker(e,{radius:i?.pointRadius??6,fillColor:t,fillOpacity:s,color:i?.strokeColor??"rgba(0,100,255,1)",opacity:i?.strokeOpacity??1,weight:i?.strokeWidth??2})}}bindLeafletPopup(t,e,s){if(s?.textProperty&&t.properties&&t.properties[s.textProperty]){const i=String(t.properties[s.textProperty]);e.bindTooltip(`<div style="color: ${s?.textColor??"#000000"}; font-size: ${s?.textSize??12}px; font-family: Arial, sans-serif;">${i}</div>`,{permanent:!0,direction:"center",className:"leaflet-tooltip-custom"})}}async createWFSLayer(t){const e=await this.fetchWFSFromUrl(t);let s={};if(t.geostylerStyle)s=await this.createGeostylerLeafletOptions(t.geostylerStyle);else{const e=t.style?{...n,...t.style}:n;s={style:this.createLeafletStyle(e),pointToLayer:(t,s)=>this.createLeafletPoint(t,s,e),onEachFeature:(t,s)=>this.bindLeafletPopup(t,s,e)}}return r.geoJSON(e,s)}async updateWFSLayer(t,e){const s=await this.fetchWFSFromUrl(e);t.clearLayers(),t.addData(s)}async fetchWFSFromUrl(t){const e={service:"WFS",request:"GetFeature",version:t.version??"1.1.0",typeName:t.typeName,outputFormat:t.outputFormat??"application/json",srsName:t.srsName??"EPSG:4326",...t.params??{}},s=this.appendParams(t.url,e),i=await fetch(s);if(!i.ok)throw new Error(`WFS request failed (${i.status} ${i.statusText})`);const r=(t.outputFormat??"application/json").toLowerCase();if(r.includes("json")||r.includes("geojson")||"application/json"===r)return await i.json();if(r.includes("gml")||r.includes("xml")){const t=await i.text(),e=new f;return await e.parse(t)}return await i.json()}appendParams(t,e){const s=new URLSearchParams;return Object.entries(e).forEach((([t,e])=>{null!=e&&s.set(t,String(e))})),s.toString()?`${t}${t.includes("?")?"&":"?"}${s.toString()}`:t}getMap(){return this.map}}export{g as LeafletProvider}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Build as n}from"@stencil/core/internal/client";const o=!n.isDev,e=(()=>{try{return"undefined"!=typeof location&&new URLSearchParams(location.search).has("vmapDebug")}catch{return!1}})(),r=!o||e||"undefined"!=typeof localStorage&&"1"===localStorage.getItem("@pt9912/v-map:exposeConsoleAPI"),t="@pt9912/v-map:logLevel";function c(){try{if("undefined"!=typeof window&&"localStorage"in window)return window.localStorage}catch{}return null}const a=o?"warn":"debug";let l=function(){const n=c();if(!n)return null;const o=n.getItem(t);return!o||"none"!==o&&"error"!==o&&"warn"!==o&&"info"!==o&&"debug"!==o?null:o}()??a,i=new class{log(n,o,e){const r=e?`[${e}]`:void 0,t=[...o];if("debug"===n||"warn"===n||"error"===n){const o="debug"===n||"warn"===n||"error"===n?(new Error).stack?.split("\n")[4]?.trim():null;o&&t.push(`${o}`)}switch(n){case"debug":case"info":r?console.log(r,...t):console.log(...t);break;case"warn":r?console.warn(r,...t):console.warn(...t);break;case"error":r?console.error(r,...t):console.error(...t)}}};function s(n,o,e){(function(n){const o={none:0,error:1,warn:2,info:3,debug:4};return o[n]<=o[l]})(n)&&i.log(n,o,e)}const u=(...n)=>s("debug",n),f=(...n)=>s("warn",n),d=(...n)=>s("error",n);if(r&&"undefined"!=typeof globalThis){const n=globalThis;n.setLogLevel=function(n){l=n,function(n){const o=c();if(o)try{o.setItem(t,n)}catch{}}(n)},n.getLogLevel=function(){return l},n.log=(...n)=>u(...n),n.info=(...n)=>((...n)=>s("info",n))(...n),n.warn=(...n)=>f(...n),n.error=(...n)=>d(...n)}export{d as e,u as l,f as w}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import e from"ol/Map";import t from"ol/View";import r from"ol/layer/Vector";import o from"ol/layer/Group";import s from"ol/layer/Tile";import n from"ol/layer/Image";import a from"ol/source/Vector";import i from"ol/source/TileWMS";import c from"ol/source/OSM";import l from"ol/source/XYZ";import u from"ol/source/Google";import f from"ol/source/TileArcGISRest";import w from"ol/Image";import y from"ol/source/Image";import h from"ol/format/GeoJSON";import m from"ol/format/GML2";import p from"ol/format/GML3";import d from"ol/format/GML32";import g from"ol/format/WKT";import b from"ol/control/Control";import S from"ol/style/Style";import L from"ol/style/Fill";import G from"ol/style/Stroke";import I from"ol/style/Circle";import v from"ol/style/Icon";import j from"ol/style/Text";import{bbox as E}from"ol/loadingstrategy";import{get as k,fromLonLat as F}from"ol/proj";import{D as $}from"./styleconfig.js";import{w as P,e as T,l as x}from"./events.js";import{O as W}from"./v-map2.js";import C from"./index4.js";import O from"ol/source/GeoTIFF";import{g as M}from"./main-dist.js";import{register as R}from"ol/proj/proj4";import N from"ol/layer/WebGLTile";async function z(e){return class extends O{geoKeys_=null;constructor(){super(e)}async getGeoKeys(){if(null!==this.geoKeys_)return this.geoKeys_;await this.getView();const e=this.sourceImagery_;return e&&e.length>0&&this.determineGeoKeys(e),this.geoKeys_}determineGeoKeys(e){if(!e||0===e.length)return;const t=e[0];for(let e=t.length-1;e>=0;--e){const o="function"==typeof(r=t[e]).getGeoKeys?r.getGeoKeys()||null:r.geoKeys||null;if(o){this.geoKeys_=o;break}}var r}async getProjectionParameters(){const e=await this.getGeoKeys();return e?M.toProj4(e):null}async getProj4String(){const e=await this.getProjectionParameters();return e&&e.proj4||null}async registerProjectionIfNeeded(){try{const e=await this.getProj4String(),t=this.getProjection()?.getCode();return k(t)||(null===e?(P(`Can not get proj string for code: ${t}`),null):(C.defs(t,e),R(C),k(t)))}catch(e){return T("Fehler bei der Registrierung der Projektion:",e),null}}}}class A{map;layers=[];baseLayers=[];googleLogoAdded=!1;projection="EPSG:3857";layerErrorCallbacks=new globalThis.Map;layerErrorCleanups=new globalThis.Map;async init(r){await async function(e){if(!e)return;const t="ol-css-sheet";if(e.querySelector(`style[data-id="${t}"]`))return;const r=`https://cdn.jsdelivr.net/npm/ol@${W}/ol.css`,o=await(await fetch(r)).text();if("adoptedStyleSheets"in Document.prototype){const t=new CSSStyleSheet;await t.replace(o),e.adoptedStyleSheets=[...e.adoptedStyleSheets??[],t]}else{const r=document.createElement("style");r.setAttribute("data-id",t),r.textContent=o,e.appendChild(r)}}(r.shadowRoot),Object.assign(r.target.style,{width:"100%",height:"100%",position:"relative",background:"#fff"}),this.map=new e({target:r.target,layers:[],view:new t({projection:this.projection,center:F(r?.mapInitOptions?.center??[0,0]),zoom:r?.mapInitOptions?.zoom??2})}),new ResizeObserver((()=>this.map?.updateSize())).observe(r.target)}async destroy(){this.map?.setTarget(void 0),this.map=void 0}async updateLayer(e,t){const r=await this._getLayerById(e);switch(t.type){case"geojson":await this.updateGeoJSONLayer(r,t.data);break;case"osm":await this.updateOSMLayer(r,t.data);break;case"wms":await this.updateWMSLayer(r,t.data);break;case"wfs":await this.updateWFSLayer(r,t.data);break;case"wcs":await this.updateWCSLayer(r,t.data);break;case"arcgis":await this.updateArcGISLayer(r,t.data);break;case"wkt":await this.updateWKTLayer(r,t.data);break;case"geotiff":await this.updateGeoTIFFLayer(r,t.data)}}async ensureGroup(e,t,r){await this._ensureGroup(e,t)}async _ensureGroup(e,t){if(!this.map)return null;let r=this.layers.find((t=>t.get?.("groupId")===e));return r||(r=new o({layers:[],properties:{groupId:e,visible:void 0===typeof t||t}}),this.map.addLayer(r),this.layers.push(r)),r}async setBaseLayer(e,t){if(null===t)return void x("ol - setBaseLayer - layerElementId is null.");const r=this.layers.find((t=>t.get?.("groupId")===e)),o=this.baseLayers.find((e=>e.get("layerElementId")===t));void 0!==o?(r.getLayers().clear(),r.getLayers().push(o)):x("ol - setBaseLayer - layer not found. layerElementId: "+t)}async addBaseLayer(e,t,r){if(null==r)return x("ol - addBaseLayer - layerElementId not set."),null;null==t&&x("ol - addBaseLayer - basemapid not set.");const o=await this._ensureGroup(e.groupId,e.groupVisible);if(null==o)return null;o.set("basemap",!0,!1);const s=await this.createLayer(e);if(null==s)return null;s.set("group",o),this.baseLayers.push(s);let n=null;if(s){n=crypto.randomUUID(),s.set("id",n,!1),s.set("layerElementId",r,!1);const a=e;void 0!==a.opacity&&s.setOpacity(a.opacity),void 0!==a.zIndex&&s.setZIndex(a.zIndex),a.visible?s.setVisible(!0):!1===a.visible&&s.setVisible(!1),t===r&&(o.getLayers().clear(),o.getLayers().push(s))}return n}async addLayerToGroup(e){const t=await this._ensureGroup(e.groupId,e.groupVisible);if(null==t)return null;const r=await this.createLayer(e);if(null===r)return null;r.set("group",t),t.getLayers().push(r);const o=crypto.randomUUID();r.set("id",o,!1);const s=e;return void 0!==s.opacity&&r.setOpacity(s.opacity),void 0!==s.zIndex&&r.setZIndex(s.zIndex),s.visible?r.setVisible(!0):!1===s.visible&&r.setVisible(!1),o}async createLayer(e){switch(e.type){case"geojson":return this.createGeoJSONLayer(e);case"xyz":return this.createXYZLayer(e);case"google":return this.createGoogleLayer(e);case"osm":return this.createOSMLayer(e);case"wms":return this.createWMSLayer(e);case"wfs":return this.createWFSLayer(e);case"wcs":return this.createWCSLayer(e);case"arcgis":return this.createArcGISLayer(e);case"wkt":return this.createWKTLayer(e);case"geotiff":return this.createGeoTIFFLayer(e);default:throw new Error(`Unsupported layer type: ${e.type}`)}}async updateWMSLayer(e,t){e.setSource(new i({url:t.url,params:{LAYERS:t.layers,TILED:!0,...t.extraParams??{}}}))}async updateOSMLayer(e,t){let r="https://tile.openstreetmap.org/{z}/{x}/{y}.png";t.url&&(r=t.url+"/{z}/{x}/{y}.png"),e.setSource(new c({url:r}))}async updateGeoJSONLayer(e,t){let r=null;const o={featureProjection:this.projection};if(t.geojson){const e=JSON.parse(t.geojson);r=new a({features:new h(o).readFeatures(e)})}else r=new a({url:t.url,format:new h(o)});let s;e.setSource(r),t.geostylerStyle?s=await this.createGeostylerStyleFunction(t.geostylerStyle):t.style&&(s=await this.createEnhancedStyleFunction(t.style)),s&&e.setStyle(s)}async updateWFSLayer(e,t){const r=this.mergeLayerConfig(e,"wfsConfig",t),o=await this.createWFSSpource(r);let s;e.setSource(o),r.geostylerStyle?s=await this.createGeostylerStyleFunction(r.geostylerStyle):r.style&&(s=await this.createEnhancedStyleFunction(r.style)),s&&e.setStyle(s)}async updateWCSLayer(e,t){const r=this.mergeLayerConfig(e,"wcsConfig",t),o=await this.createWcsSource(r);e.setSource(o)}async updateArcGISLayer(e,t){const r=e,o=r.getSource(),s={...o?.getParams?.()??{},...t?.params??{}};t?.token&&(s.token=t.token);const n={url:t?.url??o?.getUrls?.()?.[0],params:s,...t?.options??{}},a=new f(n);r.setSource(a)}async createEnhancedStyleFunction(e){function t(e,t){if(e.startsWith("rgba")){const r=e.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(r){const[,e,o,s]=r;return`rgba(${e}, ${o}, ${s}, ${t})`}}else if(e.startsWith("rgb")){const r=e.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);if(r){const[,e,o,s]=r;return`rgba(${e}, ${o}, ${s}, ${t})`}}else if(e.startsWith("#")){const r=e.slice(1);return`rgba(${parseInt(r.slice(0,2),16)}, ${parseInt(r.slice(2,4),16)}, ${parseInt(r.slice(4,6),16)}, ${t})`}return e}return r=>{const o=[],s=r.getGeometry().getType(),n=new L({color:t(e.fillColor??"rgba(0,100,255,0.3)",e.fillOpacity??.3)}),a=e.strokeWidth??2,i=new G({color:t(e.strokeColor??"rgba(0,100,255,1)",e.strokeOpacity??1),width:a,lineDash:e.strokeDashArray});if(o.push(new S("Point"===s?e.iconUrl?{image:new v({src:e.iconUrl,size:e.iconSize||[32,32],anchor:e.iconAnchor||[.5,1]})}:{image:new I({radius:e.pointRadius??6,fill:new L({color:t(e.pointColor??"rgba(0,100,255,1)",e.pointOpacity??1)}),stroke:i})}:{fill:s.includes("Polygon")?n:void 0,stroke:i})),e.textProperty&&r.get(e.textProperty)){const t=e.textColor??"#000000",s=e.textSize??12,n=e.textHaloColor,a=e.textHaloWidth??2,i=e.textOffset||[0,0];o.push(new S({text:new j({text:String(r.get(e.textProperty)),font:`${s}px Arial`,fill:new L({color:t}),stroke:n?new G({color:n,width:a}):void 0,offsetX:i[0],offsetY:i[1]})}))}return o}}async createGeoJSONLayer(e){let t=null;const o={featureProjection:this.projection};if(e.geojson){const r=JSON.parse(e.geojson);t=new a({features:new h(o).readFeatures(r)})}else t=new a({url:e.url,format:new h(o)});let s;if(e.geostylerStyle)s=await this.createGeostylerStyleFunction(e.geostylerStyle);else{const t=e.style?{...$,...e.style}:$;s=await this.createEnhancedStyleFunction(t)}return new r({source:t,style:s})}async createWFSSpource(e){const t=(e.outputFormat??"application/json").toLowerCase();let r=new h;switch(t){case"gml2":r=new m;break;case"gml3":r=new p;break;case"gml32":r=new d}const o=this.getWFSGetFeatureUrl(e);return new a({format:r,url:o,strategy:E})}async createWFSLayer(e){const t=await this.createWFSSpource(e);let o;if(e.geostylerStyle)o=await this.createGeostylerStyleFunction(e.geostylerStyle);else{const t=e.style?{...$,...e.style}:$;o=await this.createEnhancedStyleFunction(t)}const s=new r({source:t,style:o});return s.set("wfsConfig",e,!1),s}async createGeostylerStyleFunction(e){const t=(e,t)=>null==e||"object"==typeof e&&e.name?t:e;return r=>{const o=[],s=r.getGeometry().getType();if(e.rules)for(const n of e.rules)if(n.symbolizers)for(const e of n.symbolizers)switch(e.kind){case"Fill":if(s.includes("Polygon")){const r=t(e.color,"rgba(0,100,255,0.3)"),s=t(e.outlineColor),n=t(e.outlineWidth,1);o.push(new S({fill:new L({color:r}),stroke:s?new G({color:s,width:n}):void 0}))}break;case"Line":{const r=t(e.color,"rgba(0,100,255,1)"),s=t(e.width,1),n=e.dasharray&&Array.isArray(e.dasharray)?e.dasharray.map((e=>t(e,0))):void 0;o.push(new S({stroke:new G({color:r,width:s,lineDash:n})}))}break;case"Mark":if("Point"===s){const r=t(e.color,"rgba(0,100,255,1)"),s=t(e.radius,6),n=t(e.strokeColor),a=t(e.strokeWidth,1);o.push(new S({image:new I({radius:s,fill:new L({color:r}),stroke:n?new G({color:n,width:a}):void 0})}))}break;case"Icon":if("Point"===s){const r=t(e.image),s=t(e.size,32),n=t(e.opacity,1);r&&"string"==typeof r&&o.push(new S({image:new v({src:r,size:[s,s],opacity:n})}))}break;case"Text":{const s=e,n=t(s.label);if(n&&r.get(n)){const e=t(s.color,"#000000"),a=t(s.size,12),i=t(s.font?.[0],"Arial"),c=t(s.haloColor),l=t(s.haloWidth,1),u=s.offset,f=u&&Array.isArray(u)?t(u[0],0):0,w=u&&Array.isArray(u)?t(u[1],0):0;o.push(new S({text:new j({text:String(r.get(n)),font:`${a}px ${i}`,fill:new L({color:e}),stroke:c?new G({color:c,width:l}):void 0,offsetX:f,offsetY:w})}))}}}return o.length>0?o:void 0}}async createXYZLayer(e){return new s({source:new l({url:e.url,attributions:e.attributions,maxZoom:e.maxZoom??19,...e.options??{}})})}async createGoogleLayer(e){if(!e.apiKey)throw new Error("Google-Layer benötigt 'apiKey' (Google Maps Platform).");const t=new u({key:e.apiKey,mapType:e.mapType??"roadmap",scale:e.scale??"scaleFactor2x",highDpi:e.highDpi??!0,language:e.language,region:e.region,imageFormat:e.imageFormat,styles:e.styles,layerTypes:e.layerTypes});t.on("change",(()=>{if("error"===t.getState()){const e=t.getError();T("Google source error",e),this.map.getTargetElement()?.dispatchEvent(new CustomEvent("google-source-error",{detail:{message:e??"Google source error"},bubbles:!0,composed:!0}))}}));const r=new s({source:t});if(!this.googleLogoAdded){class e extends b{constructor(){const e=document.createElement("img");e.style.pointerEvents="none",e.style.position="absolute",e.style.bottom="5px",e.style.left="5px",e.style.height="18px",e.alt="Google",e.src="https://developers.google.com/static/maps/documentation/images/google_on_white.png",super({element:e})}}this.map.addControl(new e),this.googleLogoAdded=!0}return r}async createOSMLayer(e){let t="https://tile.openstreetmap.org/{z}/{x}/{y}.png";return e.url&&(t=e.url+"/{z}/{x}/{y}.png"),new s({source:new c({url:t})})}async createWMSLayer(e){return new s({source:new i({url:e.url,params:{LAYERS:e.layers,TILED:!0,...e.extraParams??{}}})})}onLayerError(e,t){this.layerErrorCallbacks.set(e,t),this._getLayerById(e).then((t=>{t&&this.attachSourceErrorListeners(e,t)}))}offLayerError(e){this.layerErrorCleanups.get(e)?.(),this.layerErrorCleanups.delete(e),this.layerErrorCallbacks.delete(e)}attachSourceErrorListeners(e,t){this.layerErrorCleanups.get(e)?.();const r=this.layerErrorCallbacks.get(e);if(!r)return;const o=t.getSource?.();if(!o)return;const s=[];if("getTile"in o||o instanceof i||o instanceof c||o instanceof l||o instanceof u||o instanceof f){const e=()=>{r({type:"network",message:"Tile load error"})};o.on("tileloaderror",e),s.push((()=>o.un("tileloaderror",e)))}if(o instanceof a){const e=()=>{r({type:"network",message:"Feature load error"})};o.on("featuresloaderror",e),s.push((()=>o.un("featuresloaderror",e)))}if(o instanceof y){const e=()=>{r({type:"network",message:"Image load error"})};o.on("imageloaderror",e),s.push((()=>o.un("imageloaderror",e)))}const n=()=>{this.attachSourceErrorListeners(e,t)};t.on("change:source",n),s.push((()=>t.un("change:source",n))),this.layerErrorCleanups.set(e,(()=>s.forEach((e=>e()))))}async setView(e,t){this.map&&this.map.getView().animate({center:F(e),zoom:t,duration:0})}async _forEachLayer(e,t){if(e instanceof o){const r=e.getLayers().getArray();for(const e of r)if(await this._forEachLayer(e,t))return!0}else if(t(e))return!0;return!1}async _getLayerById(e){if(!this.map)return null;let t=null;return await this._forEachLayer(this.map.getLayerGroup(),(r=>{if(r.get("id")===e)return t=r,!0})),t||(t=this.baseLayers.find((t=>t.get("id")===e)),void 0===t?null:t)}async _getLayerGroupById(e){if(!this.map)return null;const t=this.layers.find((t=>t.get?.("groupId")===e));return void 0!==t?t:null}async removeLayer(e){if(!e)return;this.offLayerError(e);const t=await this._getLayerById(e);if(t){const e=t.get("group");e&&e.getLayers().remove(t)}}async setOpacity(e,t){if(!e)return;const r=await this._getLayerById(e);r&&r.setOpacity(t)}async setZIndex(e,t){if(!e)return;const r=await this._getLayerById(e);r&&r.setZIndex(t)}async setVisible(e,t){const r=await this._getLayerById(e);r&&r.setVisible(t)}async setGroupVisible(e,t){const r=await this._getLayerGroupById(e);r&&r.setVisible(t)}async updateWKTLayer(e,t){const r=new g;let o=null;const s=this.map?.getView()?.getProjection();if(t.wkt){const e=r.readFeature(t.wkt,{dataProjection:"EPSG:4326",featureProjection:s});o=new a({features:[e]})}else if(t.url){const e=await fetch(t.url);if(!e.ok)throw new Error(`Failed to fetch WKT: ${e.status}`);const n=await e.text(),i=r.readFeature(n,{dataProjection:"EPSG:4326",featureProjection:s});o=new a({features:[i]})}let n;o&&e.setSource(o),t.geostylerStyle?n=await this.createGeostylerStyleFunction(t.geostylerStyle):t.style&&(n=await this.createEnhancedStyleFunction(t.style)),n&&e.setStyle(n)}async createWKTLayer(e){const t=new g;let o=null;const s=this.map?.getView()?.getProjection();if(e.wkt)try{const r=t.readFeature(e.wkt,{dataProjection:"EPSG:4326",featureProjection:s});o=new a({features:[r]})}catch(e){T("Failed to parse WKT:",e),o=new a({features:[]})}else if(e.url)try{const r=await fetch(e.url);if(!r.ok)throw new Error(`Failed to fetch WKT: ${r.status}`);const n=await r.text(),i=t.readFeature(n,{dataProjection:"EPSG:4326",featureProjection:s});o=new a({features:[i]})}catch(e){T("Failed to load WKT from URL:",e),o=new a({features:[]})}else o=new a({features:[]});let n;if(e.geostylerStyle)n=await this.createGeostylerStyleFunction(e.geostylerStyle);else{const t=e.style?{...$,...e.style}:$;n=await this.createEnhancedStyleFunction(t)}return new r({source:o,style:n,opacity:e.opacity??1,visible:e.visible??!0,zIndex:e.zIndex??1e3})}async createGeoTIFFLayer(e){if(!e.url)throw new Error("GeoTIFF layer requires a URL");const t={url:e.url};null===e.nodata||isNaN(e.nodata)||(t.nodata=e.nodata);const r=new(await z({sources:[t],wrapX:!1}));return await r.registerProjectionIfNeeded(),new N({source:r,opacity:e.opacity??1,visible:e.visible??!0,zIndex:e.zIndex??100})}async createWCSLayer(e){const t=await this.createWcsSource(e),r=new n({source:t,visible:e.visible??!0,opacity:e.opacity??1});return r.set("wcsConfig",e,!1),r}getWFSGetFeatureUrl(e){return t=>{const r={service:"WFS",request:"GetFeature",version:e.version??"1.1.0",typeName:e.typeName,outputFormat:e.outputFormat??"application/json",bbox:t.join(","),srsName:e.srsName??this.projection,...e.params??{}};return this.appendParams(e.url,r)}}getWCSGetCoverageUrl(e,t){return r=>{const o=e.version??"2.0.1",s=e.format??"image/tiff",n=e.projection??this.projection,a={SERVICE:"WCS",REQUEST:"GetCoverage",VERSION:o,FORMAT:s};if(o.startsWith("2.0")){a.coverageId=e.coverageName;const[t,o,n,i]=r;a.subset=`X(${t},${n})`,a.subset2=`Y(${o},${i})`,(s.includes("tiff")||s.includes("geotiff"))&&(a["geotiff:compression"]="LZW")}else{a.COVERAGE=e.coverageName,a.BBOX=r.join(","),a.CRS=n;const o=Math.round((r[2]-r[0])/t),s=Math.round((r[3]-r[1])/t);a.WIDTH=o,a.HEIGHT=s}if(e.params&&Object.entries(e.params).forEach((([e,t])=>{"string"!=typeof t&&"number"!=typeof t||(a[e]=t)})),o.startsWith("2.0")){const t=a.subset2;delete a.subset2;const r=new URLSearchParams;Object.entries(a).forEach((([e,t])=>{null!=t&&r.append(e,String(t))})),t&&r.append("subset",String(t));const o=e.url;return`${o}${o.includes("?")?"&":"?"}${r.toString()}`}return this.appendParams(e.url,a)}}mergeLayerConfig(e,t,r){const o={...e.get(t)??{},...r};return e.set(t,o,!1),o}appendParams(e,t){const r=new URLSearchParams;return Object.entries(t).forEach((([e,t])=>{null!=t&&r.set(e,String(t))})),r.toString()?`${e}${e.includes("?")?"&":"?"}${r.toString()}`:e}async createWcsSource(e){const t=e.projection??this.projection,r=this.map?.getView()?.getResolution()??1,o=this.getWCSGetCoverageUrl(e,r);return new class extends y{urlFunction_;constructor(r){super({projection:t,resolutions:e.resolutions}),this.urlFunction_=r}getImageInternal(e,t,r,o){const s=this.urlFunction_(e),n=new w(e,t,r,s);return n.load=()=>{const e=n.getImage();e.src!==s&&(e.crossOrigin="anonymous",e.src=s)},n}}(o)}async createArcGISLayer(e){const t={...e.params??{}};e.token&&(t.token=e.token);const r={url:e.url,params:t,...e.options??{}};return new s({source:new f(r),visible:e.visible??!0})}async updateGeoTIFFLayer(e,t){if(!t.url)throw new Error("GeoTIFF update requires a URL");const r={url:t.url};null==t.nodata||isNaN(t.nodata)||(r.nodata=t.nodata);const o=new(await z({sources:[r],wrapX:!1}));await o.registerProjectionIfNeeded(),e.setSource(o)}getMap(){return this.map}}export{A as OpenLayersProvider}
|
|
1
|
+
import e from"ol/Map";import t from"ol/View";import r from"ol/layer/Vector";import o from"ol/layer/Group";import s from"ol/layer/Tile";import n from"ol/layer/Image";import a from"ol/source/Vector";import i from"ol/source/TileWMS";import c from"ol/source/OSM";import l from"ol/source/XYZ";import u from"ol/source/Google";import f from"ol/source/TileArcGISRest";import w from"ol/Image";import y from"ol/source/Image";import h from"ol/format/GeoJSON";import m from"ol/format/GML2";import p from"ol/format/GML3";import g from"ol/format/GML32";import d from"ol/format/WKT";import b from"ol/control/Control";import S from"ol/style/Style";import L from"ol/style/Fill";import G from"ol/style/Stroke";import I from"ol/style/Circle";import j from"ol/style/Icon";import v from"ol/style/Text";import{bbox as E}from"ol/loadingstrategy";import{get as k,fromLonLat as F}from"ol/proj";import{D as $}from"./styleconfig.js";import{w as P,e as T,l as x}from"./logger.js";import{O as W}from"./v-map2.js";import C from"./index4.js";import O from"ol/source/GeoTIFF";import{g as M}from"./main-dist.js";import{register as R}from"ol/proj/proj4";import N from"ol/layer/WebGLTile";async function z(e){return class extends O{geoKeys_=null;constructor(){super(e)}async getGeoKeys(){if(null!==this.geoKeys_)return this.geoKeys_;await this.getView();const e=this.sourceImagery_;return e&&e.length>0&&this.determineGeoKeys(e),this.geoKeys_}determineGeoKeys(e){if(!e||0===e.length)return;const t=e[0];for(let e=t.length-1;e>=0;--e){const o="function"==typeof(r=t[e]).getGeoKeys?r.getGeoKeys()||null:r.geoKeys||null;if(o){this.geoKeys_=o;break}}var r}async getProjectionParameters(){const e=await this.getGeoKeys();return e?M.toProj4(e):null}async getProj4String(){const e=await this.getProjectionParameters();return e&&e.proj4||null}async registerProjectionIfNeeded(){try{const e=await this.getProj4String(),t=this.getProjection()?.getCode();return k(t)||(null===e?(P(`Can not get proj string for code: ${t}`),null):(C.defs(t,e),R(C),k(t)))}catch(e){return T("Fehler bei der Registrierung der Projektion:",e),null}}}}class A{map;layers=[];baseLayers=[];googleLogoAdded=!1;projection="EPSG:3857";layerErrorCallbacks=new globalThis.Map;layerErrorCleanups=new globalThis.Map;async init(r){await async function(e){if(!e)return;const t="ol-css-sheet";if(e.querySelector(`style[data-id="${t}"]`))return;const r=`https://cdn.jsdelivr.net/npm/ol@${W}/ol.css`,o=await(await fetch(r)).text();if("adoptedStyleSheets"in Document.prototype){const t=new CSSStyleSheet;await t.replace(o),e.adoptedStyleSheets=[...e.adoptedStyleSheets??[],t]}else{const r=document.createElement("style");r.setAttribute("data-id",t),r.textContent=o,e.appendChild(r)}}(r.shadowRoot),Object.assign(r.target.style,{width:"100%",height:"100%",position:"relative",background:"#fff"}),this.map=new e({target:r.target,layers:[],view:new t({projection:this.projection,center:F(r?.mapInitOptions?.center??[0,0]),zoom:r?.mapInitOptions?.zoom??2})}),new ResizeObserver((()=>this.map?.updateSize())).observe(r.target)}async destroy(){this.map?.setTarget(void 0),this.map=void 0}async updateLayer(e,t){const r=await this._getLayerById(e);switch(t.type){case"geojson":await this.updateGeoJSONLayer(r,t.data);break;case"osm":await this.updateOSMLayer(r,t.data);break;case"wms":await this.updateWMSLayer(r,t.data);break;case"wfs":await this.updateWFSLayer(r,t.data);break;case"wcs":await this.updateWCSLayer(r,t.data);break;case"arcgis":await this.updateArcGISLayer(r,t.data);break;case"wkt":await this.updateWKTLayer(r,t.data);break;case"geotiff":await this.updateGeoTIFFLayer(r,t.data)}}async ensureGroup(e,t,r){await this._ensureGroup(e,t)}async _ensureGroup(e,t){if(!this.map)return null;let r=this.layers.find((t=>t.get?.("groupId")===e));return r||(r=new o({layers:[],properties:{groupId:e,visible:void 0===typeof t||t}}),this.map.addLayer(r),this.layers.push(r)),r}async setBaseLayer(e,t){if(null===t)return void x("ol - setBaseLayer - layerElementId is null.");const r=this.layers.find((t=>t.get?.("groupId")===e)),o=this.baseLayers.find((e=>e.get("layerElementId")===t));void 0!==o?(r.getLayers().clear(),r.getLayers().push(o)):x("ol - setBaseLayer - layer not found. layerElementId: "+t)}async addBaseLayer(e,t,r){if(null==r)return x("ol - addBaseLayer - layerElementId not set."),null;null==t&&x("ol - addBaseLayer - basemapid not set.");const o=await this._ensureGroup(e.groupId,e.groupVisible);if(null==o)return null;o.set("basemap",!0,!1);const s=await this.createLayer(e);if(null==s)return null;s.set("group",o),this.baseLayers.push(s);let n=null;if(s){n=crypto.randomUUID(),s.set("id",n,!1),s.set("layerElementId",r,!1);const a=e;void 0!==a.opacity&&s.setOpacity(a.opacity),void 0!==a.zIndex&&s.setZIndex(a.zIndex),a.visible?s.setVisible(!0):!1===a.visible&&s.setVisible(!1),t===r&&(o.getLayers().clear(),o.getLayers().push(s))}return n}async addLayerToGroup(e){const t=await this._ensureGroup(e.groupId,e.groupVisible);if(null==t)return null;const r=await this.createLayer(e);if(null===r)return null;r.set("group",t),t.getLayers().push(r);const o=crypto.randomUUID();r.set("id",o,!1);const s=e;return void 0!==s.opacity&&r.setOpacity(s.opacity),void 0!==s.zIndex&&r.setZIndex(s.zIndex),s.visible?r.setVisible(!0):!1===s.visible&&r.setVisible(!1),o}async createLayer(e){switch(e.type){case"geojson":return this.createGeoJSONLayer(e);case"xyz":return this.createXYZLayer(e);case"google":return this.createGoogleLayer(e);case"osm":return this.createOSMLayer(e);case"wms":return this.createWMSLayer(e);case"wfs":return this.createWFSLayer(e);case"wcs":return this.createWCSLayer(e);case"arcgis":return this.createArcGISLayer(e);case"wkt":return this.createWKTLayer(e);case"geotiff":return this.createGeoTIFFLayer(e);default:throw new Error(`Unsupported layer type: ${e.type}`)}}async updateWMSLayer(e,t){e.setSource(new i({url:t.url,params:{LAYERS:t.layers,TILED:!0,...t.extraParams??{}}}))}async updateOSMLayer(e,t){let r="https://tile.openstreetmap.org/{z}/{x}/{y}.png";t.url&&(r=t.url+"/{z}/{x}/{y}.png"),e.setSource(new c({url:r}))}async updateGeoJSONLayer(e,t){let r=null;const o={featureProjection:this.projection};if(t.geojson){const e=JSON.parse(t.geojson);r=new a({features:new h(o).readFeatures(e)})}else r=new a({url:t.url,format:new h(o)});let s;e.setSource(r),t.geostylerStyle?s=await this.createGeostylerStyleFunction(t.geostylerStyle):t.style&&(s=await this.createEnhancedStyleFunction(t.style)),s&&e.setStyle(s)}async updateWFSLayer(e,t){const r=this.mergeLayerConfig(e,"wfsConfig",t),o=await this.createWFSSpource(r);let s;e.setSource(o),r.geostylerStyle?s=await this.createGeostylerStyleFunction(r.geostylerStyle):r.style&&(s=await this.createEnhancedStyleFunction(r.style)),s&&e.setStyle(s)}async updateWCSLayer(e,t){const r=this.mergeLayerConfig(e,"wcsConfig",t),o=await this.createWcsSource(r);e.setSource(o)}async updateArcGISLayer(e,t){const r=e,o=r.getSource(),s={...o?.getParams?.()??{},...t?.params??{}};t?.token&&(s.token=t.token);const n={url:t?.url??o?.getUrls?.()?.[0],params:s,...t?.options??{}},a=new f(n);r.setSource(a)}async createEnhancedStyleFunction(e){function t(e,t){if(e.startsWith("rgba")){const r=e.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(r){const[,e,o,s]=r;return`rgba(${e}, ${o}, ${s}, ${t})`}}else if(e.startsWith("rgb")){const r=e.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);if(r){const[,e,o,s]=r;return`rgba(${e}, ${o}, ${s}, ${t})`}}else if(e.startsWith("#")){const r=e.slice(1);return`rgba(${parseInt(r.slice(0,2),16)}, ${parseInt(r.slice(2,4),16)}, ${parseInt(r.slice(4,6),16)}, ${t})`}return e}return r=>{const o=[],s=r.getGeometry().getType(),n=new L({color:t(e.fillColor??"rgba(0,100,255,0.3)",e.fillOpacity??.3)}),a=e.strokeWidth??2,i=new G({color:t(e.strokeColor??"rgba(0,100,255,1)",e.strokeOpacity??1),width:a,lineDash:e.strokeDashArray});if(o.push(new S("Point"===s?e.iconUrl?{image:new j({src:e.iconUrl,size:e.iconSize||[32,32],anchor:e.iconAnchor||[.5,1]})}:{image:new I({radius:e.pointRadius??6,fill:new L({color:t(e.pointColor??"rgba(0,100,255,1)",e.pointOpacity??1)}),stroke:i})}:{fill:s.includes("Polygon")?n:void 0,stroke:i})),e.textProperty&&r.get(e.textProperty)){const t=e.textColor??"#000000",s=e.textSize??12,n=e.textHaloColor,a=e.textHaloWidth??2,i=e.textOffset||[0,0];o.push(new S({text:new v({text:String(r.get(e.textProperty)),font:`${s}px Arial`,fill:new L({color:t}),stroke:n?new G({color:n,width:a}):void 0,offsetX:i[0],offsetY:i[1]})}))}return o}}async createGeoJSONLayer(e){let t=null;const o={featureProjection:this.projection};if(e.geojson){const r=JSON.parse(e.geojson);t=new a({features:new h(o).readFeatures(r)})}else t=new a({url:e.url,format:new h(o)});let s;if(e.geostylerStyle)s=await this.createGeostylerStyleFunction(e.geostylerStyle);else{const t=e.style?{...$,...e.style}:$;s=await this.createEnhancedStyleFunction(t)}return new r({source:t,style:s})}async createWFSSpource(e){const t=(e.outputFormat??"application/json").toLowerCase();let r=new h;switch(t){case"gml2":r=new m;break;case"gml3":r=new p;break;case"gml32":r=new g}const o=this.getWFSGetFeatureUrl(e);return new a({format:r,url:o,strategy:E})}async createWFSLayer(e){const t=await this.createWFSSpource(e);let o;if(e.geostylerStyle)o=await this.createGeostylerStyleFunction(e.geostylerStyle);else{const t=e.style?{...$,...e.style}:$;o=await this.createEnhancedStyleFunction(t)}const s=new r({source:t,style:o});return s.set("wfsConfig",e,!1),s}async createGeostylerStyleFunction(e){const t=(e,t)=>null==e||"object"==typeof e&&e.name?t:e;return r=>{const o=[],s=r.getGeometry().getType();if(e.rules)for(const n of e.rules)if(n.symbolizers)for(const e of n.symbolizers)switch(e.kind){case"Fill":if(s.includes("Polygon")){const r=t(e.color,"rgba(0,100,255,0.3)"),s=t(e.outlineColor),n=t(e.outlineWidth,1);o.push(new S({fill:new L({color:r}),stroke:s?new G({color:s,width:n}):void 0}))}break;case"Line":{const r=t(e.color,"rgba(0,100,255,1)"),s=t(e.width,1),n=e.dasharray&&Array.isArray(e.dasharray)?e.dasharray.map((e=>t(e,0))):void 0;o.push(new S({stroke:new G({color:r,width:s,lineDash:n})}))}break;case"Mark":if("Point"===s){const r=t(e.color,"rgba(0,100,255,1)"),s=t(e.radius,6),n=t(e.strokeColor),a=t(e.strokeWidth,1);o.push(new S({image:new I({radius:s,fill:new L({color:r}),stroke:n?new G({color:n,width:a}):void 0})}))}break;case"Icon":if("Point"===s){const r=t(e.image),s=t(e.size,32),n=t(e.opacity,1);r&&"string"==typeof r&&o.push(new S({image:new j({src:r,size:[s,s],opacity:n})}))}break;case"Text":{const s=e,n=t(s.label);if(n&&r.get(n)){const e=t(s.color,"#000000"),a=t(s.size,12),i=t(s.font?.[0],"Arial"),c=t(s.haloColor),l=t(s.haloWidth,1),u=s.offset,f=u&&Array.isArray(u)?t(u[0],0):0,w=u&&Array.isArray(u)?t(u[1],0):0;o.push(new S({text:new v({text:String(r.get(n)),font:`${a}px ${i}`,fill:new L({color:e}),stroke:c?new G({color:c,width:l}):void 0,offsetX:f,offsetY:w})}))}}}return o.length>0?o:void 0}}async createXYZLayer(e){return new s({source:new l({url:e.url,attributions:e.attributions,maxZoom:e.maxZoom??19,...e.options??{}})})}async createGoogleLayer(e){if(!e.apiKey)throw new Error("Google-Layer benötigt 'apiKey' (Google Maps Platform).");const t=new u({key:e.apiKey,mapType:e.mapType??"roadmap",scale:e.scale??"scaleFactor2x",highDpi:e.highDpi??!0,language:e.language,region:e.region,imageFormat:e.imageFormat,styles:e.styles,layerTypes:e.layerTypes});t.on("change",(()=>{if("error"===t.getState()){const e=t.getError();T("Google source error",e),this.map.getTargetElement()?.dispatchEvent(new CustomEvent("google-source-error",{detail:{message:e??"Google source error"},bubbles:!0,composed:!0}))}}));const r=new s({source:t});if(!this.googleLogoAdded){class e extends b{constructor(){const e=document.createElement("img");e.style.pointerEvents="none",e.style.position="absolute",e.style.bottom="5px",e.style.left="5px",e.style.height="18px",e.alt="Google",e.src="https://developers.google.com/static/maps/documentation/images/google_on_white.png",super({element:e})}}this.map.addControl(new e),this.googleLogoAdded=!0}return r}async createOSMLayer(e){let t="https://tile.openstreetmap.org/{z}/{x}/{y}.png";return e.url&&(t=e.url+"/{z}/{x}/{y}.png"),new s({source:new c({url:t})})}async createWMSLayer(e){return new s({source:new i({url:e.url,params:{LAYERS:e.layers,TILED:!0,...e.extraParams??{}}})})}onLayerError(e,t){this.layerErrorCallbacks.set(e,t),this._getLayerById(e).then((t=>{t&&this.attachSourceErrorListeners(e,t)}))}offLayerError(e){this.layerErrorCleanups.get(e)?.(),this.layerErrorCleanups.delete(e),this.layerErrorCallbacks.delete(e)}attachSourceErrorListeners(e,t){this.layerErrorCleanups.get(e)?.();const r=this.layerErrorCallbacks.get(e);if(!r)return;const o=t.getSource?.();if(!o)return;const s=[];if("getTile"in o||o instanceof i||o instanceof c||o instanceof l||o instanceof u||o instanceof f){const e=()=>{r({type:"network",message:"Tile load error"})};o.on("tileloaderror",e),s.push((()=>o.un("tileloaderror",e)))}if(o instanceof a){const e=()=>{r({type:"network",message:"Feature load error"})};o.on("featuresloaderror",e),s.push((()=>o.un("featuresloaderror",e)))}if(o instanceof y){const e=()=>{r({type:"network",message:"Image load error"})};o.on("imageloaderror",e),s.push((()=>o.un("imageloaderror",e)))}const n=()=>{this.attachSourceErrorListeners(e,t)};t.on("change:source",n),s.push((()=>t.un("change:source",n))),this.layerErrorCleanups.set(e,(()=>s.forEach((e=>e()))))}async setView(e,t){this.map&&this.map.getView().animate({center:F(e),zoom:t,duration:0})}async _forEachLayer(e,t){if(e instanceof o){const r=e.getLayers().getArray();for(const e of r)if(await this._forEachLayer(e,t))return!0}else if(t(e))return!0;return!1}async _getLayerById(e){if(!this.map)return null;let t=null;return await this._forEachLayer(this.map.getLayerGroup(),(r=>{if(r.get("id")===e)return t=r,!0})),t||(t=this.baseLayers.find((t=>t.get("id")===e)),void 0===t?null:t)}async _getLayerGroupById(e){if(!this.map)return null;const t=this.layers.find((t=>t.get?.("groupId")===e));return void 0!==t?t:null}async removeLayer(e){if(!e)return;this.offLayerError(e);const t=await this._getLayerById(e);if(t){const e=t.get("group");e&&e.getLayers().remove(t)}}async setOpacity(e,t){if(!e)return;const r=await this._getLayerById(e);r&&r.setOpacity(t)}async setZIndex(e,t){if(!e)return;const r=await this._getLayerById(e);r&&r.setZIndex(t)}async setVisible(e,t){const r=await this._getLayerById(e);r&&r.setVisible(t)}async setGroupVisible(e,t){const r=await this._getLayerGroupById(e);r&&r.setVisible(t)}async updateWKTLayer(e,t){const r=new d;let o=null;const s=this.map?.getView()?.getProjection();if(t.wkt){const e=r.readFeature(t.wkt,{dataProjection:"EPSG:4326",featureProjection:s});o=new a({features:[e]})}else if(t.url){const e=await fetch(t.url);if(!e.ok)throw new Error(`Failed to fetch WKT: ${e.status}`);const n=await e.text(),i=r.readFeature(n,{dataProjection:"EPSG:4326",featureProjection:s});o=new a({features:[i]})}let n;o&&e.setSource(o),t.geostylerStyle?n=await this.createGeostylerStyleFunction(t.geostylerStyle):t.style&&(n=await this.createEnhancedStyleFunction(t.style)),n&&e.setStyle(n)}async createWKTLayer(e){const t=new d;let o=null;const s=this.map?.getView()?.getProjection();if(e.wkt)try{const r=t.readFeature(e.wkt,{dataProjection:"EPSG:4326",featureProjection:s});o=new a({features:[r]})}catch(e){T("Failed to parse WKT:",e),o=new a({features:[]})}else if(e.url)try{const r=await fetch(e.url);if(!r.ok)throw new Error(`Failed to fetch WKT: ${r.status}`);const n=await r.text(),i=t.readFeature(n,{dataProjection:"EPSG:4326",featureProjection:s});o=new a({features:[i]})}catch(e){T("Failed to load WKT from URL:",e),o=new a({features:[]})}else o=new a({features:[]});let n;if(e.geostylerStyle)n=await this.createGeostylerStyleFunction(e.geostylerStyle);else{const t=e.style?{...$,...e.style}:$;n=await this.createEnhancedStyleFunction(t)}return new r({source:o,style:n,opacity:e.opacity??1,visible:e.visible??!0,zIndex:e.zIndex??1e3})}async createGeoTIFFLayer(e){if(!e.url)throw new Error("GeoTIFF layer requires a URL");const t={url:e.url};null===e.nodata||isNaN(e.nodata)||(t.nodata=e.nodata);const r=new(await z({sources:[t],wrapX:!1}));return await r.registerProjectionIfNeeded(),new N({source:r,opacity:e.opacity??1,visible:e.visible??!0,zIndex:e.zIndex??100})}async createWCSLayer(e){const t=await this.createWcsSource(e),r=new n({source:t,visible:e.visible??!0,opacity:e.opacity??1});return r.set("wcsConfig",e,!1),r}getWFSGetFeatureUrl(e){return t=>{const r={service:"WFS",request:"GetFeature",version:e.version??"1.1.0",typeName:e.typeName,outputFormat:e.outputFormat??"application/json",bbox:t.join(","),srsName:e.srsName??this.projection,...e.params??{}};return this.appendParams(e.url,r)}}getWCSGetCoverageUrl(e,t){return r=>{const o=e.version??"2.0.1",s=e.format??"image/tiff",n=e.projection??this.projection,a={SERVICE:"WCS",REQUEST:"GetCoverage",VERSION:o,FORMAT:s};if(o.startsWith("2.0")){a.coverageId=e.coverageName;const[t,o,n,i]=r;a.subset=`X(${t},${n})`,a.subset2=`Y(${o},${i})`,(s.includes("tiff")||s.includes("geotiff"))&&(a["geotiff:compression"]="LZW")}else{a.COVERAGE=e.coverageName,a.BBOX=r.join(","),a.CRS=n;const o=Math.round((r[2]-r[0])/t),s=Math.round((r[3]-r[1])/t);a.WIDTH=o,a.HEIGHT=s}if(e.params&&Object.entries(e.params).forEach((([e,t])=>{"string"!=typeof t&&"number"!=typeof t||(a[e]=t)})),o.startsWith("2.0")){const t=a.subset2;delete a.subset2;const r=new URLSearchParams;Object.entries(a).forEach((([e,t])=>{null!=t&&r.append(e,String(t))})),t&&r.append("subset",String(t));const o=e.url;return`${o}${o.includes("?")?"&":"?"}${r.toString()}`}return this.appendParams(e.url,a)}}mergeLayerConfig(e,t,r){const o={...e.get(t)??{},...r};return e.set(t,o,!1),o}appendParams(e,t){const r=new URLSearchParams;return Object.entries(t).forEach((([e,t])=>{null!=t&&r.set(e,String(t))})),r.toString()?`${e}${e.includes("?")?"&":"?"}${r.toString()}`:e}async createWcsSource(e){const t=e.projection??this.projection,r=this.map?.getView()?.getResolution()??1,o=this.getWCSGetCoverageUrl(e,r);return new class extends y{urlFunction_;constructor(r){super({projection:t,resolutions:e.resolutions}),this.urlFunction_=r}getImageInternal(e,t,r,o){const s=this.urlFunction_(e),n=new w(e,t,r,s);return n.load=()=>{const e=n.getImage();e.src!==s&&(e.crossOrigin="anonymous",e.src=s)},n}}(o)}async createArcGISLayer(e){const t={...e.params??{}};e.token&&(t.token=e.token);const r={url:e.url,params:t,...e.options??{}};return new s({source:new f(r),visible:e.visible??!0})}async updateGeoTIFFLayer(e,t){if(!t.url)throw new Error("GeoTIFF update requires a URL");const r={url:t.url};null==t.nodata||isNaN(t.nodata)||(r.nodata=t.nodata);const o=new(await z({sources:[r],wrapX:!1}));await o.registerProjectionIfNeeded(),e.setSource(o)}getMap(){return this.map}}export{A as OpenLayersProvider}
|