PageSourceSearch

https://www.visorando.com/libs/js/visorando-map.umd.js?v=1790147288

js visorando.com collected 2026-09-24 09:13:57 UTC 193,698 bytes, 1 lines download raw bytes

1!function(t,i){"object"==typeof exports&&"undefined"!=typeof module?i(exports,require("maplibre-gl"),require("highcharts/highstock")):"function"==typeof define&&define.amd?define(["exports","maplibre-gl","highcharts/highstock"],i):i((t="undefined"!=typeof globalThis?globalThis:t||self).VisorandoMap={},t.maplibregl,t.Highcharts)}(this,function(t,i,e){"use strict";function s(t,i){for(var e=0;e<i.length;e++){const s=i[e];if("string"!=typeof s&&!Array.isArray(s))for(const i in s)if("default"!==i&&!(i in t)){const e=Object.getOwnPropertyDescriptor(s,i);e&&Object.defineProperty(t,i,e.get?e:{enumerable:!0,get:()=>s[i]})}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}class n{constructor(t,i,e=[],s){if(this.id=t,this.elevationAreas=s,!t||0===t.trim().length)throw new Error("Trail id cannot be empty");if(i.length<2)throw new Error("Trail path must have at least 2 points");this.path=[...i],this.waypoints=[...e]}path;waypoints;getPath(){return[...this.path]}getWaypoints(){return[...this.waypoints]}get waypointCount(){return this.waypoints.length}getElevationAreas(){return this.elevationAreas?[...this.elevationAreas]:void 0}}var r=(t=>(t.START="start",t.END="end",t.STAGE="stage",t.WAYPOINT="waypoint",t.BIKE_DIRECTION="bike-direction",t.BIKE_DIRECTION_INFO="bike-direction-info",t))(r||{});class o{constructor(t,i,e,s="waypoint",n,r,o,a=!1,h,l,c=!1,u,d){if(this.id=t,this.position=i,this.elevation=e,this.type=s,this.htmlContent=n,this.trailId=r,this.index=o,this.isStartEnd=a,this.wptTitle=h,this.wptText=l,this.hasBikeDirection=c,this.distanceFromStartMeters=u,this.raison=d,!t||0===t.trim().length)throw new Error("Waypoint id cannot be empty")}getBikeDirectionImageUrl(t){if(this.isBikeDirection()&&this.trailId&&void 0!==this.index)return`${t}${this.trailId}/${this.index}.jpg`}isBikeDirection(){return"bike-direction"===this.type||"bike-direction-info"===this.type||this.hasBikeDirection}isStage(){return"stage"===this.type}}class a{constructor(t,i,e){this.position=t,this.elevation=i,this.distanceFromStartMeters=e}}var h=6371008.8,l={centimeters:637100880,centimetres:637100880,degrees:360/(2*Math.PI),feet:20902260.511392,inches:39.37*h,kilometers:6371.0088,kilometres:6371.0088,meters:h,metres:h,miles:3958.761333810546,millimeters:6371008800,millimetres:6371008800,nauticalmiles:h/1852,radians:1,yards:6967335.223679999};function c(t,i,e={}){if(!t)throw new Error("coordinates is required");if(!Array.isArray(t))throw new Error("coordinates must be an Array");if(t.length<2)throw new Error("coordinates must be at least 2 numbers long");if(!p(t[0])||!p(t[1]))throw new Error("coordinates must contain numbers");return function(t,i,e={}){const s={type:"Feature"};return(0===e.id||e.id)&&(s.id=e.id),e.bbox&&(s.bbox=e.bbox),s.properties=i||{},s.geometry=t,s}({type:"Point",coordinates:t},i,e)}function u(t,i="kilometers"){const e=l[i];
1if(!e)throw new Error(i+" units is invalid");return t*e}function d(t){return t%360*Math.PI/180}function f(t,i="kilometers",e="kilometers"){if(!(t>=0))throw new Error("length must be a positive number");return u(function(t,i="kilometers"){const e=l[i];if(!e)throw new Error(i+" units is invalid");return t/e}(t,i),e)}function p(t){return!isNaN(t)&&null!==t&&!Array.isArray(t)}function m(t){if(!t)throw new Error("coord is required");if(!Array.isArray(t)){if("Feature"===t.type&&null!==t.geometry&&"Point"===t.geometry.type)return[...t.geometry.coordinates];if("Point"===t.type)return[...t.coordinates]}if(Array.isArray(t)&&t.length>=2&&!Array.isArray(t[0])&&!Array.isArray(t[1]))return[...t];throw new Error("coord must be GeoJSON Point or an Array of numbers")}class y{lat;lng;constructor(t,i){if(this.lat=t,this.lng=i,!this.isValid())throw new Error(`Invalid coordinates: lat=${t} (must be -90 to 90), lng=${i} (must be -180 to 180)`);Object.freeze(this)}distanceTo(t){return 1e3*function(t,i,e={}){var s=m(t),n=m(i),r=d(n[1]-s[1]),o=d(n[0]-s[0]),a=d(s[1]),h=d(n[1]),l=Math.pow(Math.sin(r/2),2)+Math.pow(Math.sin(o/2),2)*Math.cos(a)*Math.cos(h);return u(2*Math.atan2(Math.sqrt(l),Math.sqrt(1-l)),e.units)}(c([this.lng,this.lat]),c([t.lng,t.lat]),{units:"kilometers"})}isValid(){return this.lat>=-90&&this.lat<=90&&this.lng>=-180&&this.lng<=180&&!isNaN(this.lat)&&!isNaN(this.lng)}}class w{meters;constructor(t){if(isNaN(t))throw new Error(`Invalid elevation: ${t} (must be a valid number)`);this.meters=t,Object.freeze(this)}toMeters(){return this.meters}}var v=(t=>(t.RASTER="raster",t.VECTOR="vector",t))(v||{}),g=(t=>(t.BASE="base",t.OVERLAY="overlay",t))(g||{});class b{constructor(t,i,e,s,n,r,o,a,h,l,c,u,d){this.id=t,this.name=i,this.category=e,this.type=s,this.source=n,this.group=r,this.order=o,this.defaultVisible=a,this.access=h,this.description=l,this.paint=c,this.styleUrl=u,this.thumbnailUrl=d,Object.freeze(this)}static create(t){return new b(t.id,t.name,t.category,t.type,t.source,t.group,t.order??0,t.defaultVisible??!1,t.access,t.description,t.paint,t.styleUrl,t.thumbnailUrl)}isBaseLayer(){return this.category===g.BASE}isOverlay(){return this.category===g.OVERLAY}}const M={minZoom:0,maxZoom:22,minPitch:0,maxPitch:80,pitch:0,bearing:0,pitchWithRotate:!0,dragRotate:!0,touchPitch:!0,touchZoomRotate:!0,maxTileCacheSize:2e3,renderWorldCopies:!0,fadeDuration:50,coordinateFormat:"UTM",elevationUnit:"m",enableTracking:!1},S={minPitch:0,maxPitch:60,enablePitch:!1,enableRotation:!1,enable3DMode:!1,showMouseCoordinates:!1,coordinateFormat:"UTM",elevationUnit:"m",maxTileCacheSize:500,renderWorldCopies:!1,fadeDuration:300,enableTracking:!1,showControls:!0,stylesBaseUrl:"https://www.visorando.com"},C=new Map;let L="https://www.visorando.com";async function $(t){const i=function(t){return/^https?:\/\//i.test(t)?t:`${L}/${t.replace(/^\//,"")}`}(t),e=C.get(i);if(e)return e;const s=(async()=>{const t=await fetch(i,{credentials:"same-origin",headers:{Accept:"application/json"}});if(!t.ok)throw new Error(`Failed to load style fragment from ${i}: ${t.status} ${t.statusText}`);return function(t){for(const i of t.layers??[]){const t=i.layout;if(t)for(const[i,e]of Object.entries(t))t[i]=F(e)}return t}(await t.json())})();return C.set(i,s),s.catch(()=>C.delete(i)),s}function F(t){if(!Array.isArray(t))return t;const i=t.map(t=>F(t));return"number-format"===i[0]&&Array.isArray(i[2])&&0===i[2].length&&(i[2]={}),i}async function O(t){try{const i=await fetch(t,{credentials:"same-origin",headers:{Accept:"application/json"}});if(!i.ok)throw new Error(`Failed to load custom style from ${t}: ${i.status} ${i.statusText}`);return await i.json()}catch(i){throw new Error(`Failed to load custom style: ${i instanceof Error?i.message:"Unknown error"}`)}}const k="https://dem.visomap.com/{z}/{x}/{y}.webp",x=16,A="terrarium",T="https://tileservergl.tests.in.visorando.com/fonts/{fontstack}/{range}.pbf",P="summits-labels";function E(t,i,e={}){return{id:`waypoints-symbol-${t}`,type:"symbol",source:"waypoints-source",filter:["==",["get","icon"],t],layout:{"icon-image":t,"icon-size":["interpolate",["linear"],["zoom"],8,.5,16,1],"icon-anchor":"bottom","icon-allow-overlap":!0,"icon-ignore-placement":!0,...e},paint:{"icon-opacity":.85},metadata:{"visorando:category":"waypoints","visorando:icon-url":i}}}function R(t,i){return{...t,layout:{...t.layout??{},visibility:i}}}function N(t,i){const e="3d"===i?"3d":"web";return t+(t.includes("?")?"&":"?")+`variant=${e}`}const B="contour-source",U={15:[20,100]},I="level",D="contours";function G(t){return{type:"vector",tiles:[t({multiplier:1,thresholds:U,elevationKey:"ele",levelKey:I,contourLayer:D,extent:4096,buffer:1,overzoom:2})],maxzoom:15}}const _={id:"contour-lines-major",type:"line",source:B,"source-layer":D,filter:["==",I,1],metadata:{"visorando:runtime":!0},minzoom:15,paint:{"line-color":"#8b6914","line-width":["interpolate",["linear"],["zoom"],11,1.2,15,2],"line-opacity":.8,"line-blur"
1:0},layout:{visibility:"none"}},z={id:"contour-lines-minor",type:"line",source:B,"source-layer":D,filter:["==",I,0],metadata:{"visorando:runtime":!0},minzoom:15,paint:{"line-color":["interpolate",["linear"],["zoom"],11,"rgba(100,50,13,0.25)",18,"rgba(164,87,25,0.8)"],"line-width":["match",["get","level"],1,1.2,.5]},layout:{visibility:"none"}},j={id:"contour-labels",type:"symbol",source:B,"source-layer":D,filter:["==",I,1],metadata:{"visorando:runtime":!0},minzoom:15,layout:{"symbol-placement":"line","text-keep-upright":!1,"text-rotation-alignment":"map","text-pitch-alignment":"map","text-field":["number-format",["get","ele"],{}],"text-font":["Noto Sans Regular"],"text-size":12,"symbol-spacing":["interpolate",["linear"],["zoom"],15,500,17,350],"text-max-angle":30,"text-padding":4,"text-letter-spacing":.05},paint:{"text-color":"rgba(117,74,46,0.9)","text-halo-color":"rgba(255, 246, 232, 0.7)","text-halo-width":1}};function H(t,i,e){const s=t.findIndex(t=>t.id===i);-1!==s?t.splice(s+1,0,...e):t.push(...e)}const W={SLOPES:{titleKey:"layers.slopes",table:{"#F0E54C":"layers.legend.slopes.30_35","#E6993C":"layers.legend.slopes.35_40","#E33122":"layers.legend.slopes.40_45","#BF8CB8":"layers.legend.slopes.gt45"}},MAPPATOU:{titleKey:"layers.mappatou",table:{"#FF8040":"layers.legend.mappatou.noDogs","#AD62C2":"layers.legend.mappatou.dogs","#777777":"layers.legend.mappatou.unknown"}},GROUP_SNOWCOVER:{titleKey:"layers.snow",table:{"#add8e6":"layers.legend.snowcover.1_5cm","#87cfeb":"layers.legend.snowcover.6_15cm","#6493ed":"layers.legend.snowcover.16_30cm","#4169e1":"layers.legend.snowcover.31_50cm","#00008b":"layers.legend.snowcover.gt50cm"}},GROUP_FRESH_SNOW:{titleKey:"layers.freshSnow",table:{"#ffc0e6":"layers.legend.freshSnow.1_5cm","#ff80ff":"layers.legend.freshSnow.6_15cm","#ff33ff":"layers.legend.freshSnow.16_30cm","#cc00cc":"layers.legend.freshSnow.31_50cm","#8b008b":"layers.legend.freshSnow.gt50cm"}}},V={maps:[{id:"IGNTOPO",title:"Topo",styleUrl:"https://www.visorando.com/app/styles/maps/IGNTOPO.json"},{id:"IGNSAT",title:"Satellite",styleUrl:"https://www.visorando.com/app/styles/maps/IGNSAT.json"},{id:"HIKINGMAP",title:"OSM rando",styleUrl:"https://www.visorando.com/app/styles/maps/HIKINGMAP.json"},{id:"MAPNIK",title:"OSM",styleUrl:"https://www.visorando.com/app/styles/maps/MAPNIK.json"},{id:"CYCLINGMAP",title:"OSM vélo",styleUrl:"https://www.visorando.com/app/styles/maps/CYCLINGMAP.json"},{id:"TOPO_VECTO",title:"Topo vector",styleUrl:"https://www.visorando.com/app/styles/maps/TOPO_VECTO.json",thumbnailURL:"https://www.visorando.com/img/layers/thumbnails/16-9/visovector.jpg",webRequiresPremium:!0,minUserGid:9,visibilityMinUserGid:9,runtimeContours:{linesAfterLayerId:"River tunnel",labelsAfterLayerId:"River labels"},sharedDemSourceId:"mapterhorn"}],overlay_groups:[{id:"SLOPES",title:"Pentes",overlays:[{id:"SLOPES",title:"Pentes",styleUrl:"https://www.visorando.com/app/styles/layers/SLOPES.json",webRequiresPremium:!0,minUserGid:2}]},{id:"MAPPATOU",title:"Troupeaux et chiens de protection",overlays:[{id:"MAPPATOU",title:"Troupeaux et chiens de protection",styleUrl:"https://www.visorando.com/app/styles/layers/MAPPATOU.json",webRequiresPremium:!1,minUserGid:2}]},{id:"GROUP_SNOWCOVER",slug:"enneigement",title:"Enneigement",overlays:[{id:"SNOWCOVER",title:"Aujourd'hui",styleUrl:"https://www.visorando.com/app/styles/layers/SNOWCOVER.json",webRequiresPremium:!0,minUserGid:2},{id:"SNOWCOVER_FORECAST_24H",title:"+24h",styleUrl:"https://www.visorando.com/app/styles/layers/SNOWCOVER_FORECAST_24H.json",webRequiresPremium:!0,minUserGid:2},{id:"SNOWCOVER_FORECAST_48H",title:"+48h",styleUrl:"https://www.visorando.com/app/styles/layers/SNOWCOVER_FORECAST_48H.json",webRequiresPremium:!0,minUserGid:2}]},{id:"GROUP_FRESH_SNOW",slug:"neige-fraiche",title:"Neige fraîche",overlays:[{id:"FRESH_SNOW",title:"Aujourd'hui",styleUrl:"https://www.visorando.com/app/styles/layers/FRESH_SNOW.json",webRequiresPremium:!0,minUserGid:2},{id:"FRESH_SNOW_FORECAST_24H",title:"+24h",styleUrl:"https://www.visorando.com/app/styles/layers/FRESH_SNOW_FORECAST_24H.json",webRequiresPremium:!0,minUserGid:2},{id:"FRESH_SNOW_FORECAST_48H",title:"+48h",styleUrl:"https://www.visorando.com/app/styles/layers/FRESH_SNOW_FORECAST_48H.json",webRequiresPremium:!0,minUserGid:2}]}]};function K(t){if(!t||"object"!=typeof t)return null;let i=t;return!Array.isArray(i.maps)&&i.content&&"object"==typeof i.content&&(i=i.content),Array.isArray(i.maps)?{..."string"==typeof i.mapLegendsUrl&&{mapLegendsUrl:i.mapLegendsUrl},..."string"==typeof i.glyphsUrl&&{glyphsUrl:i.glyphsUrl},maps:i.maps,overlay_groups:Array.isArray(i.overlay_groups)?i.overlay_groups:[]}:null}function Z(t){return t.slug?t.slug:t.overlays.length>1?t.id??t.title:void 0}function q(t){return{useMinUserGid:t.minUserGid??0,useRequiresPremium:t.webRequiresPremium??t.premium??!1,...void 0!==t.visibilityMinUserGid&&{visibilityMinUserGid:t.visibilityMinUserGid}}}const Y=new class{currentLocale="fr";translations=null;baseUrl="";setBaseUrl(t){this.baseUrl=t}async init(t="fr"){this.currentLocale=t;try{const i=this.baseUrl?`${this.baseUrl}/${t}.json`:`/locales/${t}.json`,e=await fetch(i);if(!e.ok)throw new Error(`Failed to fetch translation file: ${e.statusText}`);this.translations=await e.json()}catch{this.translations={}}}t(t,i){if(!this.translations)return t;const e=t.split(".");let s=this.translations;for(const r of e)if(s=s?.[r],void 0===s)return t;let n=String(s);
1return i&&Object.entries(i).forEach(([t,i])=>{n=n.replace(`{${t}}`,String(i))}),n}getLanguage(){return this.currentLocale}async changeLanguage(t){await this.init(t)}};function J(t){Y.setBaseUrl(t)}async function X(t="fr"){await Y.init(t)}function Q(t,i){return Y.t(t,i)}function tt(){return Y.getLanguage()}class it{enabled;constructor(t=!1){this.enabled=t}enable(){this.enabled=!0}trackEvent(t,i,e){if(!this.enabled)return;const s=window;void 0!==s._paq&&s._paq.push(["trackEvent",t,i,e])}}class et{platform;isReady=!1;messageCallbacks=[];constructor(t=null){this.platform=t,this.isReady=this.checkPlatformReady(),this.setupMessageReceiver()}setupMessageReceiver(){this.platform&&(window.visorandoMapReceiveMessage=t=>{const i=JSON.parse(t);this.messageCallbacks.forEach(t=>{t(i.type,i.payload)})})}onMessage(t){this.messageCallbacks.push(t)}checkPlatformReady(){return!!this.platform&&("ios"===this.platform?!!window.webkit?.messageHandlers?.visorandoMap:"android"===this.platform&&!!window.VisorandoMapAndroid)}sendEvent(t){if(!this.platform)return;if(!this.isReady)return;const i=JSON.stringify(t);"ios"===this.platform?window.webkit?.messageHandlers?.visorandoMap?.postMessage(i):"android"===this.platform&&window.VisorandoMapAndroid?.postMessage(i)}sendMapReady(t){const i={type:"mapReady",...void 0!==t&&{payload:t},timestamp:Date.now()};this.sendEvent(i)}sendCustomEvent(t,i){const e={type:t,...void 0!==i&&{payload:i},timestamp:Date.now()};this.sendEvent(e)}}var st,nt,rt,ot=.9996,at=.00669438,ht=Math.pow(at,2),lt=Math.pow(at,3),ct=at/(1-at),ut=1-at/4-3*ht/64-5*lt/256,dt=3*at/8+3*ht/32+45*lt/1024,ft=15*ht/256+45*lt/1024,pt=35*lt/3072,mt=6378137;function yt(t){return t*Math.PI/180}function wt(t,i){const e=Math.abs(t),s=Math.floor(e),n=60*(e-s),r=Math.floor(n),o=(60*(n-r)).toFixed(4);return`${Q(i?t>=0?"coordinates.cardinalPoints.north":"coordinates.cardinalPoints.south":t>=0?"coordinates.cardinalPoints.east":"coordinates.cardinalPoints.west")} ${s}° ${r}' ${o}"`}function vt(t,i,e="UTM"){switch(e){case"DD":{const e=Q(t>=0?"coordinates.cardinalPoints.north":"coordinates.cardinalPoints.south"),s=Q(i>=0?"coordinates.cardinalPoints.east":"coordinates.cardinalPoints.west");return`${e} ${Math.abs(t).toFixed(5)} ${s} ${Math.abs(i).toFixed(5)}`}case"DMS":return`${wt(t,!0)} ${wt(i,!1)}`;case"UTM":{const e=function(t,i){if(t>84||t<-80)throw new RangeError("latitude out of range (must be between 80 deg S and 84 deg N)");if(i>180||i<-180)throw new RangeError("longitude out of range (must be between 180 deg W and 180 deg E)");var e,s=yt(t),n=Math.sin(s),r=Math.cos(s),o=Math.tan(s),a=Math.pow(o,2),h=Math.pow(o,4);e=function(t,i){if(56<=t&&t<64&&3<=i&&i<12)return 32;if(72<=t&&t<=84&&i>=0){if(i<9)return 31;
1if(i<21)return 33;if(i<33)return 35;if(i<42)return 37}return Math.floor((i+180)/6)+1}(t,i);var l=function(t){return-80<=t&&t<=84?"CDEFGHJKLMNPQRSTUVWXX"[Math.floor((t+80)/8)]:null}(t),c=yt(i),u=yt(function(t){return 6*(t-1)-180+3}(e)),d=mt/Math.sqrt(1-at*n*n),f=ct*r*r,p=r*(c-u),m=Math.pow(p,2),y=Math.pow(p,3),w=Math.pow(p,4),v=Math.pow(p,5),g=Math.pow(p,6),b=mt*(ut*s-dt*Math.sin(2*s)+ft*Math.sin(4*s)-pt*Math.sin(6*s)),M=ot*(b+d*o*(m/2+w/24*(5-a+9*f+4*f*f)+g/720*(61-58*a+h+600*f-330*ct)));return t<0&&(M+=1e7),{easting:ot*d*(p+y/6*(1-a+f)+v/120*(5-18*a+h+72*f-58*ct))+5e5,northing:M,zoneNum:e,zoneLetter:l}}(t,i);return`${e.zoneNum}${e.zoneLetter} ${e.easting.toFixed(3)} ${e.northing.toFixed(3)}`}default:return`${t.toFixed(5)}, ${i.toFixed(5)}`}}function gt(t,i){if(st)if(nt){var e="var sharedChunk = {}; ("+st+")(sharedChunk); ("+nt+")(sharedChunk);",s={};st(s),rt=i(s),"undefined"!=typeof window&&(rt.workerUrl=window.URL.createObjectURL(new Blob([e],{type:"text/javascript"})))}else nt=i;else st=i}gt(0,function(t){class i{constructor(t,i){this.start=t,this.end=i,this.points=[],this.append=this.append.bind(this),this.prepend=this.prepend.bind(this)}append(t,i){this.points.push(Math.round(t),Math.round(i))}prepend(t,i){this.points.splice(0,0,Math.round(t),Math.round(i))}lineString(){return this.toArray()}isEmpty(){return this.points.length<2}appendFragment(t){this.points.push(...t.points),this.end=t.end}toArray(){return this.points}}const e=[[],[[[1,2],[0,1]]],[[[2,1],[1,2]]],[[[2,1],[0,1]]],[[[1,0],[2,1]]],[[[1,2],[0,1]],[[1,0],[2,1]]],[[[1,0],[1,2]]],[[[1,0],[0,1]]],[[[0,1],[1,0]]],[[[1,2],[1,0]]],[[[0,1],[1,0]],[[2,1],[1,2]]],[[[2,1],[1,0]]],[[[0,1],[2,1]]],[[[1,2],[2,1]]],[[[0,1],[1,2]]],[]];function s(t,i,e,s){return(i=2*i+s[0])+(e=2*e+s[1])*(t+1)*2}function n(t,i,e){return(i-t)/(e-t)}function r(t,r,o=4096,a=1){if(!t)return{};const h=o/(r.width-1);let l,c,u,d,f,p;const m={},y=new Map,w=new Map;function v(t,i,e){0===t[0]?e(h*(p-1),h*(f-n(u,i,l))):2===t[0]?e(h*p,h*(f-n(d,i,c))):0===t[1]?e(h*(p-n(c,i,l)),h*(f-1)):e(h*(p-n(d,i,u)),h*f)}for(f=1-a;f<r.height+a;f++){c=r.get(0,f-1),d=r.get(0,f);let n=Math.min(c,d),o=Math.max(c,d);for(p=1-a;p<r.width+a;p++){l=c,u=d,c=r.get(p,f-1),d=r.get(p,f);const a=n,h=o;if(n=Math.min(c,d),o=Math.max(c,d),isNaN(l)||isNaN(c)||isNaN(d)||isNaN(u))continue;const g=Math.min(a,n),b=Math.max(h,o),M=Math.ceil(g/t)*t,S=Math.floor(b/t)*t;for(let n=M;n<=S;n+=t){const t=l>n,o=c>n,a=u>n,h=d>n;for(const l of e[(t?8:0)|(o?4:0)|(h?2:0)|(a?1:0)]){let t=y.get(n);t||y.set(n,t=new Map);let e=w.get(n);e||w.set(n,e=new Map);const o=l[0],a=l[1],h=s(r.width,p,f,o),c=s(r.width,p,f,a);let u,d;if(u=e.get(h))if(e.delete(h),d=t.get(c))if(t.delete(c),u===d){if(v(a,n,u.append),!u.isEmpty()){let t=m[n];t||(m[n]=t=[]),t.push(u.lineString())}}else u.appendFragment(d),e.set(u.end=d.end,u);else v(a,n,u.append),e.set(u.end=c,u);else if(u=t.get(c))t.delete(c),v(o,n,u.prepend),t.set(u.start=h,u);else{const s=new i(h,c);v(o,n,s.append),v(a,n,s.append),t.set(h,s),e.set(c,s)}}}}}for(const[i,e]of y.entries()){let t=null;for(const s of e.values())s.isEmpty()||(null==t&&(t=m[i]||(m[i]=[])),t.push(s.lineString()))}return m}function o(t,i){var e={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&i.indexOf(s)<0&&(e[s]=t[s]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(s=Object.getOwnPropertySymbols(t);n<s.length;n++)i.indexOf(s[n])<0&&Object.prototype.propertyIsEnumerable.call(t,s[n])&&(e[s[n]]=t[s[n]])}return e}function a(t,i,e,s){return new(e||(e=Promise))(function(n,r){function o(t){try{h(s.next(t))}catch(i){r(i)}}function a(t){try{h(s.throw(t))}catch(i){r(i)}}function h(t){var i;t.done?n(t.value):(i=t.value,i instanceof e?i:new e(function(t){t(i)})).then(o,a)}h((s=s.apply(t,i||[])).next())})}function h(t){const i=Object.entries(t);return i.sort(([t],[i])=>t<i?-1:t>i?1:0),i}function l(t){return h(t).map(([t,i])=>[t,..."number"==typeof i?[i]:i].join("*")).join("~")}function c(t){return h(t).map(([t,i])=>`${encodeURIComponent(t)}=${encodeURIComponent(i)}`).join(",")}let u=null;function d(){return null==u&&(u="undefined"!=typeof OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&"function"==typeof createImageBitmap),u||!1}let f=null;function p(t,i,e){let s=()=>{};const n=setTimeout(()=>{s(new Error("timed out")),null==e||e.abort()},t);m(e,()=>{s(new Error("aborted")),clearTimeout(n)});const r=new Promise((t,i)=>{s=i});return Promise.race([r,i.finally(()=>clearTimeout(n))])}function m(t,i){i&&(null==t||t.signal.addEventListener("abort",i))}function y(t){var i;return Boolean(null===(i=null==t?void 0:t.signal)||void 0===i?void 0:i.aborted)}let w,v,g,b,M=0;class S{constructor(t=100){this.size=()=>this.items.size,this.get=(t,i,e)=>{let s=this.items.get(t);if(s)s.lastUsed=++M,s.waiting++;else{const e=new AbortController,n=i(t,e);s={abortController:e,item:n,lastUsed:++M,waiting:1},this.items.set(t,s),this.prune()}const n=this.items,r=s.item.then(t=>t,i=>(n.delete(t),Promise.reject(i)));let o=!1;return m(e,()=>{var i;s&&s.abortController&&!o&&(o=!0,--s.waiting<=0&&(null===(i=s.abortController)||void 0===i||i.abort(),n.delete(t)))}),r},this.clear=()=>this.items.clear(),this.maxSize=t,this.items=new Map}
1prune(){if(this.items.size>this.maxSize){let t,i=1/0;this.items.forEach((e,s)=>{e.lastUsed<i&&(i=e.lastUsed,t=s)}),void 0!==t&&this.items.delete(t)}}}function C(t,i){return w||(w=new OffscreenCanvas(t.width,t.height),v=w.getContext("2d",{willReadFrequently:!0})),$(t,i,w,v)}const L=function(){if(null==f&&(f=!1,d()&&"undefined"!=typeof VideoFrame)){const t=5,i=new OffscreenCanvas(5,5).getContext("2d",{willReadFrequently:!0});if(i){for(let s=0;s<t*t;s++){const e=4*s;i.fillStyle=`rgb(${e},${e+1},${e+2})`,i.fillRect(s%t,Math.floor(s/t),1,1)}const e=i.getImageData(0,0,t,t).data;for(let i=0;i<t*t*4;i++)if(i%4!=3&&e[i]!==i){f=!0;break}}}return f||!1}()?function(t,i,e){return a(this,void 0,void 0,function*(){var s,n,r;const o=yield createImageBitmap(t);if(y(e))return null;const a=new VideoFrame(o,{timestamp:0});try{if(!(null===(s=null==a?void 0:a.format)||void 0===s?void 0:s.startsWith("BGR"))&&!(null===(n=null==a?void 0:a.format)||void 0===n?void 0:n.startsWith("RGB")))throw new Error(`Unrecognized format: ${null==a?void 0:a.format}`);const t=null===(r=null==a?void 0:a.format)||void 0===r?void 0:r.startsWith("BGR"),e=a.allocationSize(),h=new Uint8ClampedArray(e);if(yield a.copyTo(h),t)for(let i=0;i<h.length;i+=4){const t=h[i];h[i]=h[i+2],h[i+2]=t}return F(o.width,o.height,i,h)}catch(h){return y(e)?null:C(o,i)}finally{a.close()}})}:d()?function(t,i,e){return a(this,void 0,void 0,function*(){const s=yield createImageBitmap(t);return y(e)?null:C(s,i)})}:"undefined"!=typeof WorkerGlobalScope&&"undefined"!=typeof self&&self instanceof WorkerGlobalScope?function(t,i,e){return self.actor.send("decodeImage",[],e,void 0,t,i)}:function(t,i,e){return a(this,void 0,void 0,function*(){g||(g=document.createElement("canvas"),b=g.getContext("2d",{willReadFrequently:!0}));const s=new Image;return m(e,()=>s.src=""),$(yield new Promise((i,n)=>{s.onload=()=>{y(e)||i(s),URL.revokeObjectURL(s.src),s.onload=null},s.onerror=()=>n(new Error("Could not load image.")),s.src=t.size?URL.createObjectURL(t):""}),i,g,b)})};function $(t,i,e,s){if(e.width=t.width,e.height=t.height,!s)throw new Error("failed to get context");s.drawImage(t,0,0,t.width,t.height);const n=s.getImageData(0,0,t.width,t.height).data;return F(t.width,t.height,i,n)}function F(t,i,e,s){const n="mapbox"===e?(t,i,e)=>.1*(256*t*256+256*i+e)-1e4:(t,i,e)=>256*t+i+e/256-32768,r=new Float32Array(t*i);for(let o=0;o<s.length;o+=4)r[o/4]=n(s[o],s[o+1],s[o+2]);return{width:t,height:i,data:r}}class O{constructor(t,i,e){this.split=(t,i,e)=>{if(0===t)return this;const s=1<<t,n=i*this.width/s,r=e*this.height/s;return new O(this.width/s,this.height/s,(t,i)=>this.get(t+n,i+r))},this.subsamplePixelCenters=t=>{const i=(t,i,e)=>isNaN(t)?i:isNaN(i)?t:t+(i-t)*e;if(t<=1)return this;const e=.5-1/(2*t);return new O(this.width*t,this.height*t,(s,n)=>{const r=s/t-e,o=n/t-e,a=Math.floor(r),h=Math.floor(o),l=this.get(a,h),c=this.get(a+1,h),u=this.get(a,h+1),d=this.get(a+1,h+1),f=r-a,p=o-h,m=i(l,c,f),y=i(u,d,f);return i(m,y,p)})},this.averagePixelCentersToGrid=(t=1)=>new O(this.width+1,this.height+1,(i,e)=>{let s=0,n=0,r=0;for(let o=i-t;o<i+t;o++)for(let i=e-t;i<e+t;i++)isNaN(r=this.get(o,i))||(n++,s+=r);return 0===n?NaN:s/n}),this.scaleElevation=t=>1===t?this:new O(this.width,this.height,(i,e)=>this.get(i,e)*t),this.materialize=(t=2)=>{const i=this.width+2*t,e=new Float32Array(i*(this.height+2*t));let s=0;for(let n=-t;n<this.height+t;n++)for(let i=-t;i<this.width+t;i++)e[s++]=this.get(i,n);return new O(this.width,this.height,(s,n)=>e[(n+t)*i+s+t])},this.get=e,this.width=t,this.height=i}static fromRawDem(t){return new O(t.width,t.height,(i,e)=>{const s=t.data[e*t.width+i];return n=s,!isNaN(n)&&n>=-12e3&&n<=9e3?s:NaN;var n})}
1static combineNeighbors(t){if(9!==t.length)throw new Error("Must include a tile plus 8 neighbors");const i=t[4];if(!i)return;const e=i.width,s=i.height;return new O(e,s,(i,n)=>{let r=0;n<0?n+=s:n<s?r+=3:(n-=s,r+=6),i<0?i+=e:i<e?r+=1:(i-=e,r+=2);const o=t[r];return o?o.get(i,n):NaN})}}const k=4294967296,x=1/k,A="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8");class T{constructor(t=new Uint8Array(16)){this.buf=ArrayBuffer.isView(t)?t:new Uint8Array(t),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length}readFields(t,i,e=this.length){for(;this.pos<e;){const e=this.readVarint(),s=e>>3,n=this.pos;this.type=7&e,t(s,i,this),this.pos===n&&this.skip(e)}return i}readMessage(t,i){return this.readFields(t,i,this.readVarint()+this.pos)}readFixed32(){const t=this.dataView.getUint32(this.pos,!0);return this.pos+=4,t}readSFixed32(){const t=this.dataView.getInt32(this.pos,!0);return this.pos+=4,t}readFixed64(){const t=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*k;return this.pos+=8,t}readSFixed64(){const t=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*k;return this.pos+=8,t}readFloat(){const t=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,t}readDouble(){const t=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,t}readVarint(t){const i=this.buf;let e,s;return s=i[this.pos++],e=127&s,s<128?e:(s=i[this.pos++],e|=(127&s)<<7,s<128?e:(s=i[this.pos++],e|=(127&s)<<14,s<128?e:(s=i[this.pos++],e|=(127&s)<<21,s<128?e:(s=i[this.pos],e|=(15&s)<<28,function(t,i,e){const s=e.buf;let n,r;if(r=s[e.pos++],n=(112&r)>>4,r<128)return P(t,n,i);if(r=s[e.pos++],n|=(127&r)<<3,r<128)return P(t,n,i);if(r=s[e.pos++],n|=(127&r)<<10,r<128)return P(t,n,i);if(r=s[e.pos++],n|=(127&r)<<17,r<128)return P(t,n,i);if(r=s[e.pos++],n|=(127&r)<<24,r<128)return P(t,n,i);if(r=s[e.pos++],n|=(1&r)<<31,r<128)return P(t,n,i);throw new Error("Expected varint not more than 10 bytes")}(e,t,this)))))}readVarint64(){return this.readVarint(!0)}readSVarint(){const t=this.readVarint();return t%2==1?(t+1)/-2:t/2}readBoolean(){return Boolean(this.readVarint())}readString(){const t=this.readVarint()+this.pos,i=this.pos;return this.pos=t,t-i>=12&&A?A.decode(this.buf.subarray(i,t)):function(t,i,e){let s="",n=i;for(;n<e;){const i=t[n];let r,o,a,h=null,l=i>239?4:i>223?3:i>191?2:1;if(n+l>e)break;1===l?i<128&&(h=i):2===l?(r=t[n+1],128==(192&r)&&(h=(31&i)<<6|63&r,h<=127&&(h=null))):3===l?(r=t[n+1],o=t[n+2],128==(192&r)&&128==(192&o)&&(h=(15&i)<<12|(63&r)<<6|63&o,(h<=2047||h>=55296&&h<=57343)&&(h=null))):4===l&&(r=t[n+1],o=t[n+2],a=t[n+3],128==(192&r)&&128==(192&o)&&128==(192&a)&&(h=(15&i)<<18|(63&r)<<12|(63&o)<<6|63&a,(h<=65535||h>=1114112)&&(h=null))),null===h?(h=65533,l=1):h>65535&&(h-=65536,s+=String.fromCharCode(h>>>10&1023|55296),h=56320|1023&h),s+=String.fromCharCode(h),n+=l}return s}(this.buf,i,t)}readBytes(){const t=this.readVarint()+this.pos,i=this.buf.subarray(this.pos,t);return this.pos=t,i}readPackedVarint(t=[],i){const e=this.readPackedEnd();for(;this.pos<e;)t.push(this.readVarint(i));return t}readPackedSVarint(t=[]){const i=this.readPackedEnd();for(;this.pos<i;)t.push(this.readSVarint());return t}readPackedBoolean(t=[]){const i=this.readPackedEnd();for(;this.pos<i;)t.push(this.readBoolean());return t}readPackedFloat(t=[]){const i=this.readPackedEnd();for(;this.pos<i;)t.push(this.readFloat());return t}readPackedDouble(t=[]){const i=this.readPackedEnd();for(;this.pos<i;)t.push(this.readDouble());return t}readPackedFixed32(t=[]){const i=this.readPackedEnd();for(;this.pos<i;)t.push(this.readFixed32());return t}readPackedSFixed32(t=[]){const i=this.readPackedEnd();for(;this.pos<i;)t.push(this.readSFixed32());return t}readPackedFixed64(t=[]){const i=this.readPackedEnd();for(;this.pos<i;)t.push(this.readFixed64());return t}readPackedSFixed64(t=[]){const i=this.readPackedEnd();for(;this.pos<i;)t.push(this.readSFixed64());return t}readPackedEnd(){return 2===this.type?this.readVarint()+this.pos:this.pos+1}skip(t){const i=7&t;if(0===i)for(;this.buf[this.pos++]>127;);else if(2===i)this.pos=this.readVarint()+this.pos;else if(5===i)this.pos+=4;else{if(1!==i)throw new Error(`Unimplemented type: ${i}`);this.pos+=8}}writeTag(t,i){this.writeVarint(t<<3|i)}realloc(t){let i=this.length||16;for(;i<this.pos+t;)i*=2;if(i!==this.length){const t=new Uint8Array(i);t.set(this.buf),this.buf=t,this.dataView=new DataView(t.buffer),this.length=i}}finish(){return this.length=this.pos,this.pos=0,this.buf.subarray(0,this.length)}writeFixed32(t){this.realloc(4),this.dataView.setInt32(this.pos,t,!0),this.pos+=4}writeSFixed32(t){this.realloc(4),this.dataView.setInt32(this.pos,t,!0),this.pos+=4}
vendor: 4,393 bytes, line 1
1writeFixed64(t){this.realloc(8),this.dataView.setInt32(this.pos,-1&t,!0),this.dataView.setInt32(this.pos+4,Math.floor(t*x),!0),this.pos+=8}writeSFixed64(t){this.realloc(8),this.dataView.setInt32(this.pos,-1&t,!0),this.dataView.setInt32(this.pos+4,Math.floor(t*x),!0),this.pos+=8}writeVarint(t){(t=+t||0)>268435455||t<0?function(t,i){let e,s;if(t>=0?(e=t%4294967296|0,s=t/4294967296|0):(e=~(-t%4294967296),s=~(-t/4294967296),4294967295^e?e=e+1|0:(e=0,s=s+1|0)),t>=0x10000000000000000||t<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");i.realloc(10),function(t,i,e){e.buf[e.pos++]=127&t|128,t>>>=7,e.buf[e.pos++]=127&t|128,t>>>=7,e.buf[e.pos++]=127&t|128,t>>>=7,e.buf[e.pos++]=127&t|128,t>>>=7,e.buf[e.pos]=127&t}(e,0,i),function(t,i){const e=(7&t)<<4;i.buf[i.pos++]|=e|((t>>>=3)?128:0),t&&(i.buf[i.pos++]=127&t|((t>>>=7)?128:0),t&&(i.buf[i.pos++]=127&t|((t>>>=7)?128:0),t&&(i.buf[i.pos++]=127&t|((t>>>=7)?128:0),t&&(i.buf[i.pos++]=127&t|((t>>>=7)?128:0),t&&(i.buf[i.pos++]=127&t)))))}(s,i)}(t,this):(this.realloc(4),this.buf[this.pos++]=127&t|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=t>>>7&127))))}writeSVarint(t){this.writeVarint(t<0?2*-t-1:2*t)}writeBoolean(t){this.writeVarint(+t)}writeString(t){t=String(t),this.realloc(4*t.length),this.pos++;const i=this.pos;this.pos=function(t,i,e){for(let s,n,r=0;r<i.length;r++){if(s=i.charCodeAt(r),s>55295&&s<57344){if(!n){s>56319||r+1===i.length?(t[e++]=239,t[e++]=191,t[e++]=189):n=s;continue}if(s<56320){t[e++]=239,t[e++]=191,t[e++]=189,n=s;continue}s=n-55296<<10|s-56320|65536,n=null}else n&&(t[e++]=239,t[e++]=191,t[e++]=189,n=null);s<128?t[e++]=s:(s<2048?t[e++]=s>>6|192:(s<65536?t[e++]=s>>12|224:(t[e++]=s>>18|240,t[e++]=s>>12&63|128),t[e++]=s>>6&63|128),t[e++]=63&s|128)}return e}(this.buf,t,this.pos);const e=this.pos-i;e>=128&&E(i,e,this),this.pos=i-1,this.writeVarint(e),this.pos+=e}writeFloat(t){this.realloc(4),this.dataView.setFloat32(this.pos,t,!0),this.pos+=4}writeDouble(t){this.realloc(8),this.dataView.setFloat64(this.pos,t,!0),this.pos+=8}writeBytes(t){const i=t.length;this.writeVarint(i),this.realloc(i);for(let e=0;e<i;e++)this.buf[this.pos++]=t[e]}writeRawMessage(t,i){this.pos++;const e=this.pos;t(i,this);const s=this.pos-e;s>=128&&E(e,s,this),this.pos=e-1,this.writeVarint(s),this.pos+=s}writeMessage(t,i,e){this.writeTag(t,2),this.writeRawMessage(i,e)}writePackedVarint(t,i){i.length&&this.writeMessage(t,R,i)}writePackedSVarint(t,i){i.length&&this.writeMessage(t,N,i)}writePackedBoolean(t,i){i.length&&this.writeMessage(t,I,i)}writePackedFloat(t,i){i.length&&this.writeMessage(t,B,i)}writePackedDouble(t,i){i.length&&this.writeMessage(t,U,i)}writePackedFixed32(t,i){i.length&&this.writeMessage(t,D,i)}writePackedSFixed32(t,i){i.length&&this.writeMessage(t,G,i)}writePackedFixed64(t,i){i.length&&this.writeMessage(t,_,i)}writePackedSFixed64(t,i){i.length&&this.writeMessage(t,z,i)}writeBytesField(t,i){this.writeTag(t,2),this.writeBytes(i)}writeFixed32Field(t,i){this.writeTag(t,5),this.writeFixed32(i)}writeSFixed32Field(t,i){this.writeTag(t,5),this.writeSFixed32(i)}writeFixed64Field(t,i){this.writeTag(t,1),this.writeFixed64(i)}writeSFixed64Field(t,i){this.writeTag(t,1),this.writeSFixed64(i)}writeVarintField(t,i){this.writeTag(t,0),this.writeVarint(i)}writeSVarintField(t,i){this.writeTag(t,0),this.writeSVarint(i)}writeStringField(t,i){this.writeTag(t,2),this.writeString(i)}writeFloatField(t,i){this.writeTag(t,5),this.writeFloat(i)}writeDoubleField(t,i){this.writeTag(t,1),this.writeDouble(i)}writeBooleanField(t,i){this.writeVarintField(t,+i)}}function P(t,i,e){return e?4294967296*i+(t>>>0):4294967296*(i>>>0)+(t>>>0)}function E(t,i,e){const s=i<=16383?1:i<=2097151?2:i<=268435455?3:Math.floor(Math.log(i)/(7*Math.LN2));e.realloc(s);for(let n=e.pos-1;n>=t;n--)e.buf[n+s]=e.buf[n]}function R(t,i){for(let e=0;e<t.length;e++)i.writeVarint(t[e])}function N(t,i){for(let e=0;e<t.length;e++)i.writeSVarint(t[e])}function B(t,i){for(let e=0;e<t.length;e++)i.writeFloat(t[e])}function U(t,i){for(let e=0;e<t.length;e++)i.writeDouble(t[e])}function I(t,i){for(let e=0;e<t.length;e++)i.writeBoolean(t[e])}function D(t,i){for(let e=0;e<t.length;e++)i.writeFixed32(t[e])}function G(t,i){for(let e=0;e<t.length;e++)i.writeSFixed32(t[e])}function _(t,i){for(let e=0;e<t.length;
1e++)i.writeFixed64(t[e])}function z(t,i){for(let e=0;e<t.length;e++)i.writeSFixed64(t[e])}var j,H;function W(t,i){if(!i)throw new Error("pbf undefined");i.writeVarintField(15,2),i.writeStringField(1,t.id||""),i.writeVarintField(5,t.extent||4096);const e={keys:[],values:[],keycache:{},valuecache:{}};for(const s of t.features)e.feature=s,i.writeMessage(2,V,e);for(const s of e.keys)i.writeStringField(3,s);for(const s of e.values)i.writeMessage(4,J,s)}function V(t,i){const e=t.feature;if(!e||!i)throw new Error;i.writeMessage(2,K,t),i.writeVarintField(3,e.type),i.writeMessage(4,Y,e)}function K(t,i){const e=t.feature;if(!e||!i)throw new Error;const s=t.keys,n=t.values,r=t.keycache,o=t.valuecache;for(const a in e.properties){let t=e.properties[a],h=r[a];if(null===t)continue;void 0===h&&(s.push(a),h=s.length-1,r[a]=h),i.writeVarint(h);const l=typeof t;"string"!==l&&"boolean"!==l&&"number"!==l&&(t=JSON.stringify(t));const c=`${l}:${t}`;let u=o[c];void 0===u&&(n.push(t),u=n.length-1,o[c]=u),i.writeVarint(u)}}function Z(t,i){return(i<<3)+(7&t)}function q(t){return t<<1^t>>31}function Y(t,i){if(!i)throw new Error;const e=t.geometry,s=t.type;let n=0,r=0;for(const o of e){let t=1;s===j.POINT&&(t=o.length/2),i.writeVarint(Z(1,t));const e=o.length/2,a=s===j.POLYGON?e-1:e;for(let h=0;h<a;h++){1===h&&1!==s&&i.writeVarint(Z(2,a-1));const t=o[2*h]-n,e=o[2*h+1]-r;i.writeVarint(q(t)),i.writeVarint(q(e)),n+=t,r+=e}s===j.POLYGON&&i.writeVarint(Z(7,1))}}function J(t,i){if(!i)throw new Error;"string"==typeof t?i.writeStringField(1,t):"boolean"==typeof t?i.writeBooleanField(7,t):"number"==typeof t&&(t%1!=0?
1i.writeDoubleField(3,t):t<0?i.writeSVarintField(6,t):i.writeVarintField(5,t))}(H=j||(j={}))[H.UNKNOWN=0]="UNKNOWN",H[H.POINT=1]="POINT",H[H.LINESTRING=2]="LINESTRING",H[H.POLYGON=3]="POLYGON";const X="undefined"!=typeof performance?performance:void 0,Q=X?X.timeOrigin||(new Date).getTime()-X.now():(new Date).getTime();function tt(t){var i;return JSON.parse(JSON.stringify((null===(i=null==X?void 0:X.getEntriesByName)||void 0===i?void 0:i.call(X,t))||[]))}function it(){return X?X.now():(new Date).getTime()}function et(t){const i=[];for(const e of t)i.push(...e);return i}class st{constructor(t){this.marks={},this.urls=[],this.fetched=[],this.resources=[],this.tilesFetched=0,this.timeOrigin=Q,this.finish=t=>{this.markFinish();const i=t=>{const i=this.marks[t]||[],e=Math.max(...i.map(t=>Math.max(...t))),s=Math.min(...i.map(t=>Math.min(...t)));return Number.isFinite(e)?e-s:void 0},e=i("main")||0,s=i("fetch"),n=i("decode"),r=i("isoline");return{url:t,tilesUsed:this.tilesFetched,origin:this.timeOrigin,marks:this.marks,resources:[...this.resources,...et(this.fetched.map(tt))],duration:e,fetch:s,decode:n,process:r,wait:e-(s||0)-(n||0)-(r||0)}},this.error=t=>Object.assign(Object.assign({},this.finish(t)),{error:!0}),this.marker=t=>{var i;this.marks[t]||(this.marks[t]=[]);const e=[it()];return null===(i=this.marks[t])||void 0===i||i.push(e),()=>e.push(it())},this.useTile=t=>{this.urls.indexOf(t)<0&&(this.urls.push(t),this.tilesFetched++)},this.fetchTile=t=>{this.fetched.indexOf(t)<0&&this.fetched.push(t)},this.addAll=t=>{var i;this.tilesFetched+=t.tilesUsed;const e=t.origin-this.timeOrigin;for(const s in t.marks){const n=s;(this.marks[n]||(this.marks[n]=[])).push(...(null===(i=t.marks[n])||void 0===i?void 0:i.map(t=>t.map(t=>t+e)))||[])}this.resources.push(...t.resources.map(t=>function(t,i){const e={};for(const s in t)0!==t[s]&&nt.test(s)?e[s]=Number(t[s])+i:e[s]=t[s];return e}(t,e)))},this.markFinish=this.marker(t)}}const nt=/(Start$|End$|^start|^end)/,rt=(t,i)=>a(void 0,void 0,void 0,function*(){const e={signal:i.signal},s=yield fetch(t,e);if(!s.ok)throw new Error(`Bad response: ${s.status} for ${t}`);return{data:yield s.blob(),expires:s.headers.get("expires")||void 0,cacheControl:s.headers.get("cache-control")||void 0}});let ot=0;t.A=class{constructor(t,i,e=2e4){this.callbacks={},this.cancels={},this.dest=t,this.timeoutMs=e,this.dest.onmessage=t=>a(this,[t],void 0,function*({data:t}){const e=t;if("cancel"===e.type){const t=this.cancels[e.id];delete this.cancels[e.id],null==t||t.abort()}else if("response"===e.type){const t=this.callbacks[e.id];delete this.callbacks[e.id],t&&t(e.error?new Error(e.error):void 0,e.response,e.timings)}else if("request"===e.type){const t=new st("worker"),n=i[e.name],r=new AbortController,o=n.apply(n,[...e.args,r,t]),a=`${e.name}_${e.id}`;if(e.id&&o){this.cancels[e.id]=r;try{const i=yield o,s=null==i?void 0:i.transferrables;this.postMessage({id:e.id,type:"response",response:i,timings:t.finish(a)},s)}catch(s){this.postMessage({id:e.id,type:"response",error:(null==s?void 0:s.toString())||"error",timings:t.finish(a)})}delete this.cancels[e.id]}}})}postMessage(t,i){this.dest.postMessage(t,i||[])}send(t,i,e,s,...n){const r=++ot,o=new Promise((e,o)=>{this.postMessage({id:r,type:"request",name:t,args:n},i),this.callbacks[r]=(t,i,n)=>{null==s||s.addAll(n),t?o(t):e(i)}});return m(e,()=>{delete this.callbacks[r],this.postMessage({id:r,type:"cancel"})}),p(this.timeoutMs,o,e)}},t.H=O,t.L=class{constructor(t){this.loaded=Promise.resolve(),this.fetchAndParseTile=(t,i,e,s,n)=>{const r=this,o=this.demUrlPattern.replace("{z}",t.toString()).replace("{x}",i.toString()).replace("{y}",e.toString());return null==n||n.useTile(o),this.parsedCache.get(o,(s,o)=>a(this,void 0,void 0,function*(){const s=yield r.fetchTile(t,i,e,o,n);if(y(o))throw new Error("canceled");const a=r.decodeImage(s.data,r.encoding,o),h=null==n?void 0:n.marker("decode"),l=yield a;return null==h||h(),l}),s)},this.tileCache=new S(t.cacheSize),this.parsedCache=new S(t.cacheSize),this.contourCache=new S(t.cacheSize),this.timeoutMs=t.timeoutMs,this.demUrlPattern=t.demUrlPattern,this.encoding=t.encoding,this.maxzoom=t.maxzoom,this.decodeImage=t.decodeImage||L,this.getTile=t.getTile||rt}fetchTile(t,i,e,s,n){const r=this.demUrlPattern.replace("{z}",t.toString()).replace("{x}
1",i.toString()).replace("{y}",e.toString());return null==n||n.useTile(r),this.tileCache.get(r,(t,i)=>{null==n||n.fetchTile(r);const e=null==n?void 0:n.marker("fetch");return p(this.timeoutMs,this.getTile(r,i).finally(()=>null==e?void 0:e()),i)},s)}fetchDem(t,i,e,s,n,r){return a(this,void 0,void 0,function*(){const o=Math.min(t-(s.overzoom||0),this.maxzoom),a=t-o,h=1<<a,l=Math.floor(i/h),c=Math.floor(e/h),u=yield this.fetchAndParseTile(o,l,c,n,r);return O.fromRawDem(u).split(a,i%h,e%h)})}fetchContourTile(t,i,e,s,n,o){const{levels:h,multiplier:l=1,buffer:u=1,extent:d=4096,contourLayer:f="contours",elevationKey:p="ele",levelKey:m="level",subsampleBelow:w=100}=s;if(!h||0===h.length)return Promise.resolve({arrayBuffer:new ArrayBuffer(0)});const v=[t,i,e,c(s)].join("/");return this.contourCache.get(v,(n,c)=>a(this,void 0,void 0,function*(){const n=1<<t,a=[];for(let r=e-1;r<=e+1;r++)for(let e=i-1;e<=i+1;e++)a.push(r<0||r>=n?void 0:this.fetchDem(t,(e+n)%n,r,s,c,o));const v=yield Promise.all(a);let g=O.combineNeighbors(v);if(!g||y(c))return{arrayBuffer:(new Uint8Array).buffer};const b=null==o?void 0:o.marker("isoline");if(g.width>=w)g=g.materialize(2);else for(;g.width<w;)g=g.subsamplePixelCenters(2).materialize(2);g=g.averagePixelCentersToGrid().scaleElevation(l).materialize(1);const M=r(h[0],g,d,u);null==b||b();const S=function(t){const i=new T;for(const e in t.layers){const s=t.layers[e];s.extent||(s.extent=t.extent),i.writeMessage(3,W,Object.assign(Object.assign({},s),{id:e}))}return i.finish()}({extent:d,layers:{[f]:{features:Object.entries(M).map(([t,i])=>{const e=Number(t);return{type:j.LINESTRING,geometry:i,properties:{[p]:e,[m]:Math.max(...h.map((t,i)=>e%t===0?i:0))}}})}}});return null==b||b(),{arrayBuffer:S.buffer}}),n)}},t.T=st,t.i=a,t.a=function(t){return Object.fromEntries(t.replace(/^.*\?/,"").split("&").map(t=>{const i=t.split("=").map(decodeURIComponent),e=i[0];let s=i[1];switch(e){case"thresholds":n=s,s=Object.fromEntries(n.split("~").map(t=>t.split("*").map(Number)).map(([t,...i])=>[t,i]));break;case"extent":case"multiplier":case"overzoom":case"buffer":s=Number(s)}var n;return[e,s]}))},t.b=r,t.c=F,t.d=L,t.e=function(t){var{thresholds:i}=t,e=o(t,["thresholds"]);return h(Object.assign({thresholds:l(i)},e)).map(([t,i])=>`${encodeURIComponent(t)}=${encodeURIComponent(i)}`).join("&")},t.f=function(t){return t.then(({arrayBuffer:t})=>{const i=function(t){const i=new ArrayBuffer(t.byteLength);return new Uint8Array(i).set(new Uint8Array(t)),i}(t);return{arrayBuffer:i,transferrables:[i]}})},t.g=function(t,i){const{thresholds:e}=t,s=o(t,["thresholds"]);let n=[],r=-1/0;return Object.entries(e).forEach(([t,e])=>{const s=Number(t);s<=i&&s>r&&(r=s,n="number"==typeof e?[e]:e)}),Object.assign({levels:n},s)},t.p=function(t,i){return t.then(t=>{var{data:e}=t,s=o(t,["data"]);let n=e;return i&&(n=new Float32Array(e.length),n.set(e)),Object.assign(Object.assign({},s),{data:n,transferrables:[n.buffer]})})}}),gt(0,function(t){const i=t=>Promise.reject(new Error(`No manager registered for ${t}`)),e="undefined"!=typeof self?self:"undefined"!=typeof window?window:global;e.actor=new t.A(e,new class{constructor(){this.managers={},this.init=(i,e)=>(this.managers[i.managerId]=new t.L(i),Promise.resolve()),this.fetchTile=(t,e,s,n,r,o)=>{var a;return(null===(a=this.managers[t])||void 0===a?void 0:a.fetchTile(e,s,n,r,o))||i(t)},this.fetchAndParseTile=(e,s,n,r,o,a)=>{var h;return t.p((null===(h=this.managers[e])||void 0===h?void 0:h.fetchAndParseTile(s,n,r,o,a))||i(e),!0)},this.fetchContourTile=(e,s,n,r,o,a,h)=>{var l;return t.f((null===(l=this.managers[e])||void 0===l?void 0:l.fetchContourTile(s,n,r,o,a,h))||i(e))}}})}),gt(0,function(t){const i={workerUrl:""};let e,s=0;class n{constructor(){this.decodeImage=(i,e,s)=>t.p(t.d(i,e,s),!1)}}
1class r{constructor(r){this.fetchTile=(t,i,e,s,n)=>this.actor.send("fetchTile",[],s,n,this.managerId,t,i,e),this.fetchAndParseTile=(t,i,e,s,n)=>this.actor.send("fetchAndParseTile",[],s,n,this.managerId,t,i,e),this.fetchContourTile=(t,i,e,s,n,r)=>this.actor.send("fetchContourTile",[],n,r,this.managerId,t,i,e,s);const o=this.managerId=++s;this.actor=r.actor||function(){if(!e){const s=new Worker(i.workerUrl),r=new n;e=new t.A(s,r)}return e}(),this.loaded=this.actor.send("init",[],new AbortController,void 0,Object.assign(Object.assign({},r),{managerId:o}))}}Blob.prototype.arrayBuffer||(Blob.prototype.arrayBuffer=function(){return new Promise((t,i)=>{const e=new FileReader;e.onload=i=>{var e;return t(null===(e=i.target)||void 0===e?void 0:e.result)},e.onerror=i,e.readAsArrayBuffer(this)})});const o=t=>(i,e)=>{if(e instanceof AbortController)return t(i,e);{const s=new AbortController;return t(i,s).then(t=>e(void 0,t.data,t.cacheControl,t.expires),t=>e(t)).catch(t=>e(t)),{cancel:()=>s.abort()}}},a=new Set;return{generateIsolines:t.b,DemSource:class{constructor({url:i,cacheSize:e=100,id:s="dem",encoding:n="terrarium",maxzoom:h=12,worker:l=!0,timeoutMs:c=1e4,actor:u}){this.timingCallbacks=[],this.onTiming=t=>{this.timingCallbacks.push(t)},this.setupMaplibre=t=>{t.addProtocol(this.sharedDemProtocolId,this.sharedDemProtocol),t.addProtocol(this.contourProtocolId,this.contourProtocol)},this.sharedDemProtocolV4=(i,e)=>t.i(this,void 0,void 0,function*(){const[s,n,r]=this.parseUrl(i.url),o=new t.T("main");let a;try{const t=yield this.manager.fetchTile(s,n,r,e,o);return a=o.finish(i.url),{data:yield t.data.arrayBuffer(),cacheControl:t.cacheControl,expires:t.expires}}catch(h){throw a=o.error(i.url),h}finally{this.timingCallbacks.forEach(t=>t(a))}}),this.contourProtocolV4=(i,e)=>t.i(this,void 0,void 0,function*(){const s=new t.T("main");let n;try{const[r,o,a]=this.parseUrl(i.url),h=t.a(i.url),l=yield this.manager.fetchContourTile(r,o,a,t.g(h,r),e,s);return n=s.finish(i.url),{data:l.arrayBuffer}}catch(r){throw n=s.error(i.url),r}finally{this.timingCallbacks.forEach(t=>t(n))}}),this.contourProtocol=o(this.contourProtocolV4),this.sharedDemProtocol=o(this.sharedDemProtocolV4),this.contourProtocolUrl=i=>`${this.contourProtocolUrlBase}?${t.e(i)}`;let d=s,f=1;for(;a.has(d);)d=s+f++;a.add(d),this.sharedDemProtocolId=`${d}-shared`,this.contourProtocolId=`${d}-contour`,this.sharedDemProtocolUrl=`${this.sharedDemProtocolId}://{z}/{x}/{y}`,this.contourProtocolUrlBase=`${this.contourProtocolId}://{z}/{x}/{y}`;const p=l?r:t.L;this.manager=new p({demUrlPattern:i,cacheSize:e,encoding:n,maxzoom:h,timeoutMs:c,actor:u})}getDemTile(t,i,e,s){return this.manager.fetchAndParseTile(t,i,e,s||new AbortController)}parseUrl(t){const[,i,e,s]=/\/\/(\d+)\/(\d+)\/(\d+)/.exec(t)||[];return[Number(i),Number(e),Number(s)]}},HeightTile:t.H,LocalDemManager:t.L,decodeParsedImage:t.c,set workerUrl(t){i.workerUrl=t},get workerUrl(){return i.workerUrl}}});var bt=rt;let Mt=null;function St(){return Mt||(Mt=new bt.DemSource({url:k,encoding:A,maxzoom:x,worker:"undefined"!=typeof Worker,cacheSize:400,timeoutMs:1e4}),Mt.setupMaplibre(i)),Mt}async function Ct(t,i,e=16){const s=Math.min(Math.floor(e),x);if(s<0)return null;const n=Math.pow(2,s),r=(i+180)/360*n,o=(1-Math.log(Math.tan(t*Math.PI/180)+1/Math.cos(t*Math.PI/180))/Math.PI)/2*n,a=Math.floor(r),h=Math.floor(o);if(h<0||h>=n||a<0||a>=n)return null;let l;try{l=await St().getDemTile(s,a,h)}catch{return Ct(t,i,s-1)}const c=Math.min(Math.floor((r-a)*l.width),l.width-1),u=Math.min(Math.floor((o-h)*l.height),l.height-1),d=l.data[u*l.width+c];return void 0!==d&&Number.isFinite(d)?d:null}class Lt{map;container;coordinatesDisplay;altitudeDisplay;format;elevationUnit;lastElevationRequestTime=0;pendingElevationRequest=null;elevationRequestAnimationFrame=null;constructor(t="UTM",i="m"){this.format=t,this.elevationUnit=i}async requestElevation(t,i){if(this.altitudeDisplay&&this.map)try{const e=Math.min(Math.floor(this.map.getZoom()),x),s=await Ct(t,i,e);if(this.altitudeDisplay)if(null===s||isNaN(s))this.altitudeDisplay.textContent="Alt: —";else{let t,i;"ft"===this.elevationUnit?(t=f(s,"meters","feet"),i="ft"):(t=s,i="m"),this.altitudeDisplay.textContent=`Alt: ${Math.round(t)} ${i}`}}catch{this.altitudeDisplay&&(this.altitudeDisplay.textContent="Alt: —")}}onAdd(t){return this.map=t,this.container=document.createElement("div"),this.container.className="maplibregl-ctrl maplibregl-ctrl-group mouse-coordinates-ctrl",this.container.style.background="rgba(255, 255, 255, 0.9)",this.container.style.padding="5px 10px",this.container.style.fontFamily="monospace",this.container.style.fontSize="12px",this.container.style.borderRadius="4px",this.container.style.boxShadow="0 0 0 2px rgba(0, 0, 0, 0.1)",this.container.style.minWidth="200px",this.coordinatesDisplay=document.createElement("div"),this.coordinatesDisplay.textContent="—",this.container.appendChild(this.coordinatesDisplay),this.altitudeDisplay=document.createElement("div"),this.altitudeDisplay.textContent="Alt: —",this.altitudeDisplay.style.marginTop="2px",this.altitudeDisplay.style.color="#666",this.altitudeDisplay.style.fontSize="11px",this.container.appendChild(this.altitudeDisplay),this.map.on("mousemove",t=>{if(this.coordinatesDisplay&&this.altitudeDisplay){this.coordinatesDisplay.textContent=vt(t.lngLat.lat,t.lngLat.lng,this.format);const i=Date.now();i-this.lastElevationRequestTime>=100?(this.lastElevationRequestTime=i,this.requestElevation(t.lngLat.lat,t.lngLat.lng)):(this.pendingElevationRequest={lat:t.lngLat.lat,lng:t.lngLat.lng},null!==this.elevationRequestAnimationFrame&&cancelAnimationFrame(this.elevationRequestAnimationFrame),this.elevationRequestAnimationFrame=requestAnimationFrame(()=>{if(this.pendingElevationRequest){const{lat:t,lng:i}=this.pendingElevationRequest;
1this.lastElevationRequestTime=Date.now(),this.requestElevation(t,i),this.pendingElevationRequest=null}this.elevationRequestAnimationFrame=null}))}}),this.map.on("mouseout",()=>{this.coordinatesDisplay&&this.altitudeDisplay&&(null!==this.elevationRequestAnimationFrame&&(cancelAnimationFrame(this.elevationRequestAnimationFrame),this.elevationRequestAnimationFrame=null),this.pendingElevationRequest=null,this.coordinatesDisplay.textContent="—",this.altitudeDisplay.textContent="Alt: —")}),this.container}onRemove(){null!==this.elevationRequestAnimationFrame&&(cancelAnimationFrame(this.elevationRequestAnimationFrame),this.elevationRequestAnimationFrame=null),this.pendingElevationRequest=null,this.container&&this.container.parentNode&&this.container.parentNode.removeChild(this.container),this.map=void 0,this.container=void 0,this.coordinatesDisplay=void 0,this.altitudeDisplay=void 0}}class $t{constructor(t=()=>[]){this.getBaseLayerIds=t}map;container;innerContainer;onAdd(t){return this.map=t,this.container=document.createElement("div"),this.container.className="maplibregl-ctrl maplibregl-ctrl-attrib",this.container.setAttribute("role","region"),this.container.setAttribute("aria-label","Attributions de la carte"),this.innerContainer=document.createElement("div"),this.innerContainer.className="maplibregl-ctrl-attrib-inner",this.container.appendChild(this.innerContainer),this.map.on("styledata",()=>this.updateAttributions()),this.map.on("sourcedata",()=>this.updateAttributions()),this.updateAttributions(),this.container}onRemove(){this.container&&this.container.parentNode&&this.container.parentNode.removeChild(this.container),this.map=void 0}updateAttributions(){if(!this.map||!this.innerContainer)return;const t=new Set,i=this.map.getStyle();if(i&&i.layers&&i.sources)for(const e of this.getBaseLayerIds()){const s=i.layers.find(t=>t.id===e);if(!s||!("source"in s))continue;if("visible"!==s.layout?.visibility&&s.layout?.visibility)continue;const n=i.sources[s.source];if(n&&"object"==typeof n&&"attribution"in n){const i=n.attribution;i&&t.add(i)}}t.size>0?(this.innerContainer.innerHTML=Array.from(t).join(" | "),this.container&&(this.container.style.display="")):this.container&&(this.container.style.display="none")}}class Ft{constructor(t,i){this.adapter=t,this.tracker=i}map=null;scaleControl=null;mouseCoordinatesControl=null;toggle3DControl=null;attributionControl=null;initializeControls(t,e,s,n,r,o,a,h){this.map=t,e&&(this.map.addControl(new i.FullscreenControl(h?{container:h}:void 0),"top-right"),this.map.addControl(new i.NavigationControl({showCompass:s,visualizePitch:n}),"top-right"),this.addToggle3DControl(),this.scaleControl=new i.ScaleControl({maxWidth:100,unit:"metric"}),this.map.addControl(this.scaleControl,"bottom-left"),r&&(this.mouseCoordinatesControl=new Lt(o,a),this.map.addControl(this.mouseCoordinatesControl,"top-left")),this.attributionControl=new $t(()=>this.adapter.getCurrentBaseLayerIds()),this.map.addControl(this.attributionControl,"bottom-right"))}addToggle3DControl(){if(!this.map)return;const t=new class{map;container;button;is3D=!1;adapter;tracker;constructor(t,i){this.adapter=t,this.tracker=i}updateButtonState(t){this.is3D=t,this.button&&(t?(this.button.innerHTML="2D",this.button.title=Q("controls.toggle2D"),this.button.style.backgroundColor="#3498db",this.button.style.color="white"):(this.button.innerHTML="3D",this.button.title=Q("controls.toggle3D"),this.button.style.backgroundColor="",this.button.style.color=""))}onAdd(t){return this.map=t,this.container=document.createElement("div"),this.container.className="maplibregl-ctrl maplibregl-ctrl-group",this.button=document.createElement("button"),this.button.className="maplibregl-ctrl-icon",this.button.type="button",this.button.title=Q("controls.toggle3D"),this.button.innerHTML="3D",this.button.style.fontWeight="bold",this.button.style.fontSize="12px",this.button.addEventListener("click",()=>{if(this.map)if(this.is3D=!this.is3D,this.is3D){this.tracker.trackEvent("3D View","Toggle 3D mode","3D"),this.adapter.enable3DTerrain().catch(()=>{});const t=this.adapter.currentTrailPoints;t&&t.length>0?this.map.once("styledata",()=>{this.map&&this.adapter.centerOnTrailWithOptimalView(50,0,1500)}):this.map.once("styledata",()=>{this.map&&this.map.easeTo({pitch:50,duration:1e3})}),this.button&&(this.button.innerHTML="2D",this.button.title=Q("controls.toggle2D"),this.button.style.backgroundColor="#3498db",this.button.style.color="white"),this.hideScaleControl()}else this.button&&(this.button.innerHTML="3D",this.button.title=Q("controls.toggle3D"),this.button.style.backgroundColor="",this.button.style.color=""),this.adapter.disable3DTerrain().catch(()=>{}),this.tracker.trackEvent("3D View","Toggle 3D mode","2D"),this.map.once("styledata",()=>{const t=this.adapter.currentTrailBounds,i=this.adapter.fitBoundsPadding;t?this.adapter.fitBounds(t.southwest,t.northeast,i,0,0):this.map?.easeTo({pitch:0,bearing:0,duration:1e3})}),this.showScaleControl()}),this.container.appendChild(this.button),this.container}hideScaleControl(){const t=this.adapter.scaleControl;if(t&&this.map){const i=t.o;i&&(i.style.display="none")}}showScaleControl(){const t=this.adapter.scaleControl;if(t&&this.map){const i=t.o;i&&(i.style.display="block")}}onRemove(){this.container&&this.container.parentNode&&this.container.parentNode.removeChild(this.container),this.map=void 0}}(this.adapter,this.tracker);
1this.toggle3DControl=t,this.map.addControl(t,"top-right")}getToggle3DControl(){return this.toggle3DControl}getScaleControl(){return this.scaleControl}hideScaleControl(){if(this.scaleControl){const t=this.scaleControl.o;t&&(t.style.display="none")}}setupFullscreenTracking(){document.addEventListener("fullscreenchange",()=>{if(!this.map)return;const t=!!document.fullscreenElement;this.tracker.trackEvent("Fullscreen","Toggle fullscreen",t?"Enter fullscreen":"Exit fullscreen")})}}class Ot{constructor(t){this.map=t}currentTrailBounds=null;currentTrailPoints=null;fitBoundsPadding=50;isManualModeSwitch=!1;setMap(t){this.map=t}setCenter(t,i){if(!this.map)throw new Error("Map is not initialized");const e=void 0!==i?{center:this.coordinatesToLngLat(t),zoom:i}:void 0;e?this.map.jumpTo(e):this.map.setCenter(this.coordinatesToLngLat(t))}fitBounds(t,i,e=50,s,n){if(!this.map)throw new Error("Map is not initialized");this.currentTrailBounds={southwest:t,northeast:i},this.fitBoundsPadding=e;const r={padding:e,duration:1e3};if(void 0!==s){const t=Math.min(85,Math.max(0,s));if(r.pitch=t,t>0){const i=150*Math.pow(t/85,1);r.offset=[0,i],r.linear=!0}}void 0!==n&&(r.bearing=n%360),this.map.fitBounds([this.coordinatesToLngLat(t),this.coordinatesToLngLat(i)],r)}centerOnTrailWithOptimalView(t=50,i=0,e=1500){if(!this.map)throw new Error("Map is not initialized");if(!this.currentTrailPoints||0===this.currentTrailPoints.length)return;const s=this.isManualModeSwitch;this.isManualModeSwitch=!0;const n=this.currentTrailPoints,r=n.reduce((t,i)=>t+i[0],0)/n.length,o=n.reduce((t,i)=>t+i[1],0)/n.length,a=n.map(t=>t[0]),h=n.map(t=>t[1]),l=Math.max(...a)-Math.min(...a),c=Math.max(...h)-Math.min(...h),u=
1Math.max(l,c);let d;d=u<.001?15:u<.01?14:u<.05||u<.1?13:u<.5?12:11;const f=d-t/90*1.2;this.map.easeTo({center:[r,o],zoom:f,pitch:t,bearing:i,duration:e}),setTimeout(()=>{this.isManualModeSwitch=s},e+100)}setTrailPoints(t){this.currentTrailPoints=t}getCurrentTrailBounds(){return this.currentTrailBounds}getCurrentTrailPoints(){return this.currentTrailPoints}getFitBoundsPadding(){return this.fitBoundsPadding}coordinatesToLngLat(t){return[t.lng,t.lat]}}const kt="diplomat";function xt(t){let i=new URLSearchParams(t.hash.substr(1)).get("language");return""===i?null:i}function At(t){return t.variants??t.minimize().baseName.match(/-([-\w]+)/)?.[1]}function Tt(){let t=xt(window.location)?.split(","),i=(t??navigator.languages??[navigator.language]).flatMap(t=>function(t){let i;try{i=new Intl.Locale(t)}catch{return[]}let e=i.maximize(),s=(n=[e.script,e.region,At(e),e.numberingSystem].filter(t=>t),n.reduce((t,i)=>[...t,...t.map(t=>[...t,i])],[[]])).map(t=>[e.language,...t].join("-"));var n;s.push(i+""),s.push(i.baseName);let r=s.map(t=>{try{return new Intl.Locale(t)}catch{}}).filter(t=>t),o=t=>{let i=t+"",e=0;return e+=i.length??0,e+=i.split("-").length??0,e+=At(t)?.length??0,e+=i.match(/(?:-[tx]-|-u-\w\w-)\w+/)?.[0]?.length??0,e};r.sort((t,i)=>o(i)-o(t));let a=r.map(t=>t+"");
1return[...new Set(a)]}(t));return[...new Set(i)]}const Pt="name";function Et(t,i={}){return["coalesce",...[...t.flatMap(t=>{let e=(i.localizedNamePropertyFormat||"name:$1").replaceAll("$1",t),s=[e];return!i.includesLegacyFields||"de"!==t&&"en"!==t||s.push(e.replaceAll(":","_")),s}),i.unlocalizedNameProperty||Pt].map(t=>["get",t])]}function Rt(t,i,e){if(!t||"let"!==t[0])return;let s=t.indexOf(i);s%2==1?t[s+1]=e:t.splice(-1,0,i,e)}const Nt=`${kt}__localizedName`,Bt=`${kt}__localizedCollator`,Ut=`${kt}__diacriticInsensitiveCollator`;function It(t,i,e){if(!Array.isArray(t)||"literal"===t[0])return;if("get"===t[0])return 2===t.length&&t[1]===i?e:void 0;let s=!1;return t.forEach((n,r)=>{if(!r)return;let o=It(n,i,e);void 0!==o&&(t[r]=o,s=!0)}),s?t:void 0}function Dt(t,i,e){let s=t.layout&&t.layout["text-field"];if(!s||"let"===s[0]&&s.includes(Nt))return;let n=t.layout&&t.layout["symbol-placement"],r=It(s,i||Pt,e?qt:"line"===n||"line-center"===n?Wt:jt);void 0!==r&&(t.layout["text-field"]=["let",Nt,"",r])}function Gt(t,i,e,s){if(!("layout"in t)||!("text-field"in t.layout))return;let n=t.layout["text-field"];Rt(n,Nt,"transportation_name"===t["source-layer"]?s:e),Rt(n,Bt,["collator",{"case-sensitive":!1,"diacritic-sensitive":!0,locale:i}]),Rt(n,Ut,["collator",{"case-sensitive":!1,"diacritic-sensitive":!/^en\b/.test(i),locale:i}])}function _t(t,i=Tt(),e={}){let s=Et(i,e),n=Et(i,{...e,includesLegacyFields:!0});for(let r of t)Gt(r,i[0],s,n)}function zt(t,i,e){let s=`${kt}__values`,n=`${kt}__omissionIndex`,r=`${kt}__abridgedValues`;return["let",s,["split",["join",["split",["join",["split",t,";;"],"‘’"],"; "],";"],";"],["let",n,e?["index-of",e,["var",s]]:-1,["let",r,["match",["var",n],-1,["join",["var",s],i],["concat",["join",["slice",["var",s],0,["var",n]],i],["case",["any",["==",["var",n],0],["==",["var",n],["-",["length",["var",s]],1]]],"",i],["join",["slice",["var",s],["+",["var",n],1]],i]]],["join",["split",["var",r],"‘’"],";"]]]]}const jt=zt(["var",Nt],"\n"),Ht=["let",Nt,"",jt],Wt=zt(["var",Nt]," • "),Vt=["let",Nt,"",Wt],Kt=`${kt}__localizedNameList`,Zt=`${kt}__nameList`,qt=["let",Kt,zt(["var",Nt],"\n"),["case",["==",["var",Nt],["get","name"],["var",Bt]],["format",["var",Kt]],["let",Zt,zt(["get","name"],"\n"),["case",(Yt=["var",Nt],Jt=["get","name"],Xt=["var",Ut],["all",["==",["slice",Yt,0,["length",Jt]],Jt,Xt],["in",["slice",["concat",Yt," ,"[0]],["length",Jt],["+",["length",Jt],1]]," ,"]]),["format",function(t,i){return["concat",i,["slice",t,["length",i]]]}(["var",Nt],["var",Zt])],function(t,i,e){let s=`${kt}__suffixStart`;return["let",s,["-",["length",t],["length",i]],["all",["==",["slice",t,["var",s]],i,e],["==",["slice",t,["-",["var",s],1],["var",s]]," "]]]}(["var",Nt],["get","name"],["var",Ut]),["format",function(t,i){return["concat",["slice",t,0,["-",["length",t],["length",i]]],i]}(["var",Nt],["var",Zt])],["format",["var",Kt],"\n","(⁨",{"font-scale":.8},zt(["get","name"]," • ",["var",Nt]),{"font-scale":.8},"⁩)",{"font-scale":.8}]]]]];var Yt,Jt,Xt;const Qt=["let",Nt,"",Bt,["collator",{}],Ut,["collator",{}],qt],ti={ABW:"AW",AFG:"AF",AGO:"AO",AIA:"AI",ALB:"AL",AND:"AD",ARE:"AE",ARG:"AR",ARM:"AM",ASM:"AS",ATA:"AQ",ATF:"TF",ATG:"AG",AUS:"AU",AUT:"AT",AZE:"AZ",BDI:"BI",BEL:"BE",BEN:"BJ",BFA:"BF",BGD:"BD",BGR:"BG",BHR:"BH",BHS:"BS",BIH:"BA",BLM:"BL",BLR:"BY",BLZ:"BZ",BMU:"BM",BOL:"BO",BRA:"BR",BRB:"BB",BRN:"BN",BTN:"BT",BVT:"BV",BWA:"BW",CAF:"CF",CAN:"CA",CCK:"CC",CHE:"CH",CHL:"CL",CHN:"CN",CIV:"CI",CMR:"CM",COD:"CD",COG:"CG",COK:"CK",COL:"CO",COM:"KM",CPV:"CV",CRI:"CR",CUB:"CU",CUW:"CW",CXR:"CX",CYM:"KY",CYP:"CY",CZE:"CZ",DEU:"DE",DJI:"DJ",DMA:"DM",DNK:"DK",DOM:"DO",DZA:"DZ",ECU:"EC",EGY:"EG",ERI:"ER",ESH:"EH",ESP:"ES",EST:"EE",ETH:"ET",FIN:"FI",FJI:"FJ",FLK:"FK",FRA:"FR",FRO:"FO",FSM:"FM",FXX:"FX",GAB:"GA",GBR:"GB",GEO:"GE",GGY:"GG",GHA:"GH",GIB:"GI",GIN:"GN",GLP:"GP",GMB:"GM",GNB:"GW",GNQ:"GQ",GRC:"GR",GRD:"GD",GRL:"GL",GTM:"GT",GUF:"GF",GUM:"GU",GUY:"GY",HKG:"HK",HMD:"HM",HND:"HN",HRV:"HR",HTI:"HT",HUN:"HU",IDN:"ID",IMN:"IM",IND:"IN",IOT:"IO",IRL:"IE",IRN:"IR",IRQ:"IQ",ISL:"IS",ISR:"IL",ITA:"IT",JAM:"JM",JEY:"JE",JOR:"JO",JPN:"JP",KAZ:"KZ",KEN:"KE",KGZ:"KG",KHM:"KH",KIR:"KI",KNA:"KN",KOR:"KR",KWT:"KW",LAO:"LA",LBN:"LB",LBR:"LR",LBY:"LY",LCA:"LC",LIE:"LI",LKA:"LK",LSO:"LS",LTU:"LT",LUX:"LU",LVA:"LV",MAC:"MO",MAF:"MF",MAR:"MA",MCO:"MC",MDA:"MD",MDG:"MG",MDV:"MV",MEX:"MX",MHL:"MH",MKD:"MK",MLI:"ML",MLT:"MT",MMR:"MM",MNE:"ME",MNG:"MN",MNP:"MP",MOZ:"MZ",MRT:"MR",MSR:"MS",MTQ:"MQ",MUS:"MU",MWI:"MW",MYS:"MY",MYT:"YT",NAM:"NA",NCL:"NC",NER:"NE",NFK:"NF",NGA:"NG",NIC:"NI",NIU:"NU",NLD:"NL",NOR:"NO",NPL:"NP",NRU:"NR",NZL:"NZ",OMN:"OM",PAK:"PK",PAN:"PA",PCN:"PN",PER:"PE",PHL:"PH",PLW:"PW",PNG:"PG",POL:"PL",PRI:"PR",PRK:"KP",PRT:"PT",PRY:"PY",PSE:"PS",PYF:"PF",QAT:"QA",REU:"RE",ROU:"RO",RUS:"RU",RWA:"RW",SAU:"SA",SDN:"SD",SEN:"SN",SGP:"SG",SGS:"GS",SHN:"SH",SJM:"SJ",SLB:"SB",SLE:"SL",SLV:"SV",SMR:"SM",SOM:"SO",SPM:"PM",SRB:"RS",SSD:"SS",STP:"ST",SUR:"SR",SVK:"SK",SVN:"SI",SWE:"SE",SWZ:"SZ",SXM:"SX",SYC:"SC",SYR:"SY",TCA:"TC",TCD:"TD",TGO:"TG",THA:"TH",TJK:"TJ",TKL:"TK",TKM:"TM",TLS:"TL",TON:"TO",TTO:"TT",TUN:"TN",TUR:"TR",TUV:"TV",TWN:"TW",TZA:"TZ",UGA:"UG",UKR:"UA",UMI:"UM",URY:"UY",USA:"US",UZB:"UZ",VAT:"VA",VCT:"
1VC",VEN:"VE",VGB:"VG",VIR:"VI",VNM:"VN",VUT:"VU",WLF:"WF",WSM:"WS",YEM:"YE",ZAF:"ZA",ZMB:"ZM",ZWE:"ZW"},ii=`${kt}__countryNamesByCode`;function ei(t,i={}){let e=new Intl.DisplayNames(t,{type:"region",fallback:"none"});return Object.fromEntries(Object.entries(ti).map(s=>{let n=e.of(s[1]);return n&&i?.uppercase&&(n=n.toLocaleUpperCase(t).replaceAll(" ","  ")),[s[0],n]}))}function si(t,i={}){let e={};return e[ii]=ei(t,{uppercase:i?.uppercaseCountryNames}),e}function ni(t,i=Tt(),e={}){let s=t.getStyle(),n=Et(i,e),r=Et(i,{...e,includesLegacyFields:!0});for(let a of s.layers){let t=a["source-layer"];(!e.layers&&!e.sourceLayers||e.layers?.includes(a.id)||t&&e.sourceLayers?.includes(t))&&Dt(a,e?.unlocalizedNameProperty,e?.glossLocalNames),Gt(a,i[0],n,r)}let o=ei(i,{uppercase:e?.uppercaseCountryNames});t.setGlobalStateProperty(ii,o),t.setStyle(s)}function ri(t){return{sources:Object.keys(t.sources??{}),layers:(t.layers??[]).map(t=>t.id)}}"undefined"!=typeof window&&(window.Diplomat={getGlobalStateForLocalization:si,getLanguageFromURL:xt,getLocales:Tt,getLocalizedCountryNameExpression:function(t){return["let","code",t,["coalesce",["get",["var","code"],["coalesce",["global-state",ii],["literal",{}]]],["concat","(",["var","code"],")"]]]},listValuesExpression:zt,localizeLayers:_t,localizeStyle:ni,localizedName:Ht,localizedNameInline:Vt,localizedNameWithLocalGloss:Qt},"maplibregl"in window&&(maplibregl.Diplomat=window.Diplomat,maplibregl.Map.prototype.localizeStyle=function(t=Tt(),i={}){ni(this,t,i)}));class oi{constructor(t){this.map=t}currentBaseLayer="IGNTOPO";fallbackGlyphs=null;baseFragmentResolver=null;injectedBase={};injectedOverlays={};setFallbackGlyphs(t){this.fallbackGlyphs=t}setBaseFragmentResolver(t){this.baseFragmentResolver=t}registerBaseFragment(t,i){this.injectedBase[t]=ri(i)}baseLayerIds(t){return(this.injectedBase[t]?.layers??[]).filter(t=>this.map?.getLayer(t))}getCurrentBaseLayerIds(){return this.baseLayerIds(this.currentBaseLayer)}setMap(t){this.map=t}setCurrentBaseLayer(t){this.currentBaseLayer=t}getCurrentBaseLayer(){return this.currentBaseLayer}firstNonBaseLayerId(){const t=this.map?.getStyle();if(!t?.layers)return;const i=new Set;for(const e of Object.values(this.injectedBase))for(const t of e.layers)i.add(t);return t.layers.find(t=>!i.has(t.id))?.id}localizeVectorMap(){if(!this.map)return;const t=new Set(this.baseLayerIds(this.currentBaseLayer)),i=(this.map.getStyle()?.layers??[]).filter(i=>t.has(i.id)&&"symbol"===i.type).map(t=>t.id);if(0===i.length)return;const e=tt(),s=this.map.getStyle()?.layers??[];for(const n of i){const t=s.find(t=>t.id===n);if(!t)continue;Dt(t),_t([t],[e]);const i=t.layout?.["text-field"];void 0!==i&&this.map.setLayoutProperty(n,"text-field",i)}for(const[n,r]of Object.entries(si([e])))this.map.setGlobalStateProperty(n,r)}async resolveBaseFragment(t){if(!this.baseFragmentResolver)throw new Error("No base fragment resolver configured");return this.baseFragmentResolver(t)}applyBaseFragment(t,i){if(!this.map)return;const e=this.map;e.setGlyphs(i.glyphs??this.fallbackGlyphs),e.setSprite("string"==typeof i.sprite?i.sprite:null);for(const[n,r]of Object.entries(i.sources??{}))e.getSource(n)||e.addSource(n,r);this.injectedBase[t]=ri(i);const s=this.firstNonBaseLayerId();for(const n of i.layers??[])e.getLayer(n.id)||e.addLayer(n,s),e.getLayer(n.id)&&e.setLayoutProperty(n.id,"visibility","visible")}removeBase(t){if(!this.map)return;const i=this.injectedBase[t];if(!i)return;for(const s of i.layers)this.map.getLayer(s)&&this.map.removeLayer(s);const e=this.map.getStyle();for(const s of i.sources){const t=e?.layers?.some(t=>t.source===s);!t&&this.map.getSource(s)&&this.map.removeSource(s)}delete this.injectedBase[t]}async changeBaseLayer(t){if(!this.map)throw new Error("Map is not initialized");if(this.currentBaseLayer===t)return;const i=this.currentBaseLayer;this.currentBaseLayer=t;try{const e=await this.resolveBaseFragment(t);this.removeBase(i),this.applyBaseFragment(t,e),this.localizeVectorMap()}catch(e){throw this.currentBaseLayer=i,e}}overlayBeforeId(){const t=this.map?.getStyle();if(!t?.layers)return;const i=t.layers.find(t=>"summits-labels"===t.id);if(i)return i.id;const e=t.layers.find(t=>
1t.id.startsWith("trail-outline-layer-")||t.id.startsWith("trail-layer-"));return e?.id}overlayLayerIds(t){return(this.injectedOverlays[t]?.layers??[]).filter(t=>this.map?.getLayer(t))}async showCatalogOverlay(t,i){if(!this.map)throw new Error("Map is not initialized");const e=this.map,s=this.overlayLayerIds(t),n=this.overlayBeforeId();if(s.length>0){for(const t of s)e.setLayoutProperty(t,"visibility","visible"),this.moveLayerBefore(t,n);return}const r=await $(N(i,"2d"));for(const[o,a]of Object.entries(r.sources??{}))e.getSource(o)||e.addSource(o,a);this.injectedOverlays[t]=ri(r);for(const o of r.layers??[])e.getLayer(o.id)||e.addLayer(o,n),e.setLayoutProperty(o.id,"visibility","visible")}hideCatalogOverlay(t){if(this.map)for(const i of this.overlayLayerIds(t))this.map.setLayoutProperty(i,"visibility","none")}moveLayerBefore(t,i){if(!this.map||!i)return;const e=this.map.getStyle(),s=e?.layers?.find(i=>i.id===t);s&&(this.map.removeLayer(t),this.map.addLayer(s,i))}reapplyCustomLayers(){this.map&&(this.reapplyBaseLayerVisibility(),this.localizeVectorMap())}reapplyBaseLayerVisibility(){if(this.map&&this.currentBaseLayer)for(const t of this.baseLayerIds(this.currentBaseLayer))this.map.setLayoutProperty(t,"visibility","visible")}addSource(t,i){if(!this.map)throw new Error("Map is not initialized");this.map.getSource(t)||this.map.addSource(t,{type:"geojson",data:i})}updateSource(t,i){if(!this.map)throw new Error("Map is not initialized");const e=this.map.getSource(t);e&&"geojson"===e.type&&e.setData(i)}removeSource(t){if(!this.map)throw new Error("Map is not initialized");this.map.getSource(t)&&this.map.removeSource(t)}addLayer(t,i){if(!this.map)throw new Error("Map is not initialized");this.map.getLayer(t.id)||this.map.addLayer(t,i)}removeLayer(t){if(!this.map)throw new Error("Map is not initialized");this.map.getLayer(t)&&this.map.removeLayer(t)}}class ai{constructor(t){this.map=t}is3DModeActive=!1;isManualModeSwitch=!1;customStyleUrl=void 0;styleProvider=null;setMap(t){this.map=t}setCustomStyleUrl(t){this.customStyleUrl=t}setStyleProvider(t){this.styleProvider=t}get3DModeActive(){return this.is3DModeActive}getRenderMode(){return this.is3DModeActive?"3d":"2d"}getManualModeSwitch(){return this.isManualModeSwitch}async enable3DTerrain(t,i){if(!this.map)throw new Error("Map is not initialized");if(this.isManualModeSwitch=!0,this.is3DModeActive)return void setTimeout(()=>{this.isManualModeSwitch=!1},2e3);this.is3DModeActive=!0;
1const e=await this.getStyleForBaseLayer(t);this.map.setStyle(e),this.map.once("styledata",()=>{this.map&&this.is3DModeActive&&(i(),setTimeout(()=>{this.isManualModeSwitch=!1},2e3))})}async disable3DTerrain(t,i){if(!this.map)throw new Error("Map is not initialized");if(!this.is3DModeActive)return;this.isManualModeSwitch=!0,this.is3DModeActive=!1;const e=await this.getStyleForBaseLayer(t);this.map.setStyle(e),this.map.once("styledata",()=>{this.map&&!this.is3DModeActive&&(i(),setTimeout(()=>{this.isManualModeSwitch=!1},2e3))})}is3DTerrainEnabled(){if(!this.map)throw new Error("Map is not initialized");return null!==this.map.getTerrain()}async getStyleForBaseLayer(t){if(this.customStyleUrl)return await O(this.customStyleUrl);if(!this.styleProvider)throw new Error("No composed style provider configured");return this.styleProvider(t,this.getRenderMode())}}function hi(t,i){const e=i?.["visorando:visibilityMinUserGid"],s=i?.["visorando:useMinUserGid"],n=i?.["visorando:useRequiresPremium"];if(void 0!==e&&("number"!=typeof e||!Number.isInteger(e)||e<0||e>9))throw new Error(`Layer ${t} must define visorando:visibilityMinUserGid as an integer from 0 to 9 when present`);if("number"!=typeof s||!Number.isInteger(s)||s<0||s>9)throw new Error(`Layer ${t} must define visorando:useMinUserGid as an integer from 0 to 9`);if("boolean"!=typeof n)throw new Error(`Layer ${t} must define visorando:useRequiresPremium as a boolean`);return{...void 0!==e&&{visibilityMinUserGid:e},useMinUserGid:s,useRequiresPremium:n}}function li(t,i){if(0===t.length)return null;const e=Math.min(t.length-1,Math.ceil(i/100*t.length)-1),s=t[Math.max(0,e)];return void 0===s?null:Math.round(10*s)/10}function ci(t){const i=[...t].sort((t,i)=>t-i);return{n:i.length,p50:li(i,50),p95:li(i,95),total:Math.round(i.reduce((t,i)=>t+i,0))}}class ui{timings=[];add(t){this.timings.push(t)}raw(){return[...this.timings]}reset(){this.timings=[]}report(){const t={},i={fetch:[],decode:[],process:[],wait:[],duration:[]};let e=0,s=0,n=0,r=0;for(const o of this.timings){const a=o.url.split("://")[0]??"unknown";t[a]=(t[a]??0)+1,void 0!==o.fetch&&i.fetch.push(o.fetch),void 0!==o.decode&&i.decode.push(o.decode),void 0!==o.process&&i.process.push(o.process),i.wait.push(o.wait),i.duration.push(o.duration),n+=o.tilesUsed,o.error&&r++;for(const t of o.resources)s++,e+=t.transferSize||t.encodedBodySize||0}return{tilesByProtocol:t,categories:{fetch:ci(i.fetch),decode:ci(i.decode),process:ci(i.process),wait:ci(i.wait),duration:ci(i.duration)},demBytesDownloaded:e,resourcesFetched:s,demTilesUsed:n,errors:r}}}class di{map=null;pendingConfig=null;customEventListeners={};tracker=new it;catalog=null;controlsManager;cameraManager;layerManager;mode3DManager;constructor(){this.controlsManager=new Ft(this,this.tracker),this.cameraManager=new Ot(null),this.layerManager=new oi(null),this.mode3DManager=new ai(null)}async init(t){if(this.map)throw new Error("Map is already initialized. Call destroy() first.");if(!t.center)return void(this.pendingConfig=t);var e;t.stylesBaseUrl&&(e=t.stylesBaseUrl,L=e.endsWith("/")?e.slice(0,-1):e,C.clear()),t.customStyleUrl&&this.mode3DManager.setCustomStyleUrl(t.customStyleUrl);const s=St();"undefined"!=typeof window&&"1"===new URLSearchParams(window.location.search).get("vrDebugContours")&&function(t){const i=new ui;t.onTiming(t=>i.add(t)),window.__vrContourTiming=i}(s),this.catalog=await this.resolveCatalog(t),this.mode3DManager.setStyleProvider((t,i)=>this.composeStyleFor(t,i)),this.layerManager.setBaseFragmentResolver(t=>this.loadBaseFragment(t,this.mode3DManager.getRenderMode())),this.layerManager.setFallbackGlyphs(this.catalog.glyphsUrl??T),this.layerManager.setCurrentBaseLayer(t.baseLayer),(t.enableTracking??M.enableTracking)&&this.tracker.enable();const n=await this.mode3DManager.getStyleForBaseLayer(t.baseLayer),r={container:t.container,center:this.coordinatesToLngLat(t.center),zoom:t.zoom,minZoom:t.minZoom??M.minZoom,maxZoom:t.maxZoom??M.maxZoom,minPitch:t.minPitch??M.minPitch,maxPitch:t.maxPitch??M.maxPitch,style:n,pitch:M.pitch,bearing:M.bearing,pitchWithRotate:t.enablePitch??M.pitchWithRotate,dragRotate:t.enableRotation??M.dragRotate,touchPitch:t.enablePitch??M.touchPitch,touchZoomRotate:M.touchZoomRotate,maxTileC
1acheSize:t.maxTileCacheSize??M.maxTileCacheSize,renderWorldCopies:t.renderWorldCopies??M.renderWorldCopies,fadeDuration:t.fadeDuration??M.fadeDuration,attributionControl:!1};this.map=new i.Map({...r,aroundCenter:!1}),this.cameraManager.setMap(this.map),this.layerManager.setMap(this.map),this.mode3DManager.setMap(this.map);const o=t.enable3DMode??S.enable3DMode;this.map.on("load",()=>{this.onMapLoad(t,o)})}async resolveCatalog(t){if(t.catalog){const i=K(t.catalog);if(i)return i}if(t.catalogUrl){const i=await async function(t){try{const i=await fetch(t,{credentials:"same-origin",headers:{Accept:"application/json"}});return i.ok?K(await i.json()):null}catch{return null}}(t.catalogUrl);if(i)return i}return V}async composeStyleFor(t,i){const e=await this.loadBaseFragment(t,i);return this.layerManager.registerBaseFragment(t,e),function(t){const{mode:i,baseFragment:e,glyphs:s,demTiles:n}=t,r="3d"===i,o={},a=[];if(e){Object.assign(o,e.sources??{});for(const t of e.layers??[])a.push(R(t,"visible"))}const h=function(t){return{summits:{type:"vector",tiles:["https://vector.visomap.com/data/summits/{z}/{x}/{y}.pbf"],minzoom:10,maxzoom:14},terrain:{type:"raster-dem",tiles:[t??k],tileSize:512,encoding:A,attribution:"© Visorando",maxzoom:x},"recording-trace":{type:"geojson",data:{type:"FeatureCollection",features:[]},lineMetrics:!0},"bike-directions-source":{type:"geojson",data:{type:"FeatureCollection",features:[]}},"waypoints-source":{type:"geojson",data:{type:"FeatureCollection",features:[]}}}}(n);for(const[c,u]of Object.entries(h))c in o||(o[c]=u);for(const c of[{id:P,type:"symbol",source:"summits","source-layer":"summits",minzoom:12,layout:{"text-field":["format",["get","name"],{"font-scale":1},"\n",{},["get","ele"],{"font-scale":.8}," m",{"font-scale":.8}],"text-font":["Open Sans Bold"],"text-size":11,"text-anchor":"bottom","text-offset":[0,-.5],"text-allow-overlap":!1,"text-optional":!0,visibility:"none"},paint:{"text-color":"#2c3e50","text-halo-color":"#ffffff","text-halo-width":2,"text-halo-blur":1},metadata:{"visorando:category":"overlay","visorando:hideFromPanel":!0,"visorando:useMinUserGid":2,"visorando:useRequiresPremium":!1}},{id:"bike-directions-layer",minzoom:10,type:"circle",source:"bike-directions-source",layout:{},paint:{"circle-radius":["interpolate",["linear"],["zoom"],8,5,16,8],"circle-color":["get","color"],"circle-stroke-width":["interpolate",["linear"],["zoom"],8,1,16,2],"circle-stroke-color":"#FFFFFF"},metadata:{"visorando:category":"waypoints"}},{...E("waypoint-normal","https://www.visorando.com/img/fiches/wpt_carte_blank.svg"),minzoom:10},{id:"waypoints-number-waypoint-normal",minzoom:10,type:"symbol",source:"waypoints-source",filter:["all",["==",["get","icon"],"waypoint-normal"],[">",["get","waypointNumber"],0]],layout:{"text-field":["to-string",["get","waypointNumber"]],"symbol-sort-key":["to-number",["get","waypointNumber"]],"text-font":["Open Sans Bold"],"text-size":["interpolate",["linear"],["zoom"],8,8,16,16],"text-line-height":1,"text-offset":[0,-2.15],"text-anchor":"center","text-allow-overlap":!0,"text-ignore-placement":!0},paint:{"text-color":"#FFFFFF","text-halo-color":"#19527C","text-halo-width":1,"text-halo-blur":1.2},metadata:{"visorando:category":"waypoints"}},E("waypoint-start","https://www.visorando.com/img/fiches/wpt_carte_depart.svg",{"symbol-sort-key":["to-number",["get","waypointNumber"]]}),E("waypoint-end","https://www.visorando.com/img/fiches/wpt_carte_arrivee.svg"),E("waypoint-startend","https://www.visorando.com/img/fiches/wpt_carte_depart_arrivee.svg"),E("waypoint-stage","https://www.visorando.com/img/fiches/wpt_carte_stage.svg"),{id:"recording-trace-outline-layer",type:"line",source:"recording-trace",layout:{"line-join":"round","line-cap":"round",visibility:"none"},paint:{"line-color":"#FFFFFF","line-width":6,"line-opacity":.8},metadata:{"visorando:category":"recording"}},{id:"recording-trace-layer",type:"line",source:"recording-trace",layout:{"line-join":"round","line-cap":"round",visibility:"none"},paint:{"line-color":"#2196F3","line-width":4,"line-opacity":.9},metadata:{"visorando:category":"recording"}}])r&&c.id===P?a.push(R(c,"visible")):a.push(c);
1const l={version:8,name:r?"Visorando 3D":"Visorando 2D",metadata:{mode:i},projection:{type:"mercator"},glyphs:e?.glyphs??s??T,...void 0!==e?.sprite&&{sprite:e.sprite},sources:o,layers:a};return r&&(l.terrain={source:"terrain",exaggeration:1},l.sky={"sky-color":"#199EF3","sky-horizon-blend":.5,"horizon-color":"#ffffff","horizon-fog-blend":.5,"fog-color":"#ffffff","fog-ground-blend":.5,"atmosphere-blend":["interpolate",["linear"],["zoom"],0,1,10,1,12,0]}),l}({mode:i,baseFragment:e,glyphs:this.catalog?.glyphsUrl,demTiles:St().sharedDemProtocolUrl})}async loadBaseFragment(t,i){const e=this.catalog?.maps.find(i=>i.id===t);if(!e)throw new Error(`Unknown base layer: ${t}`);if(!e.styleUrl)throw new Error(`Base layer is unavailable: ${t}`);let s=await $(N(e.styleUrl,i));const n=V.maps.find(i=>i.id===t),r=void 0===e?.runtimeContours?n?.runtimeContours:e.runtimeContours??void 0,o=void 0===e?.sharedDemSourceId?n?.sharedDemSourceId:e.sharedDemSourceId??void 0,a=St();if(o){const t=s.sources?.[o];"raster-dem"===t?.type&&(s={...s,sources:{...s.sources,[o]:{type:"raster-dem",tiles:[a.sharedDemProtocolUrl],tileSize:512,encoding:A,maxzoom:x}}})}return r?function(t,i,e){const s=[...t.layers??[]],n=t=>({...t,layout:{...t.layout??{},visibility:"visible"}});return H(s,e.linesAfterLayerId,[n(z),n(_)]),H(s,e.labelsAfterLayerId,[n(j)]),{...t,sources:{...t.sources??{},[B]:G(i)},layers:s}}(s,a.contourProtocolUrl.bind(a),r):s}onMapLoad(t,i){this.map&&(this.initializeControls(t),this.controlsManager.setupFullscreenTracking(),this.setupAutoPitchActivation(),this.layerManager.localizeVectorMap(),i&&setTimeout(()=>{this.enable3DTerrain()},100))}initializeControls(t){const i=M;let e;t.fullscreenContainer&&(e="string"==typeof t.fullscreenContainer?document.getElementById(t.fullscreenContainer)??void 0:t.fullscreenContainer),this.controlsManager.initializeControls(this.map,!1!==t.showControls,t.enableRotation??!0,t.enablePitch??!0,t.showMouseCoordinates??!1,t.coordinateFormat??i.coordinateFormat,t.elevationUnit??i.elevationUnit,e)}setupAutoPitchActivation(){this.map&&this.map.on("pitchend",()=>{if(this.map&&!this.mode3DManager.getManualModeSwitch()&&this.map.getPitch()>5&&!this.mode3DManager.get3DModeActive()){this.enable3DTerrain(),this.tracker.trackEvent("3D View","Toggle 3D mode","3D");const t=this.controlsManager.getToggle3DControl();t&&"function"==typeof t.updateButtonState&&t.updateButtonState(!0),this.controlsManager.hideScaleControl()}})}getMap(){return this.map}isInitialized(){return null!==this.map}setCenter(t,i){this.ensureInitialized(),this.cameraManager.setCenter(t,i)}fitBounds(t,i,e=50,s,n){this.ensureInitialized(),this.cameraManager.fitBounds(t,i,e,s,n)}centerOnTrailWithOptimalView(t=50,i=0,e=1500){this.ensureInitialized(),this.cameraManager.centerOnTrailWithOptimalView(t,i,e)}setTrailPoints(t){this.cameraManager.setTrailPoints(t)}async setBaseLayer(t){this.ensureInitialized(),await this.layerManager.changeBaseLayer(t)}async initializeWithCenter(t,i){if(this.map)return void this.setCenter(t,i);if(!this.pendingConfig)throw new Error("No pending config - map was not created without center");const e={...this.pendingConfig,center:t,zoom:i??this.pendingConfig.zoom};this.pendingConfig=null,await this.init(e)}getBaseLayer(){return this.layerManager.getCurrentBaseLayer()}async setBaseLayerFromMapLayer(t,i){if(this.ensureInitialized(),!t||!t.id)throw new Error("Invalid layer: missing id");const e=t.id;if(!(this.catalog?this.catalog.maps.map(t=>t.id):[]).includes(e))return;const s=this.layerManager.getCurrentBaseLayer();try{await this.setBaseLayer(e)}catch(n){return void this.dispatchBaseLayerEvent("vrmap:baselayererror",{layerId:e,previousLayerId:s})}this.dispatchBaseLayerEvent("vrmap:baselayerchanged",{layerId:e}),i&&setTimeout(()=>{i()},100)}dispatchBaseLayerEvent(t,i){this.map&&this.map.getContainer().dispatchEvent(new CustomEvent(t,{detail:i,bubbles:!1}))}addSource(t,i){this.ensureInitialized(),this.layerManager.addSource(t,i)}updateSource(t,i){this.ensureInitialized(),this.layerManager.updateSource(t,i)}removeSource(t){this.ensureInitialized(),this.layerManager.removeSource(t)}addLayer(t,i){this.ensureInitialized(),this.layerManager.addLayer(t,i)}removeLayer(t){this.ensureInitialized(),this.layerManager.removeLayer(t)}localizeVectorMap(){this.ensureInitialized(),this.layerManager.localizeVectorMap()}async enable3DTerrain(){this.ensureInitialized();const t=this.layerManager.getCurrentBaseLayer();await this.mode3DManager.enable3DTerrain(t,()=>this.reapplyCustomLayers())}async disable3DTerrain(){this.ensureInitialized();const t=this.layerManager.getCurrentBaseLayer();await this.mode3DManager.disable3DTerrain(t,()=>this.reapplyCustomLayers())}is3DTerrainEnabled(){return this.ensureInitialized(),this.mode3DManager.is3DTerrainEnabled()}reapplyCustomLayers(){this.layerManager.reapplyCustomLayers(),this.emitCustomEvent("style.reloaded",{is3DMode:this.mode3DManager.get3DModeActive()})}on(t,i){if("style.reloaded"===t)return this.customEventListeners[t]||(this.customEventListeners[t]=[]),void this.customEventListeners[t].push(i);this.ensureInitialized(),this.map.on(t,i)}emitCustomEvent(t,i){const e=this.customEventListeners[t];e&&e.length>0&&e.forEach(t=>{t(i)})}onLoad(t){this.map&&(this.map.loaded()?t():this.map.once("load",()=>{t()}))}async waitForLoad(){return this.map?this.map.loaded()?Promise.resolve():new Promise(t=>{this.map.once("load",()=>t())}):Promise.resolve()}ensureInitialized(){if(!this.map)throw new Error("Map is not initialized. Call init() first.")}coordinatesToLngLat(t){return[t.lng,t.lat]}get currentTrailPoints(){return this.cameraManager.getCurrentTrailPoints()}get currentTrailBounds(){return this.cameraManager.getCurrentTrailBounds()}get fitBoundsPadding(){return this.cameraManager.getFitBoundsPadding()}get scaleControl(){return this.controlsManager.getScaleControl()}getContainer(){return this.ensureInitialized(),this.map.getContainer()}flyTo(t){this.ensureInitialized(),this.map.flyTo(t)}easeTo(t){this.ensureInitialized(),this.map.easeTo(t)}setBearing(t){this.ensureInitialized(),this.map.setBearing(t)}setPitch(t){this.ensureInitialized(),this.map.setPitch(t)}isLoaded(){return this.map?.loaded()??!1}isStyleLoaded(){return this.map?.isStyleLoaded()??!1}hasImage(t){return this.ensureInitialized(),"function"==typeof this.map.hasImage&&this.map.hasImage(t)}addImage(t,i,e){this.ensureInitialized(),"function"==typeof this.map.addImage&&this.map.addImage(t,i,e)}hasSource(t){return this.ensureInitialized(),!!this.map.getSource(t)}hasLayer(t){return this.ensureInitialized(),!!this.map.getLayer(t)}setSourceData(t,i){this.ensureInitialized();const e=this.map.getSource(t);e&&e.setData(i)}addSourceRaw(t,i){this.ensureInitialized(),this.map.getSource(t)||this.map.addSource(t,i)}setLayoutProperty(t,i,e){this.ensureInitialized(),this.map.getLayer(t)&&this.map.set
1LayoutProperty(t,i,e)}getStyle(){if(this.map)return this.map.getStyle()}addControl(t,i){this.ensureInitialized(),this.map.addControl(t,i)}onLayerClick(t,i){this.ensureInitialized(),this.map.on("click",t,i)}onLayerMouseEnter(t,i){this.ensureInitialized(),this.map.on("mouseenter",t,i)}onLayerMouseLeave(t,i){this.ensureInitialized(),this.map.on("mouseleave",t,i)}setCursor(t){this.ensureInitialized(),this.map.getCanvas().style.cursor=t}extractLayerDefinitions(){return this.catalog?function(t){const i=[],e=[];for(const s of t.maps)s.hideFromPanel||i.push({id:s.id,name:s.title||s.id,category:g.BASE,type:v.RASTER,defaultVisible:!1,access:q(s),...s.styleUrl&&{styleUrl:s.styleUrl},...s.thumbnailURL&&{thumbnailUrl:s.thumbnailURL}});for(const s of t.overlay_groups){const t=Z(s);for(const i of s.overlays)i.hideFromPanel||e.push({id:i.id,name:i.title||i.id,category:g.OVERLAY,type:v.RASTER,defaultVisible:!1,access:q(i),...t&&{group:t},...i.styleUrl&&{styleUrl:i.styleUrl},...i.tooltip&&{description:i.tooltip}})}return{baseLayers:i,overlayLayers:e}}(this.catalog):this.map?function(t){const i=[],e=[],s=t.getStyle();if(!s||!s.layers)return{baseLayers:i,overlayLayers:e};for(const n of s.layers){const t=n.metadata;if(!t||!t["visorando:category"])continue;if(!0===t["visorando:hideFromPanel"])continue;const r=t["visorando:category"],o=t["visorando:group"],a=t["visorando:legendHtml"];if("base"!==r&&"overlay"!==r)continue;let h;h=n.id.endsWith("-layer")?n.id.replace("-layer","").toUpperCase():n.id.toUpperCase();const l=n.source,c=l?s.sources?.[l]:void 0;if(!c&&"background"!==n.type)continue;const u="visible"===n.layout?.visibility,d=hi(n.id,t),f=n.paint?{...n.paint}:void 0,p={id:h,name:h,category:"base"===r?g.BASE:g.OVERLAY,type:v.RASTER,defaultVisible:u,access:d,...o&&{group:o},...a&&{legendHtml:a},...f&&{paint:f}};c&&"object"==typeof c&&(p.source=c),"base"===r?i.push(p):"overlay"===r&&e.push(p)}return{baseLayers:i,overlayLayers:e}}(this.map):{baseLayers:[],overlayLayers:[]}}getCatalogLegends(){return this.catalog?function(t){const i=[];for(const e of t.overlay_groups){const t=Z(e),s=e.overlays.length>1,n=s?t??e.id??e.title:e.overlays[0]?.id??e.title;if(e.legend&&Object.keys(e.legend).length>0){i.push({key:n,isGroup:s,title:e.title,table:e.legend});continue}const r=e.id?W[e.id]:void 0;r&&i.push({key:n,isGroup:s,titleKey:r.titleKey,data:{table:r.table}})}return i}(this.catalog):null}async showCatalogOverlay(t,i){this.ensureInitialized(),await this.layerManager.showCatalogOverlay(t,i)}hideCatalogOverlay(t){this.ensureInitialized(),this.layerManager.hideCatalogOverlay(t)}getCurrentBaseLayerIds(){return this.layerManager.getCurrentBaseLayerIds()}moveLayer(t,i){this.ensureInitialized();const e=this.map.getStyle(),s=e?.layers?.find(i=>i.id===t);s&&(this.map.removeLayer(t),this.map.addLayer(s,i))}showPopup(t){this.ensureInitialized();const e={maxWidth:t.maxWidth??"280px",closeButton:t.closeButton??!0,closeOnClick:t.closeOnClick??!1};t.className&&(e.className=t.className),void 0!==t.offset&&(e.offset=t.offset);const s=new i.Popup(e).setLngLat(t.lngLat).setHTML(t.html).addTo(this.map);return{remove:()=>s.remove()}}addDomMarker(t){this.ensureInitialized();const e=new i.Marker({element:t.element,anchor:t.anchor??"center"}).setLngLat(t.lngLat).addTo(this.map);return{remove:()=>e.remove(),setLngLat:t=>{e.setLngLat(t)}}}getCenter(){this.ensureInitialized();const t=this.map.getCenter();return{lat:t.lat,lng:t.lng}}getZoom(){return this.ensureInitialized(),this.map.getZoom()}getBearing(){return this.ensureInitialized(),this.map.getBearing()}getPitch(){return this.ensureInitialized(),this.map.getPitch()}onMapEvent(t,i){this.ensureInitialized(),this.map.on(t,i)}queryRenderedFeatures(t){return this.ensureInitialized(),this.map.queryRenderedFeatures([t.x,t.y])}async getElevationAtPoint(t,i){return this.ensureInitialized(),Ct(t,i,Math.min(Math.floor(this.map.getZoom()),x))}}function fi(t,i){return"visibilityMinUserGid"in t.access&&void 0!==t.access.visibilityMinUserGid&&i.userGid<t.access.visibilityMinUserGid?"hidden":i.userGid<t.access.useMinUserGid?i.userGid<2?"login":"unavailable":t.access.useRequiresPremium&&!i.isPremium?"premium":"none"}function pi(t,i){return"none"===fi(t,i)}function mi(t,i){return"premium"===fi(t,i)}function yi(t,i){return t.filter(t=>function(t,i){return"hidden"!==fi(t,i)}(t,i))}class wi{constructor(t={userGid:0,isPremium:!1}){this.accessContext=t}layers=new Map;overlayStack=[];currentBaseLayer=null;listeners=[];registerLayers(t){t.forEach(t=>{if(this.layers.set(t.id,{layer:t,visible:!1,loaded:!1}),t.isOverlay()&&t.defaultVisible){const i=this.getStackName(t.group,t.id);this.overlayStack.push(i)}})}getAllLayers(){return Array.from(this.layers.values()).map(t=>t.layer)}getBaseLayers(){return this.getAllLayers().filter(t=>t.isBaseLayer())}getOverlayLayers(){return this.getAllLayers().filter(t=>t.isOverlay())}getOverlaysByGroup(t){return this.getOverlayLayers().filter(i=>i.group===t)}getGroups(){const t=new Set;
1return this.getOverlayLayers().forEach(i=>{i.group&&t.add(i.group)}),Array.from(t)}getCurrentBaseLayer(){if(!this.currentBaseLayer)return null;const t=this.layers.get(this.currentBaseLayer);return t?t.layer:null}setBaseLayer(t){const i=this.layers.get(t);if(!i?.layer.isBaseLayer())throw new Error(`Invalid base layer: ${t}`);if(!pi(i.layer,this.accessContext))throw new Error(`Unauthorized base layer: ${t}`);if(this.currentBaseLayer){const t=this.layers.get(this.currentBaseLayer);t&&(t.visible=!1)}i.visible=!0,this.currentBaseLayer=t,this.emit({type:"base-changed",layerId:t})}isOverlayVisible(t){const i=this.layers.get(t);return!!i&&i.visible}markLayerLoaded(t){const i=this.layers.get(t);i&&(i.loaded=!0)}showOverlay(t){const i=this.layers.get(t);if(!i||!i.layer.isOverlay())throw new Error(`Invalid overlay: ${t}`);if(!pi(i.layer,this.accessContext))return;const e=i.layer,s=this.getStackName(e.group,t);e.group&&this.hideGroup(e.group,t),i.visible=!0,this.removeFromStack(s),this.overlayStack.push(s),this.emit({type:"overlay-shown",layerId:t,...void 0!==e.group&&{groupId:e.group}})}hideOverlay(t){const i=this.layers.get(t);if(!i||!i.layer.isOverlay())return;const e=i.layer,s=this.getStackName(e.group,t);i.visible=!1,this.removeFromStack(s),this.emit({type:"overlay-hidden",layerId:t,...void 0!==e.group&&{groupId:e.group}})}hideGroup(t,i){const e=`${t}:`;this.overlayStack.slice().forEach(t=>{if(t.startsWith(e)){const s=t.substring(e.length);s!==i&&this.hideOverlay(s)}})}isGroupActive(t){return this.getOverlaysByGroup(t).some(t=>this.isOverlayVisible(t.id))}getActiveOverlayInGroup(t){const i=this.getOverlaysByGroup(t);for(const e of i)if(this.isOverlayVisible(e.id))return e;return null}setActiveOverlays(t,i){const e=new Set(t.map(t=>t.toUpperCase())),s=t=>i?i.has(t.toUpperCase()):this.isOverlayVisible(t);this.getOverlayLayers().forEach(t=>{s(t.id)&&!e.has(t.id.toUpperCase())&&this.hideOverlay(t.id)}),t.forEach(t=>{const i=t.toUpperCase(),e=this.getOverlayLayers().find(t=>t.id.toUpperCase()===i);e&&!this.isOverlayVisible(e.id)&&this.showOverlay(e.id)})}on(t){this.listeners.push(t)}emit(t){this.listeners.forEach(i=>i(t))}getStackName(t,i){return t?`${t}:${i}`:i}removeFromStack(t){const i=this.overlayStack.indexOf(t);-1!==i&&this.overlayStack.splice(i,1)}syncBaseLayerState(t){const i=this.layers.get(t);if(i&&i.layer.isBaseLayer()){if(this.currentBaseLayer&&this.currentBaseLayer!==t){const t=this.layers.get(this.currentBaseLayer);t&&(t.visible=!1)}i.visible=!0,i.loaded=!0,this.currentBaseLayer=t}}}function vi(t,i,e){return 1===t.isStage?r.STAGE:"d"===t.type?r.BIKE_DIRECTION:"i"===t.type?r.BIKE_DIRECTION_INFO:1===t.da||1===t.d?r.START:1===t.a?r.END:r.WAYPOINT}class gi{static parseTrail(t,i){const e=String(i);if(!e||0===e.trim().length)throw new Error("trailId cannot be empty");const s=t.geojson.features;if(0===s.length)throw new Error("No trail data found in API response");if(!s[0])throw new Error("No first feature found");const h=[];if(t.chartdata&&t.chartdata.data){const i=t.chartdata.data;for(let t=0;t<s.length;t++){const e=s[t];if(!e)continue;const[n,r]=e.geometry.coordinates;let o,l=0;if(t<i.length){const e=i[t];e&&(o=e[0],l=e[1])}h.push(new a(new y(r,n),new w(l),o))}}else for(const n of s){const[t,i]=n.geometry.coordinates;h.push(new a(new y(i,t),new w(0)))}const l=[],c=s.filter(t=>1===t.properties.wpt||"d"===t.properties.type||"i"===t.properties.type);for(let n=0;n<c.length;n++){const i=c[n];if(!i)continue;const[s,a]=i.geometry.coordinates;let h,u=0;if(t.chartdata&&t.chartdata.data){const e=i.properties.index;if(e<t.chartdata.data.length){const i=t.chartdata.data[e];i&&(u=i[1],h=i[0])}}c.length;const d=vi(i.properties),f=1===i.properties.da,p=i.properties.raison?.trim()||void 0;"d"===i.properties.type||"i"===i.properties.type?(l.push(new o(`wp-bike-${i.properties.index}`,new y(a,s),new w(u),d,i.properties.indications,e,i.properties.index,f,i.properties.wptTitle,i.properties.wptText,!1,h,p)),1===i.properties.wpt&&l.push(new o(`wp-${i.properties.index}`,new y(a,s),new w(u),r.WAYPOINT,i.properties.indications,e,i.properties.index,f,i.properties.wptTitle,i.properties.wptText,!1,h,p))):l.push(new o(`wp-${i.properties.index}`,new y(a,s),new w(u),d,i.properties.indications,e,i.properties.index,f,i.properties.wptTitle,i.properties.wptText,!1,h,p))}const u=t.chartdata?.areas?.map(t=>{const i={color:t.color};return void 0!==t.value&&(i.endDistanceMeters=t.value),void 0!==t.averageSlopePercent&&(i.averageSlopePercent=t.averageSlopePercent),i});return new n(e,h,l,u)}}class bi{baseUrl;timeout;constructor(t={}){this.baseUrl=(t.baseUrl??"https://www.visorando.com").replace(/\/+$/,""),this.timeout=t.timeout??3e4}async fetchTrail(t){const i=new URL(`${this.baseUrl}/index.php`);i.searchParams.set("component","exportData"),i.searchParams.set("task","getRandoGeoJson"),i.searchParams.set("chartData","1"),i.searchParams.set("wholePointsData","1"),i.searchParams.set("idRandonnee",String(t));try{const t=new AbortController,e=setTimeout(()=>t.abort(),this.timeout),s=await fetch(i.toString(),{method:"GET",signal:t.signal,headers:{Accept:"application/json"}});if(clearTimeout(e),!s.ok)throw new Error(`HTTP error! status: ${s.status}`);const n=await s.json();if(!n.geojson||!n.geojson.features||!Array.isArray(n.geojson.features))throw new Error("Invalid API response structure");return n}catch(e){if(e instanceof Error){if("AbortError"===e.name)throw new Error(`Request timeout after ${this.timeout}ms`);throw new Error(`Failed to fetch trail data: ${e.message}`)}throw e}}}const Mi={...S,zoom:13,baseLayer:"IGNTOPO",enablePitch:!0,enableRotation:!0,enable3DMode:!1,enableLayerSelector:!0,showControls:!0,fitBoundsPadding:50,fitBoundsPitch:50,fitBoundsBearing:0,showTrailOutline:!0,showElevationChart:!1,elevationChartHeight:300,comparativeScale:!0,distanceUnit:"km",locale:"fr",stylesBaseUrl:"https://www.visorando.com",apiBaseUrl:"https://www.visorando.com",bikeDirectionImageBaseUrl:"https://www.visorando.com/images/velo/directions/",enableTracking:!1,isPremium:!1,userGid:0,loginUrl:"/index.php?component=user&task=loginForm",premiumUrl:"https://www.visorando.com/premium.html",showOverlayLegends:!1,enableContextMenu:!0},Si={fr:"https://support.visorando.com/enregistrement-suivi-d-un-circuit/legende
1-des-cartes",en:"",de:""};function Ci(){const t=tt();return Si[t]??Si.fr}function Li(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function $i(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/[\n\r\f]/g,"")}class Fi{container;layerManager;panelElement=null;isOpen;tracker;isPremium;accessContext;loginUrl;premiumUrl;constructor(t){this.container=t.container,this.layerManager=t.layerManager,this.isOpen=t.defaultOpen??Oi.defaultOpen,this.tracker=new it(t.enableTracking??Oi.enableTracking),this.isPremium=t.isPremium??Oi.isPremium,this.accessContext={userGid:t.userGid??Oi.userGid,isPremium:this.isPremium},this.loginUrl=t.loginUrl??Oi.loginUrl,this.premiumUrl=t.premiumUrl??Oi.premiumUrl,this.render(),this.attachEventListeners()}render(){const t=document.createElement("aside");t.className="vrmap-map-layers-panel",t.setAttribute("role","region"),t.setAttribute("aria-label",Q("layers.baseLayers")+" "+Q("layers.overlays")),this.isOpen&&t.classList.add("vrmap-is-open"),t.innerHTML=`\n      <header>\n        <button type="button" class="vrmap-close-panel" title="${Li(
1Q("controls.close"))}" aria-label="${Li(Q("controls.close"))}">×</button>\n      </header>\n      <div class="vrmap-map-layers-panel--content">\n        ${this.renderBaseLayers()}\n        ${this.renderOverlays()}\n        ${Ci()?`<section>\n          <a class="btn btn-secondary w-full" \n             href="${Ci()}" \n             target="_blank" \n             rel="noopener noreferrer" \n             aria-label="${Li(Q("layers.legendLink"))}">\n            <i class="vr-icon vr-icon-map" aria-hidden="true"></i>${Li(Q("layers.legendLink"))}\n          </a>\n        </section>`:""}\n      </div>\n      ${this.renderFooterCta()}\n    `,this.container.appendChild(t),this.panelElement=t,this.initializeTooltips(),setTimeout(()=>{this.updateBaseLayerVisualState()},0)}renderFooterCta(){const t=this.layerManager.getAllLayers().map(t=>fi(t,this.accessContext));return t.includes("login")&&this.loginUrl?`\n       <footer>\n          <a class="btn w-full" href="${Li(this.loginUrl)}" target="_blank" rel="noopener noreferrer" data-login-btn>${Li(Q("layers.login"))}</a>\n       </footer>`:t.includes("premium")&&this.premiumUrl?`\n       <footer>\n          <a class="btn btn--premium w-full" href="${Li(this.premiumUrl)}" target="_blank" rel="noopener noreferrer" data-premium-btn>${Li(Q("layers.discover_premium"))}</a>\n       </footer>`:""}initializeTooltips(){if(!this.panelElement)return;const t=function(){if("undefined"!=typeof window&&window.tippy)return window.tippy}();t&&this.panelElement.querySelectorAll("[title]").forEach(i=>{const e=i.getAttribute("title");e&&(i.removeAttribute("title"),t(i,{content:e,placement:"top",arrow:!0,theme:"light-border",animation:"scale",duration:[200,150],maxWidth:300}))})}renderBaseLayers(){const t=this.layerManager.getBaseLayers(),i=this.layerManager.getCurrentBaseLayer(),e={IGNTOPO:{img:"https://www.visorando.com/img/layers/thumbnails/16-9/topo.jpg",label:Q("layers.topo"),title:Q("layers.topoFull")},IGNSAT:{img:"https://www.visorando.com/img/layers/thumbnails/16-9/sat.jpg",label:Q("layers.satellite"),title:Q("layers.satellite")},HIKINGMAP:{img:"https://www.visorando.com/img/layers/thumbnails/16-9/osmrando.jpg",label:Q("layers.osmHiking"),title:Q("layers.osmHikingFull")},MAPNIK:{img:"https://www.visorando.com/img/layers/thumbnails/16-9/osm.jpg",label:Q("layers.osm"),title:Q("layers.osmFull")},CYCLINGMAP:{img:"https://www.visorando.com/img/layers/thumbnails/16-9/cyclosm.jpg",label:Q("layers.osmCycling"),title:Q("layers.osmCyclingFull")}};return`\n      <section class="vrmap-baselayer-selector">\n        <strong class="vrmap-h5" id="base-layers-heading">${Li(Q("layers.baseLayers"))}</strong>\n        <fieldset role="radiogroup" aria-labelledby="base-layers-heading">\n          ${t.map(t=>{const s=e[t.id]||{img:t.thumbnailUrl??"",label:t.name,title:t.name};t.thumbnailUrl&&(s.img=t.thumbnailUrl);const n=t.id.toUpperCase().replace(/-/g,""),r=pi(t,this.accessContext);return`\n                <div>\n                  <label for="baselayer-${Li(n)}" title="${Li(s.title)}">\n                    <input \n                      type="radio" \n                      id="baselayer-${Li(n)}" \n                      value="${Li(n)}" \n                      name="baselayer" \n                      data-layer="${Li(t.id)}"\n                      ${i?.id===t.id?"checked":""}\n                      ${r?"":"disabled"}\n                    />\n                    <figure class="vrmap-baselayer-thumbnail">\n                      <img width="100" src="${Li(s.img)}" alt="${Li(s.label)}" />\n                    </figure>\n                    <span>${Li(s.label)}</span>\n                  </label>\n                </div>\n              `}).join("")}\n        </fieldset>\n      </section>\n    `}renderOverlays(){const t=this.layerManager.getGroups(),i=this.layerManager.getOverlayLayers().filter(t=>!t.group);if(0===t.length&&0===i.length)return"";let e=`\n      <section class="vrmap-overlay-selector">\n        <strong class="vrmap-h5" id="overlays-heading">\n          ${Li(Q("layers.overlays"))}\n        </strong>\n        <fieldset role="group" aria-labelledby="overlays-heading">\n          <div class="vrmap-block-list">\n    `;return t.forEach(t=>{e+=this.renderOverlayGroup(t)}
1),i.forEach(t=>{e+=this.renderOverlayItem(t)}),e+="\n          </div>\n        </fieldset>\n      </section>\n    ",e}getGroupName(t){return{enneigement:Q("layers.snow"),"neige-fraiche":Q("layers.freshSnow")}[t]||this.formatGroupName(t)}getGroupDescription(t){return{enneigement:Q("layers.snowDescription"),"neige-fraiche":Q("layers.freshSnowDescription")}[t]||""}getLayerName(t,i){return{snowcover:Q("layers.today"),"snowcover-24h":Q("layers.tomorrow"),"snowcover-48h":Q("layers.dayAfterTomorrow"),freshsnow:Q("layers.today"),"freshsnow-24h":Q("layers.tomorrow"),"freshsnow-48h":Q("layers.dayAfterTomorrow")}[t.toLowerCase()]||i}renderOverlayGroup(t){const i=this.layerManager.getOverlaysByGroup(t),e=this.layerManager.isGroupActive(t),s=this.layerManager.getActiveOverlayInGroup(t),n=i.some(t=>pi(t,this.accessContext)),r=i.some(t=>mi(t,this.accessContext)),o=this.getGroupName(t),a=this.getGroupDescription(t);return`\n      <div class="vrmap-block-list--item">\n        <div class="vrmap-form-switch${n?"":" vrmap-form-switch--disabled"}">\n          <div class="vrmap-form-switch--label">\n            <label for="GROUP_${Li(t)}">\n              ${r?'<i class="vr-icon vr-icon-premium-macaron text-premium" aria-hidden="true"></i> ':""}${Li(o)}\n              ${a?`<i class="vr-icon vr-icon-information-sign vrmap-alpha--50" title="${Li(a)}"></i>`:""}\n            </label>\n          </div>\n          <div class="vrmap-form-switch--input">\n            <input type="hidden" name="overlays" value="0" />\n            <input \n              autocomplete="off" \n              type="checkbox" \n              id="GROUP_${Li(t)}" \n              name="overlays" \n              data-group="${Li(t)}"\n              ${e?"checked":""}\n              ${n?"":"disabled"}\n            />\n          </div>\n        </div>\n\n        <div class="vrmap-block-list--collapsible" id="GROUP-${Li(t)}">\n          <div class="vrmap-map-segmented-group vrmap-map-segmented-group--sm vrmap-map-segmented-group--fill">\n            ${i.map((i,e)=>{const n=pi(i,this.accessContext);return`\n              <div class="vrmap-segmented-item">\n                <input \n                  ${0===e?"checked":""} \n                  autocomplete="off" \n                  id="${Li(i.id)}" \n                  type="radio" \n                  name="${Li(t)}" \n                  data-overlay="${Li(i.id)}" \n                  data-in-group="${Li(t)}"\n                  ${s?.id===i.id?"checked":""}\n                  ${n?"":"disabled"}\n                />\n                <label for="${Li(i.id)}">${Li(this.getLayerName(i.id,i.name))}</label>\n              </div>\n            `}).join("")}\n          </div>\n        </div>\n      </div>\n    `}renderOverlayItem(t){const i=this.layerManager.isOverlayVisible(t.id),e=pi(t,this.accessContext),s=mi(t,this.accessContext),n=this.getOverlayName(t.id,t.name),r=this.getOverlayDescription(t.id,t.description);return`\n      <div class="vrmap-block-list--item">\n        <div class="vrmap-form-switch${e?"":" vrmap-form-switch--disabled"}">\n          <div class="vrmap-form-switch--label">\n            <label for="${Li(t.id)}">\n              ${s?'<i class="vr-icon vr-icon-premium-macaron text-premium" aria-hidden="true"></i> ':""}${Li(n)}\n              ${r?`<i class="vr-icon vr-icon-information-sign vrmap-alpha--50" title="${Li(r)}"></i>`:""}\n            </label>\n          </div>\n          <div class="vrmap-form-switch--input">\n            <input type="hidden" name="overlays" value="0" />\n            <input \n              autocomplete="off" \n              type="checkbox" \n              id="${Li(t.id)}" \n              name="overlays" \n              data-overlay="${Li(t.id)}"\n              ${i?"checked":""}\n              ${e?"":"disabled"}\n            />\n          </div>\n        </div>\n      </div>\n    `}getOverlayName(t,i){return{slopes:Q("layers.slopes"),mappatou:Q("layers.mappatou")}[t.toLowerCase()]||i}getOverlayDescription(t,i){return{slopes:Q("layers.slopesDescription"),mappatou:Q("layers.mappatouDescription")}[t.toLowerCase()]||i}attachEventListeners(){if(!this.panelElement)return;this.panelElement.addEventListener("change",t=>{const i=t.target;"baselayer"===i.name&&i.dataset.layer?this.handleBaseLayerChange(i.dataset.layer):i.dataset.overlay&&i.dataset.inGroup?this.handleGroupOverlayChange(i.dataset.overlay,i.dataset.inGroup,i.checked):i.dataset.overlay?this.handleOverlayChange(i.dataset.overlay,i.checked):i.dataset.group&&this.handleGroupToggle(i.dataset.group,i.checked)}),this.container.addEventListener("vrmap:baselayererror",t=>{const i=t.detail?.previousLayerId;i&&(this.layerManager.syncBaseLayerState(i),this.updateBaseLayerVisualState())});const t=this.panelElement.querySelector(".vrmap-close-panel");t&&t.addEventListener("click",()=>this.toggle());const i=this.panelElement.querySelector("[data-premium-btn]");i&&i.addEventListener("click",()=>{this.tracker.trackEvent("Premium","Layers panel Premium CTA","Click on link Discover Premium in layers panel")});const e=this.panelElement.querySelector("[data-login-btn]");e&&e.addEventListener("click",()=>{this.tracker.trackEvent("Login","Layers panel Login CTA","Click on link Login in layers panel")})}handleBaseLayerChange(t){this.layerManager.setBaseLayer(t),this.tracker.trackEvent("Layers panel","Change base layer",t)}handleOverlayChange(t,i){i?(this.layerManager.showOverlay(t),this.tracker.trackEvent("Layers panel","Toggle overlay",`Show overlay ${t}`)):(this.layerManager.hideOverlay(t),this.tracker.trackEvent("Layers panel","Toggle overlay",`Close overlay ${t}`)),this.updateLegends()}handleGroupOverlayChange(t,i,e){e&&(this.layerManager.showOverlay(t),this.tracker.trackEvent("Layers panel","Toggle overlay",`Show overlay ${t} in group ${i}`)),this.updateLegends()}handleGroupToggle(t,i){const e=this.panelElement?.querySelector(`input[data-group="${$i(t)}"]`)?.closest(".vrmap-block-list--item");if(e){if(i){e.classList.add("vrmap-is-visible"),e.setAttribute("aria-expanded","true");const i=this.layerManager.getOverlaysByGroup(t);
1if(i.length>0){const t=i[0];if(t){this.layerManager.showOverlay(t.id);const i=e.querySelector(`input[type="radio"][data-overlay="${$i(t.id)}"]`);i&&(i.checked=!0)}}this.tracker.trackEvent("Layers panel","Toggle overlay",`Show overlays group ${t}`)}else e.classList.remove("vrmap-is-visible"),e.setAttribute("aria-expanded","false"),this.layerManager.getOverlaysByGroup(t).forEach(t=>{this.layerManager.hideOverlay(t.id)}),e.querySelectorAll(".vrmap-block-list--collapsible input[data-overlay]:checked").forEach(t=>{t.checked=!1}),this.tracker.trackEvent("Layers panel","Toggle overlay",`Hide overlays group ${t}`);this.updateLegends()}}updateLegends(){this.panelElement&&this.panelElement.querySelectorAll(".layer-legend").forEach(t=>{const i=t.dataset.layerLegend;i&&(this.layerManager.getGroups().includes(i)?t.style.display=this.layerManager.isGroupActive(i)?"block":"none":t.style.display=this.layerManager.isOverlayVisible(i)?"block":"none")})}toggle(){this.isOpen=!this.isOpen,this.panelElement&&(this.isOpen?this.panelElement.classList.add("vrmap-is-open"):this.panelElement.classList.remove("vrmap-is-open")),this.tracker.trackEvent("Layers panel","Toggle layers panel",(this.isOpen?"Open":"Close")+" layers panel")}updateBaseLayerVisualState(){if(!this.panelElement)return;const t=this.layerManager.getCurrentBaseLayer();if(!t)return;this.panelElement.querySelectorAll('input[type="radio"][name="baselayer"]').forEach(t=>{t.checked=!1});const i=this.panelElement.querySelector(`input[type="radio"][data-layer="${$i(t.id)}"]`);i&&(i.checked=!0,i.offsetHeight)}formatGroupName(t){return t.replace(/[_-]/g," ").replace(/\b\w/g,t=>t.toUpperCase())}}const Oi={defaultOpen:!1,enableTracking:!1,isPremium:!1,userGid:0,loginUrl:"/index.php?component=user&task=loginForm",premiumUrl:"https://www.visorando.com/premium.html"};class ki{constructor(t){this.panel=t}container=null;button=null;onAdd(t){return this.container=document.createElement("div"),this.container.className="maplibregl-ctrl maplibregl-ctrl-group",this.button=this.createButton(),this.container.appendChild(this.button),this.container}onRemove(){this.container?.parentNode?.removeChild(this.container),this.container=null,this.button=null}getDefaultPosition(){return"top-right"}createButton(){const t=document.createElement("button");t.type="button",t.className="maplibregl-ctrl-icon vrmap-maplibregl-ctrl-layers",t.setAttribute("aria-label",Q("controls.layersAriaLabel")),t.setAttribute("title",Q("controls.toggleLayers")),t.setAttribute("aria-expanded","false");const i=()=>{this.panel.toggle();const i="true"===t.getAttribute("aria-expanded");t.setAttribute("aria-expanded",i?"false":"true")};return t.addEventListener("click",t=>{t.preventDefault(),t.stopPropagation(),i()}),t.addEventListener("keydown",t=>{"Enter"!==t.key&&" "!==t.key||(t.preventDefault(),i())}),t}}class xi{container;layerManager;legends;legendElement=null;constructor(t,i,e){this.container=t,this.layerManager=i,this.legends=e}init(){this.render(),this.update(),this.layerManager.on(()=>this.update())}buildEntryHTML(t){const i=t.title??(t.titleKey?Q(t.titleKey):t.key),e=t.table?Object.entries(t.table).map(([t,i])=>this.buildRowHTML(t,i)).join(""):Object.entries(t.data?.table??{}).map(([t,i])=>this.buildRowHTML(t,Q(i))).join("");return`<div class="layer-legend" data-layer-legend="${t.key}" style="display:none"><strong>${i}</strong>${e}</div>`}buildRowHTML(t,i){return`<div><span style="display:inline-block;width:1em;height:1em;flex:0 0 1em;background:${t};vertical-align:middle;margin-right:0.3em;border-radius:2px;"></span>${i}</div>`}render(){const t=document.createElement("div");t.className="map-layers-legend",t.innerHTML=this.legends.map(t=>this.buildEntryHTML(t)).join("")+"<br/>",this.container.appendChild(t),this.legendElement=t}update(){this.legendElement&&this.legendElement.querySelectorAll(".layer-legend").forEach(t=>{const i=t.dataset.layerLegend??"",e=this.legends.find(t=>t.key===i);if(!e)return;const s=e.isGroup?this.layerManager.isGroupActive(i):this.layerManager.isOverlayVisible(i);t.style.display=s?"block":"none"})}}class Ai{static BEFORE_WAYPOINTS_LAYER="bike-directions-layer";static ARROW_ICON_URL="https://www.visorando.com/img/fiches/direction.svg";adapter;renderedTrails=new Set;defaultStyle;constructor(t,i){this.adapter=t,this.defaultStyle=i?{...i}:{...Pi}}setDefaultStyle(t){this.defaultStyle=t}getDefaultStyle(){return{...this.defaultStyle}}render(t,i={}){const e={...this.defaultStyle,...i},s=this.getSourceId(t.id),n=this.getOutlineLayerId(t.id),r=this.getLayerId(t.id),o=this.trailToGeoJSON(t);if(this.renderedTrails.has(t.id))this.adapter.updateSource(s,o);else{if(this.adapter.addSource(s,o),e.outlineWidth>0){const t={id:n,type:"line",source:s,paint:{"line-color":e.outlineColor,"line-width":e.width+2*e.outlineWidth,"line-opacity":e.opacity},layout:{"line-cap":"round","line-join":"round"}};this.adapter.addLayer(t,Ai.BEFORE_WAYPOINTS_LAYER)}const i={id:r,type:"line",source:s,paint:{"line-color":e.color,"line-width":e.width,"line-opacity":e.opacity},layout:{"line-cap":"round","line-join":"round"}};if(this.adapter.addLayer(i,Ai.BEFORE_WAYPOINTS_LAYER),e.showDirection){const i=this.getArrowLayerId(t.id),n={id:i,type:"symbol",source:s,minzoom:11,layout:{"symbol-placement":"line","symbol-spacing":e.arrowSpacing??150,"icon-image":"arrow","icon-size":e.arrowSize??.5,"icon-rotate":0,"icon-rotation-alignment":"map","icon-allow-overlap":!0,"icon-ignore-placement":!1},paint:{"icon-opacity":e.opacity}};this.ensureArrowIcon().then(()=>{this.adapter.hasSource(s)&&!this.adapter.hasLayer(i)&&this.adapter.addLayer(n,Ai.BEFORE_WAYPOINTS_LAYER)}).catch(()=>{})}this.renderedTrails.add(t.id)}}remove(t){if(!this.renderedTrails.has(t))return;const i=this.getSourceId(t),e=this.getOutlineLayerId(t),s=this.getLayerId(t),n=this.getArrowLayerId(t);this.adapter.removeLayer(n),this.adapter.removeLayer(s),this.adapter.removeLayer(e),this.adapter.removeSource(i),this.renderedTrails.delete(t)}resetState(){this.renderedTrails.clear()}trailToGeoJSON(t){const i=t.getPath(),e=t.getWaypoints(),s=new Set;e.forEach(t=>{if(t.isStage()){let e=0,n=Number.MAX_VALUE;
1i.forEach((i,s)=>{const r=i.position.lat-t.position.lat,o=i.position.lng-t.position.lng,a=Math.sqrt(r*r+o*o);a<n&&(n=a,e=s)}),s.add(e)}});const n=Array.from(s).sort((t,i)=>t-i),r=[];for(let l=0;l<n.length-1;l++){const t=n[l],i=n[l+1];void 0!==t&&void 0!==i&&i===t+1&&r.push({start:t,end:i})}const o=[];let a,h=[];for(let l=0;l<i.length;l++){const t=i[l];if(!t)continue;const e=r.find(t=>t.start===l);e?(h.push([t.position.lng,t.position.lat]),h.length>1&&o.push(h),l=e.end-1,h=[]):h.push([t.position.lng,t.position.lat])}return h.length>1&&o.push(h),a=0===o.length?{type:"LineString",coordinates:[]}:1===o.length&&o[0]?{type:"LineString",coordinates:o[0]}:{type:"MultiLineString",coordinates:o},{type:"FeatureCollection",features:[{type:"Feature",geometry:a,properties:{id:t.id,pathPointCount:i.length,waypointCount:t.waypointCount}}]}}getSourceId(t){return`trail-source-${t}`}getOutlineLayerId(t){return`trail-outline-layer-${t}`}getLayerId(t){return`trail-layer-${t}`}getArrowLayerId(t){return`trail-arrow-layer-${t}`}async ensureArrowIcon(){if(!this.adapter.isInitialized()||this.adapter.hasImage("arrow"))return;const t=new Image;t.crossOrigin="anonymous",t.src=Ai.ARROW_ICON_URL;try{await t.decode()}catch{return}const i=window.devicePixelRatio||1,e=Math.round(30*i),s=document.createElement("canvas");s.width=e,s.height=e;const n=s.getContext("2d");n&&(n.drawImage(t,0,0,e,e),this.adapter.addImage("arrow",n.getImageData(0,0,e,e),{sdf:!1,pixelRatio:i}))}}class Ti{static BIKE_INDICATION_ICON_URL="https://www.visorando.com/img/fiches/indication.svg";static BIKE_SOURCE="bike-directions-source";static BIKE_LAYER="bike-directions-layer";static WAYPOINTS_SOURCE="waypoints-source";adapter;popupHandle=null;typeColors;bikeDirectionImageBaseUrl;webViewBridge;renderedWaypoints=new Set;bikeWaypoints=new Map;regularWaypoints=new Map;initializedIconLayers=new Set;registeredClickLayers=new Set;bikeClickHandlerRegistered=!1;constructor(t,i,e,s,n){this.adapter=t,this.typeColors=e??Ei,this.bikeDirectionImageBaseUrl=s??"https://www.visorando.com/images/velo/directions/",this.webViewBridge=n??null}async renderMultiple(t,i={}){const e=[],s=[];for(const a of t)a.type===r.BIKE_DIRECTION||a.type===r.BIKE_DIRECTION_INFO?e.push(a):s.push(a);const n=new Set(s.map(t=>this.getIconName(t)));if(await Promise.all([...n].map(t=>this.ensureIconLoaded(t))),e.length>0){for(const t of e)this.bikeWaypoints.set(t.id,t),this.renderedWaypoints.add(t.id);this.flushBikeLayer(i)}let o=1;for(const a of s)a.type===r.STAGE?(this.regularWaypoints.set(a.id,{waypoint:a,number:-1}),this.renderedWaypoints.add(a.id),o=1):a.type===r.WAYPOINT?(this.regularWaypoints.set(a.id,{waypoint:a,number:o}),this.renderedWaypoints.add(a.id),o++):(this.regularWaypoints.set(a.id,{waypoint:a,number:-1}),this.renderedWaypoints.add(a.id));s.length>0&&await this.flushRegularLayers(i),s.some(t=>t.htmlContent&&!1!==i.enablePopup)&&this.ensureRegularClickHandlers(i)}async render(t,i={}){if(t.type===r.BIKE_DIRECTION||t.type===r.BIKE_DIRECTION_INFO)this.bikeWaypoints.set(t.id,t),this.renderedWaypoints.add(t.id),this.flushBikeLayer(i);else{await this.ensureIconLoaded(this.getIconName(t));const e=i.waypointNumber??0;this.regularWaypoints.set(t.id,{waypoint:t,number:e}),this.renderedWaypoints.add(t.id),await this.flushRegularLayers(i),t.htmlContent&&!1!==i.enablePopup&&this.ensureRegularClickHandlers(i)}}resetState(){this.renderedWaypoints.clear(),this.bikeWaypoints.clear(),this.regularWaypoints.clear(),this.initializedIconLayers.clear(),this.registeredClickLayers.clear(),this.bikeClickHandlerRegistered=!1}async removeByTrail(t){let i=!1;for(const[e,s]of this.bikeWaypoints)s.trailId===t&&(this.bikeWaypoints.delete(e),this.renderedWaypoints.delete(e),i=!0);for(const[e,s]of this.regularWaypoints)s.waypoint.trailId===t&&(this.regularWaypoints.delete(e),this.renderedWaypoints.delete(e),i=!0);i&&(this.closePopup(),this.flushBikeLayer({}),await this.flushRegularLayers({}))}closePopup(){this.popupHandle?.remove(),this.popupHandle=null}flushBikeLayer(t){if(!this.adapter.isInitialized())return;const i=this.buildBikeGeoJSON();this.adapter.hasSource(Ti.BIKE_SOURCE)&&this.adapter.setSourceData(Ti.BIKE_SOURCE,i),!this.bikeClickHandlerRegistered&&this.adapter.hasLayer(Ti.BIKE_LAYER)&&(this.registerBikeClickHandler(),this.bikeClickHandlerRegistered=!0)}buildBikeGeoJSON(){const t=[];for(const i of this.bikeWaypoints.values())t.push({type:"Feature",geometry:{type:"Point",coordinates:[i.position.lng,i.position.lat]},properties:{id:i.id,color:this.getColorForType(i.type),elevation:i.elevation.toMeters()}});return{type:"FeatureCollection",features:t}}registerBikeClickHandler(){if(!this.adapter.isInitialized())return;const t=Ti.BIKE_LAYER;this.adapter.onLayerClick(t,t=>{const i=t.features?.[0]?.properties?.id;if(!i)return;const e=this.bikeWaypoints.get(i);e&&this.showBikePopup(e)}),this.adapter.onLayerMouseEnter(t,()=>{this.adapter.setCursor("pointer")}),this.adapter.onLayerMouseLeave(t,()=>{this.adapter.setCursor("")})}
1showBikePopup(t){if(this.webViewBridge)return void this.webViewBridge.sendCustomEvent("waypointClicked",{waypointId:t.id,latitude:t.position.lat,longitude:t.position.lng,elevation:t.elevation.meters,wptTitle:t.wptTitle,wptText:t.wptText,indications:t.htmlContent,type:t.type});const i=t.getBikeDirectionImageUrl(this.bikeDirectionImageBaseUrl),e=t.raison?`<div class="content-type-i"><img height="28" width="28" alt="" src="${Ti.BIKE_INDICATION_ICON_URL}">${t.raison}</div>`:"",s=`<div style="display:flex;gap:10px;align-items:flex-start;">${i?`<img height="100" width="100" alt="Direction vélo" src="${i}" onerror="this.style.display='none'">`:""}<div style="flex:1;">${t.htmlContent??""}${e}</div></div>`;this.popupHandle&&this.popupHandle.remove(),this.popupHandle=this.adapter.showPopup({lngLat:[t.position.lng,t.position.lat],html:s,maxWidth:"280px",className:"point",closeButton:!0,closeOnClick:!1})}async flushRegularLayers(t){if(!this.adapter.isInitialized())return;const i=new Map;for(const{waypoint:r,number:o}of this.regularWaypoints.values()){const t=this.getIconName(r);i.has(t)||i.set(t,[]),i.get(t).push({type:"Feature",geometry:{type:"Point",coordinates:[r.position.lng,r.position.lat]},properties:{id:r.id,icon:t,waypointNumber:o,hasPopup:r.htmlContent?1:0,elevation:r.elevation.toMeters()}})}const e=Ti.WAYPOINTS_SOURCE,s=[];for(const r of i.values())s.push(...r);const n={type:"FeatureCollection",features:s};this.adapter.hasSource(e)&&this.adapter.setSourceData(e,n);for(const r of i.keys())this.initializedIconLayers.has(r)||(await this.ensureIconLoaded(r),this.initializedIconLayers.add(r))}ensureRegularClickHandlers(t){if(this.adapter.isInitialized())for(const i of this.initializedIconLayers){const t=`waypoints-symbol-${i}`;this.registeredClickLayers.has(t)||(this.registeredClickLayers.add(t),this.adapter.onLayerClick(t,t=>{const i=t.features?.[0]?.properties?.id;if(!i)return;const e=this.regularWaypoints.get(i);e&&e.waypoint.htmlContent&&this.showRegularPopup(e.waypoint)}),this.adapter.onLayerMouseEnter(t,()=>{this.adapter.setCursor("pointer")}),this.adapter.onLayerMouseLeave(t,()=>{this.adapter.setCursor("")}))}}showRegularPopup(t){this.webViewBridge?this.webViewBridge.sendCustomEvent("waypointClicked",{waypointId:t.id,latitude:t.position.lat,longitude:t.position.lng,elevation:t.elevation.meters,wptTitle:t.wptTitle,wptText:t.wptText,indications:t.htmlContent,type:t.type}):t.htmlContent&&(this.popupHandle&&this.popupHandle.remove(),this.popupHandle=this.adapter.showPopup({lngLat:[t.position.lng,t.position.lat],html:t.htmlContent,maxWidth:"280px",className:"point",closeButton:!0,closeOnClick:!1}))}async ensureIconLoaded(t){if(!this.adapter.isInitialized()||this.adapter.hasImage(t))return;const i=this.resolveIconUrl(t);if(!i)return;const e=new Image;e.crossOrigin="anonymous",e.src=i;try{await e.decode()}catch{return}const s=window.devicePixelRatio||1,n=Math.round(30*s),r=Math.round(50*s),o=document.createElement("canvas");o.width=n,o.height=r;const a=o.getContext("2d");a&&(a.drawImage(e,0,0,n,r),this.adapter.addImage(t,a.getImageData(0,0,n,r),{sdf:!1,pixelRatio:s}))}resolveIconUrl(t){const i=`waypoints-symbol-${t}`,e=this.adapter.getStyle(),s=e?.layers?.find(t=>t.id===i);return s?.metadata?.["visorando:icon-url"]}getIconName(t){switch(t.type){case r.STAGE:return"waypoint-stage";case r.START:return t.isStartEnd?"waypoint-startend":"waypoint-start";case r.END:return"waypoint-end";default:return"waypoint-normal"}}getColorForType(t){const i={[r.START]:"start",[r.END]:"end",[r.WAYPOINT]:"waypoint",[r.BIKE_DIRECTION]:"bikeDirection",[r.BIKE_DIRECTION_INFO]:"bikeDirectionInfo",[r.STAGE]:"stage"};return this.typeColors[i[t]]}}const Pi={color:"#FF6B35",width:2,opacity:.9,showDirection:!0,outlineColor:"#FFFFFF",outlineWidth:1.5,arrowColor:"#000000",arrowSize:.5,arrowSpacing:150},Ei={start:"#4CAF50",end:"#F44336",waypoint:"#2196F3",bikeDirection:"#82a714",bikeDirectionInfo:"#8057b5",stage:"#FF9800"};class Ri{static SOURCE_ID="markers-source";static OUTER_LAYER="markers-points-outer";static INNER_LAYER="markers-points-inner";static HALO_STROKE="#e41f1f";static HALO_FILL="rgba(228,31,31,.3)";static DEFAULT_COLOR="#000000";static COUNT_PREFIX="act_";adapter;added=!1;interactionsBound=!1;clusterListenersBound=!1;lastData={type:"FeatureCollection",features:[]};lastOptions={};activityColors=new Map;currentClusterRadius=0;clusterMarkersOnScreen={};constructor(t){this.adapter=t}render(t,i={}){this.lastData=Array.isArray(t)?this.toGeoJSON(t,i):t,this.lastOptions=i;const e=this.adapter.getMap();if(!e)throw new Error("MarkersRenderer.render() requires an initialized map");this.activityColors=new Map;for(const s of this.lastData.features){const t=s.properties?.activityId,i=s.properties?.color;"number"==typeof t&&t>=0&&"string"==typeof i&&""!==i&&this.activityColors.set(t,i)}this.added&&this.adapter.hasSource(Ri.SOURCE_ID)?this.adapter.updateSource(Ri.SOURCE_ID,this.lastData):this.addSourceAndLayers(e,this.clusterRadiusForZoom(e.getZoom())),this.bindInteractions(e),this.bindClusterListeners(e),this.updateClusterMarkers(e)}getBounds(){const t=this.lastData.features.map(t=>t.geometry?.coordinates).filter(t=>Array.isArray(t)&&t.length>=2);if(0===t.length)return null;const i=t.map(t=>t[0]),e=t.map(t=>t[1]);return[[Math.min(...i),Math.min(...e)],[Math.max(...i),Math.max(...e)]]}resetState(){this.added=!1}reRenderAfterStyleReload(){0!==this.lastData.features.length&&(this.resetState(),this.render(this.lastData,this.lastOptions))}addSourceAndLayers(t,i){const e=!1!==this.lastOptions.cluster;this.adapter.addSourceRaw(Ri.SOURCE_ID,{type:"geojson",data:this.lastData,cluster:e,clusterMa
1xZoom:t.getMaxZoom(),clusterRadius:i,clusterProperties:this.buildClusterProperties()});for(const s of this.buildLayers())this.adapter.hasLayer(s.id)||this.adapter.addLayer(s);this.currentClusterRadius=i,this.added=!0}buildClusterProperties(){const t={};for(const i of this.activityColors.keys())t[Ri.COUNT_PREFIX+i]=["+",["case",["==",["get","activityId"],i],1,0]];return t}buildLayers(){const t=["!=",["get","cluster"],!0];return[{id:Ri.OUTER_LAYER,type:"circle",source:Ri.SOURCE_ID,filter:t,paint:{"circle-stroke-color":Ri.HALO_STROKE,"circle-stroke-width":2,"circle-radius":8,"circle-color":Ri.HALO_FILL}},{id:Ri.INNER_LAYER,type:"circle",source:Ri.SOURCE_ID,filter:t,paint:{"circle-color":["get","color"],"circle-radius":4}}]}toGeoJSON(t,i){const e=i.color??Ri.DEFAULT_COLOR;return function(t,i={}){const e={type:"FeatureCollection"};return i.id&&(e.id=i.id),i.bbox&&(e.bbox=i.bbox),e.features=t,e}(t.map(t=>c([t.lng,t.lat],{id:t.id,title:t.title??"",url:t.url??"",activityId:t.activityId??-1,color:t.color??e})))}clusterRadiusForZoom(t){const i=Math.floor(t);return i<=10?100:i<=12?60:i<=15?30:10}bindClusterListeners(t){this.clusterListenersBound||!1===this.lastOptions.cluster||(t.on("data",i=>{i.sourceId===Ri.SOURCE_ID&&i.isSourceLoaded&&this.updateClusterMarkers(t)}),t.on("move",()=>this.updateClusterMarkers(t)),t.on("moveend",()=>{this.applyClusterRadius(t),this.updateClusterMarkers(t)}),this.clusterListenersBound=!0)}applyClusterRadius(t){if(!this.added||!1===this.lastOptions.cluster)return;const i=this.clusterRadiusForZoom(t.getZoom());if(i!==this.currentClusterRadius){this.removeClusterMarkers();for(const t of[Ri.INNER_LAYER,Ri.OUTER_LAYER])this.adapter.hasLayer(t)&&this.adapter.removeLayer(t);this.adapter.hasSource(Ri.SOURCE_ID)&&this.adapter.removeSource(Ri.SOURCE_ID),this.addSourceAndLayers(t,i)}}updateClusterMarkers(t){if(!1===this.lastOptions.cluster||!this.adapter.hasSource(Ri.SOURCE_ID))return;let e;try{e=t.querySourceFeatures(Ri.SOURCE_ID)}catch{return}const s=e.filter(t=>t.properties?.cluster).map(t=>Number(t.properties?.point_count??0)),n={};for(const r of e){const e=r.properties??{};if(!e.cluster)continue;const o=String(e.cluster_id);if(n[o])continue;const a=this.clusterMarkersOnScreen[o];if(a){n[o]=a;continue}const h=r.geometry.coordinates,l=this.createDonut(e,s);l.addEventListener("click",i=>{i.stopPropagation(),this.zoomToCluster(t,Number(e.cluster_id),h)}),n[o]=new i.Marker({element:l}).setLngLat(h).addTo(t)}for(const[i,r]of Object.entries(this.clusterMarkersOnScreen))n[i]||r.remove();this.clusterMarkersOnScreen=n}removeClusterMarkers(){for(const t of Object.values(this.clusterMarkersOnScreen))t.remove();this.clusterMarkersOnScreen={}}createDonut(t,i){const e=Number(t.point_count??0),s=4+String(e).length,n=Math.max(22.5,Math.sqrt(this.scaleCount(e,i))),r=n-s,o=[];let a=0;const h=this.sumActivities(t)||e,l=[...this.activityColors.entries()].map(([i,e])=>({color:e,count:Number(t[Ri.COUNT_PREFIX+i]??0)})).filter(t=>t.count>0).sort((t,i)=>i.count-t.count);for(const u of l){const t=a/h;a+=u.count,o.push(this.donutSegment(t,a/h,n,r,this.escapeHtml(u.color)))}if(0===o.length){const t=this.lastOptions.color??Ri.DEFAULT_COLOR;o.push(this.donutSegment(0,.9999,n,r,this.escapeHtml(t)))}const c=document.createElement("div");return c.className="visorando-cluster",c.style.cursor="pointer",c.innerHTML=`<svg width="${2*n}" height="${2*n}" viewBox="0 0 ${2*n} ${2*n}" text-anchor="middle" style="display:block">\n${o.join("\n")}\n<circle cx="${n}" cy="${n}" r="${r}" fill="rgba(0, 0, 0, 0.7)" />\n<text dominant-baseline="central" transform="translate(${n}, ${n})" fill="#FFFFFF" font-size="13" font-family="sans-serif">${this.escapeHtml(String(t.point_count_abbreviated??e))}</text>\n</svg>`,c}sumActivities(t){let i=0;for(const e of this.activityColors.keys())i+=Number(t[Ri.COUNT_PREFIX+e]??0);return i}scaleCount(t,i){const e=Math.min(...i),s=Math.max(...i);return Number.isFinite(e)&&Number.isFinite(s)&&s!==e?500+(t-e)*(s-500)/(s-e):500}donutSegment(t,i,e,s,n){const r=i-t===1?i-1e-5:i,o=2*Math.PI*(t-.25),a=2*Math.PI*(r-.25),h=Math.cos(o),l=Math.sin(o),c=Math.cos(a),u=Math.sin(a),d=r-t>.5?1:0;return`<path d="M ${e+s*h} ${e+s*l} L ${e+e*h} ${e+e*l} A ${e} ${e} 0 ${d} 1 ${e+e*c} ${e+e*u} L ${e+s*c} ${e+s*u} A ${s} ${s} 0 ${d} 0 ${e+s*h} ${e+s*l}" fill="${n}" />`}zoomToCluster(t,i,e){const s=t.getSource(Ri.SOURCE_ID);s?.getClusterExpansionZoom(i).then(i=>{const s=i<=t.getZoom()?Math.min(t.getZoom()+1,t.getMaxZoom()):i;t.easeTo({center:e,zoom:s})})}bindInteractions(t){this.interactionsBound||(t.on("click",Ri.OUTER_LAYER,e=>{const s=e.features?.[0];if(!s)return;const n=s.geometry.coordinates.slice(),r=s.properties??{},o=String(r.title??""),a=String(r.url??""),h={id:r.id,lat:n[1],lng:n[0],title:o,url:a,activityId:Number(r.activityId??-1),color:String(r.color??"")},l=this.lastOptions.onMarkerClick;if(l)return void l(h,n);const c=this.escapeHtml(o),u=""===a?c:`<a href="${this.escapeHtml(a)}">${c}</a>`;""!==u&&new i.Popup({offset:12,maxWidth:"280px"}).setLngLat(n).setHTML(`<div class="visorando-marker-popup">${u}</div>`).addTo(t)}),t.on("mouseenter",Ri.OUTER_LAYER,()=>{t.getCanvas().style.cursor="pointer"}),t.on("mouseleave",Ri.OUTER_LAYER,()=>{t.getCanvas().style.cursor=""}),this.interactionsBound=!0)}escapeHtml(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}}class Ni{static FIT_PADDING={top:120,right:60,bottom:60,left:60};static FIT_MIN_ZOOM=10;adapter;api;trailRenderer;waypointRenderer;autoClose;openTrail=null;popupHandle=null;requestSeq=0;
1cursorBeforeLoading="";constructor(t,i={}){this.adapter=t,this.api=new bi(void 0===i.apiBaseUrl?{}:{baseUrl:i.apiBaseUrl}),this.autoClose=!1!==i.autoClose;const e={...Pi};i.trailColor&&(e.color=i.trailColor),i.trailWidth&&(e.width=i.trailWidth),this.trailRenderer=new Ai(t,e),this.waypointRenderer=new Ti(t)}async toggle(t,i){const e=String(t.id);if(this.openTrail?.id===e)return void this.close();this.closePopup(),this.autoClose&&this.removeTrail();const s=++this.requestSeq;let n;this.setBusy(!0);try{const t=await this.api.fetchTrail(e);n=gi.parseTrail(t,e)}catch(r){return void(s===this.requestSeq&&(this.setBusy(!1),this.showPopup(i,this.getFallbackHtml(t))))}s===this.requestSeq&&(this.setBusy(!1),this.trailRenderer.render(n),this.openTrail={id:e,trail:n,lngLat:i},this.showPopup(i,this.getSummaryHtml(n,t)),this.fitTrail(n),this.renderWaypoints(n,s))}close(){this.closePopup(),this.removeTrail()}reRenderAfterStyleReload(){if(!this.openTrail)return;const t=this.openTrail.trail;this.trailRenderer.resetState(),this.trailRenderer.render(t),this.waypointRenderer.resetState(),Bi(this.waypointRenderer.renderMultiple([...t.getWaypoints()]))}async renderWaypoints(t,i){try{await this.waypointRenderer.renderMultiple([...t.getWaypoints()])}catch(e){return}i!==this.requestSeq&&Bi(this.waypointRenderer.removeByTrail(t.id))}destroy(){this.requestSeq++,this.close()}getSummaryHtml(t,i){const e=t.getWaypoints(),s=e.find(t=>(t.type===r.START||t.isStartEnd)&&t.htmlContent);return s?.htmlContent??e.find(t=>t.htmlContent)?.htmlContent??this.getFallbackHtml(i)}getFallbackHtml(t){const i=Ui(t.title??"");return t.url?`<a href="${Ui(t.url)}" class="h4">${i}</a>`:i}showPopup(t,i){""!==i&&(this.closePopup(),this.waypointRenderer.closePopup(),this.popupHandle=this.adapter.showPopup({lngLat:t,html:`<div class="visorando-marker-popup">${i}</div>`,maxWidth:"320px",closeButton:!0,closeOnClick:!0,offset:12}))}closePopup(){this.popupHandle?.remove(),this.popupHandle=null}removeTrail(){this.openTrail&&(this.trailRenderer.remove(this.openTrail.id),Bi(this.waypointRenderer.removeByTrail(this.openTrail.id)),this.openTrail=null)}fitTrail(t){const i=this.adapter.getMap(),e=t.getPath();if(!i||0===e.length)return;const s=e.map(t=>t.position.lat),n=e.map(t=>t.position.lng),r=Math.min(...n),o=Math.min(...s),a=Math.max(...n),h=Math.max(...s),l=[[r,o],[a,h]],c=Ni.FIT_PADDING,u=i.getZoom();if(u<Ni.FIT_MIN_ZOOM)return void i.fitBounds(l,{padding:c,maxZoom:Ni.FIT_MIN_ZOOM,duration:600});const d=i.getContainer(),f=i.unproject([c.left,d.clientHeight-c.bottom]),p=i.unproject([d.clientWidth-c.right,c.top]);r>=f.lng&&a<=p.lng&&o>=f.lat&&h<=p.lat||i.fitBounds(l,{padding:c,maxZoom:u,duration:600})}setBusy(t){const i=this.adapter.getMap()?.getCanvas();if(i)return t?(this.cursorBeforeLoading=i.style.cursor,void(i.style.cursor="progress")):void(i.style.cursor=this.cursorBeforeLoading)}}function Bi(t){t.catch(()=>{})}function Ui(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}class Ii{adapter;layerManager;layerPanel=null;enableTracking;isPremium;showOverlayLegends;userGid;loginUrl;premiumUrl;constructor(t,i,e,s,n=!1,r=!1,o=0,a=Mi.loginUrl,h=Mi.premiumUrl){this.adapter=t,this.layerManager=i,this.enableTracking=s,this.isPremium=n,this.showOverlayLegends=r,this.userGid=o,this.loginUrl=a,this.premiumUrl=h}static buildMapConfig(t){const i={container:t.container,zoom:t.zoom??Mi.zoom,baseLayer:t.baseLayer??Mi.baseLayer,enablePitch:t.enablePitch??Mi.enablePitch,enableRotation:t.enableRotation??Mi.enableRotation,enable3DMode:t.enable3DMode??Mi.enable3DMode,showMouseCoordinates:t.showMouseCoordinates??Mi.showMouseCoordinates,coordinateFormat:t.coordinateFormat??Mi.coordinateFormat,elevationUnit:t.elevationUnit??Mi.elevationUnit,showControls:t.showControls??Mi.showControls,stylesBaseUrl:t.stylesBaseUrl??Mi.stylesBaseUrl,enableTracking:t.enableTracking??Mi.enableTracking};return t.customStyleUrl&&(i.customStyleUrl=t.customStyleUrl),void 0!==t.catalog&&(i.catalog=t.catalog),t.catalogUrl&&(i.catalogUrl=t.catalogUrl),void 0!==t.fullscreenContainer&&(i.fullscreenContainer=t.fullscreenContainer),t.center&&(i.center=t.center),void 0!==t.maxTileC
1acheSize&&(i.maxTileCacheSize=t.maxTileCacheSize),void 0!==t.renderWorldCopies&&(i.renderWorldCopies=t.renderWorldCopies),void 0!==t.fadeDuration&&(i.fadeDuration=t.fadeDuration),void 0!==t.minZoom&&(i.minZoom=t.minZoom),void 0!==t.maxZoom&&(i.maxZoom=t.maxZoom),void 0!==t.minPitch&&(i.minPitch=t.minPitch),void 0!==t.maxPitch&&(i.maxPitch=t.maxPitch),i}initializeLayerSelectorUI(t,i){const e="string"==typeof t?document.getElementById(t):t;e&&this.adapter.onLoad(()=>{if(!this.layerManager)return;if(!this.adapter.isInitialized())return;const{baseLayers:t,overlayLayers:s}=this.adapter.extractLayerDefinitions(),n={userGid:this.userGid,isPremium:this.isPremium},r=yi(t,n).map(t=>b.create(t));this.layerManager.registerLayers(r);const o=yi(s,n).map(t=>b.create(t));this.layerManager.registerLayers(o),this.layerPanel=new Fi({container:e,layerManager:this.layerManager,defaultOpen:!1,enableTracking:this.enableTracking,isPremium:this.isPremium,userGid:this.userGid,loginUrl:this.loginUrl,premiumUrl:this.premiumUrl});const a=new ki(this.layerPanel);if(this.adapter.addControl(a,"top-right"),this.showOverlayLegends){const t=this.adapter.getCatalogLegends()??function(t){const i=[],e=new Set;for(const s of t){const t=s.metadata;if(!t)continue;if("overlay"!==t["visorando:category"])continue;if(!t["visorando:legend"])continue;const n=t["visorando:legend"],r=t["visorando:legendTitleKey"]??"",o=t["visorando:group"];if(o){if(e.has(o))continue;e.add(o),i.push({key:o,isGroup:!0,titleKey:r,data:n})}else{const t=s.id.replace(/-layer$/,"").toUpperCase();i.push({key:t,isGroup:!1,titleKey:r,data:n})}}return i}(this.adapter.getMap()?.getStyle()?.layers??[]);new xi(e,this.layerManager,t).init()}this.layerManager.on(i);const h=this.adapter.getBaseLayer(),l=this.layerManager.getAllLayers().find(t=>t.id===h&&t.isBaseLayer());l&&this.layerManager&&this.layerManager.syncBaseLayerState(l.id)})}}class Di{adapter;webViewBridge;mapMoveListenerSetup=!1;mapTapListenerSetup=!1;constructor(t,i){this.adapter=t,this.webViewBridge=i}setupMapMoveEndListener(){!this.mapMoveListenerSetup&&this.webViewBridge&&this.adapter.isInitialized()&&(this.adapter.onMapEvent("movestart",t=>{if(!this.webViewBridge)return;const i=void 0!==t.originalEvent;this.webViewBridge.sendCustomEvent("mapMoveStart",{isUserInteraction:i})}),this.adapter.onMapEvent("moveend",t=>{if(!this.webViewBridge)return;const i=this.adapter.getCenter(),e=this.adapter.getZoom(),s=this.adapter.getBearing(),n=this.adapter.getPitch(),r=void 0!==t.originalEvent;this.webViewBridge.sendCustomEvent("mapMoved",{latitude:i.lat,longitude:i.lng,zoom:e,bearing:s,pitch:n,isUserInteraction:r})}),this.mapMoveListenerSetup=!0)}setupMapTapListener(){!this.mapTapListenerSetup&&this.webViewBridge&&this.adapter.isInitialized()&&(this.adapter.onMapEvent("click",t=>{this.webViewBridge&&t.point&&0===this.adapter.queryRenderedFeatures(t.point).filter(t=>{const i=t.layer.id;return i.includes("waypoint")||i.includes("marker")}).length&&t.lngLat&&this.webViewBridge.sendCustomEvent("mapTapped",{latitude:t.lngLat.lat,longitude:t.lngLat.lng})}),this.mapTapListenerSetup=!0)}isMapMoveListenerSetup(){return this.mapMoveListenerSetup}}class Gi{adapter;layerManager;layerChangeListenerSetup=!1;styleReloadListenerSetup=!1;trailRenderer=null;waypointRenderer=null;currentTrail=null;showTrailOutline;userGid;isPremium;constructor(t,i,e,s=0,n=!1){this.adapter=t,this.layerManager=i,this.showTrailOutline=e,this.userGid=s,this.isPremium=n}setRenderers(t,i,e){this.trailRenderer=t,this.waypointRenderer=i,this.currentTrail=e}setupLayerChangeListeners(){this.layerChangeListenerSetup||this.layerManager&&(this.adapter.onLoad(()=>{this.layerManager.on(t=>{if("base-changed"===t.type){const i=this.layerManager.getAllLayers().find(i=>i.id===t.layerId);i&&(this.adapter.setBaseLayerFromMapLayer(i),this.layerManager.markLayerLoaded(i.id))}else if("overlay-shown"===t.type){const i=this.layerManager.getAllLayers().find(i=>i.id===t.layerId);i&&this.showOverlayOnMap(i)}else if("overlay-hidden"===t.type){const i=this.layerManager.getAllLayers().find(i=>i.id===t.layerId);i&&this.hideOverlayOnMap(i)}});const t=this.adapter.getBaseLayer(),i=this.layerManager.getAllLayers().find(i=>i.id===t&&i.isBaseLayer());i&&this.layerManager&&this.layerManager.syncBaseLayerState(i.id)}),this.layerChangeListenerSetup=!0)}setupStyleReloadListener(){this.styleReloadListenerSetup||(this.adapter.on("style.reloaded",t=>{if(this.trailRenderer&&this.trailRenderer.resetState(),this.waypointRenderer&&this.waypointRenderer.resetState(),this.currentTrail&&this.trailRenderer){const t=this.showTrailOutline?void 0:{outlineWidth:0};this.trailRenderer.render(this.currentTrail,t)}if(this.currentTrail&&this.waypointRenderer){const t=this.currentTrail.getWaypoints();this.waypointRenderer.renderMultiple([...t])}this.reExtractAndApplyOverlays()}),this.styleReloadListenerSetup=!0)}extractAndRegisterLayers(){if(!this.layerManager)return;const{baseLayers:t,overlayLayers:i}=this.adapter.extractLayerDefinitions(),e={userGid:this.userGid,isPremium:this.isPremium};this.layerManager.registerLayers(yi(t,e).map(t=>b.create(t))),this.layerManager.registerLayers(yi(i,e).map(t=>b.create(t)))}reExtractAndApplyOverlays(t){if(!this.layerManager)return;if(!this.adapter.isInitialized())return;const i=new Set(this.layerManager.getOverlayLayers().filter(t=>this.layerManager.isOverlayVisible(t.id)).map(t=>
1t.id.toUpperCase())),{baseLayers:e,overlayLayers:s}=this.adapter.extractLayerDefinitions(),n={userGid:this.userGid,isPremium:this.isPremium};this.layerManager.registerLayers(yi(e,n).map(t=>b.create(t))),this.layerManager.registerLayers(yi(s,n).map(t=>b.create(t)));const r=t??[...i];r.length>0&&this.layerManager.setActiveOverlays(r,i)}getOverlayBeforeId(){const t=this.adapter.getStyle();if(!t?.layers)return;const i=t.layers.find(t=>"summits-labels"===t.id);if(i)return i.id;const e=t.layers.find(t=>t.id.startsWith("trail-outline-layer-")||t.id.startsWith("trail-layer-"));return e?.id}showOverlayOnMap(t){if(!this.adapter.isInitialized())return;if(t.styleUrl)return void this.adapter.showCatalogOverlay(t.id,t.styleUrl).catch(t=>{});if(!t.source)return;const i=`${t.id.toLowerCase()}-source`,e=`${t.id.toLowerCase()}-layer`,s=this.getOverlayBeforeId();if(this.adapter.hasSource(i)||this.adapter.addSourceRaw(i,t.source),this.adapter.hasLayer(e))this.adapter.setLayoutProperty(e,"visibility","visible"),this.adapter.moveLayer(e,s);else{const n={id:e,source:i,type:t.type};t.paint&&(n.paint=t.paint),this.adapter.addLayer(n,s)}}hideOverlayOnMap(t){if(!this.adapter.isInitialized())return;if(t.styleUrl)return void this.adapter.hideCatalogOverlay(t.id);const i=`${t.id.toLowerCase()}-layer`;this.adapter.hasLayer(i)&&this.adapter.setLayoutProperty(i,"visibility","none")}}const _i="elevation-minimum",zi="elevation-maximum",ji="elevation-trail-data-background";class Hi{container;chartContainer;resetZoomButton;chart=null;trail;options;distanceUnit;elevationUnit;comparativeScale;primaryColor;chartData=[];trailPoints=[];slopeAreas=[];hoverMoveListener=null;hoverLeaveListener=null;clickListener=null;hoverFrame=null;pendingHoverClientX=null;lastHoveredPointIndex=-1;suppressNextPointClick=!1;isComparativeFullView=!0;isApplyingComparativeScale=!1;isApplyingInitialLongTrailFocus=!1;initialLongTrailFocusApplied=!1;navigatorVisible=!1;comparativeScaleFrame=null;rangeSelectionTimeout=null;constructor(t){if(this.options=t,this.trail=t.trail,this.distanceUnit=t.distanceUnit??"km",this.elevationUnit=t.elevationUnit??"m",this.primaryColor=t.seriesColor??"#3B82F6",this.comparativeScale=t.comparativeScale??!0,"string"==typeof t.container){const i=document.getElementById(t.container);if(!i)throw new Error(`Container element with id "${t.container}" not found`);this.container=i}else this.container=t.container;this.chartContainer=document.createElement("div"),this.chartContainer.style.width="100%";const i=t.height??300;this.chartContainer.style.height="string"==typeof i?i:`${i}px`,this.resetZoomButton=this.createResetZoomButton(),this.render()}render(){this.container.innerHTML="",this.container.style.position="relative",this.container.appendChild(this.chartContainer),this.container.appendChild(this.resetZoomButton),this.createChart()}getDistanceLabel(){return"mi"===this.distanceUnit?"mi":"km"}getElevationLabel(){return"ft"===this.elevationUnit?"ft":"m"}createResetZoomButton(){const t=document.createElement("button");return t.type="button",t.className="btn btn--sm btn-secondary",t.textContent=Q("elevation.chart.resetZoom"),t.style.position="absolute",t.style.top="0",t.style.right="0",t.style.zIndex="2",t.style.display="none",t.style.background="#FFFFFF",t.addEventListener("click",()=>{this.chart?.xAxis[0]?.setExtremes(void 0,void 0)}),t}setResetZoomButtonVisible(t){this.resetZoomButton.style.display=t?"block":"none"}setNavigatorVisible(t){return!(!this.chart||this.navigatorVisible===t||(this.navigatorVisible=t,this.chart.update({navigator:{enabled:t},scrollbar:{enabled:t}},!1),0))}findClosestPointIndex(t){let i=0,e=this.chartData.length-1;for(;i<=e;){const s=Math.floor((i+e)/2),n=this.chartData[s]?.[0]??0;if(n<t)i=s+1;else{if(!(n>t))return s;e=s-1}}if(i<=0)return 0;if(i>=this.chartData.length)return Math.max(0,this.chartData.length-1);const s=this.chartData[i-1]?.[0]??0,n=this.chartData[i]?.[0]??s;return Math.abs(s-t)<=Math.abs(n-t)?i-1:i}buildElevationExtremaPlotLines(t,i){const e=Math.max(0,Math.min(t,i)),s=Math.min(this.chartData.length-1,Math.max(t,i));let n=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(let h=e;h<=s;h++){const t=this.chartData[h]?.[1];void 0!==t&&(n=Math.min(n,t),r=Math.max(r,t))}if(!Number.isFinite(n)||!Number.isFinite(r))return[];const o=this.getElevationLabel(),a=(t,i,e)=>({id:t,value:i,color:"rgba(122,122,122,0.5)",dashStyle:"LongDash",width:1,zIndex:4,label:{text:e,align:"right",x:-8,y:-6,style:{color:"rgba(122,122,122,0.75)",fontSize:"11px",fontWeight:"500"}}});return n===r?[a(_i,n,`Min./max. ${n.toFixed(0)} ${o}`)]:[a(_i,n,`Min. ${n.toFixed(0)} ${o}`),a(zi,r,`Max. ${r.toFixed(0)} ${o}`)]}updateElevationExtremaPlotLines(t,i){const e=this.chart?.yAxis[0];if(e){e.removePlotLine(_i),e.removePlotLine(zi);for(const s of this.buildElevationExtremaPlotLines(t,i))e.addPlotLine(s)}}scheduleRangeSelection(t,i){this.cancelRangeSelection(),this.rangeSelectionTimeout=window.setTimeout(()=>{this.rangeSelectionTimeout=null,this.updateElevationExtremaPlotLines(t,i),this.options.onRangeSelect?.(t,
1i)},120)}cancelRangeSelection(){null!==this.rangeSelectionTimeout&&(window.clearTimeout(this.rangeSelectionTimeout),this.rangeSelectionTimeout=null)}convertDistanceForDisplay(t){return"mi"===this.distanceUnit?f(t,"meters","miles"):t/1e3}convertElevation(t){return"ft"===this.elevationUnit?f(t,"meters","feet"):t}getMetersPerElevationUnit(){return"ft"===this.elevationUnit?.3048:1}buildChartData(t){let i=Number.NEGATIVE_INFINITY;const e=t.every((t,e)=>{const s=t.distanceFromStartMeters;return!(void 0===s||!Number.isFinite(s)||s<0||s<i||0===e&&0!==s||(i=s,0))}),s=[];let n=0;return t.forEach((i,r)=>{const o=e?i.distanceFromStartMeters??0:n;if(s.push([o,this.convertElevation(i.elevation?.toMeters()??0)]),e)return;const a=t[r+1];a&&(n+=i.position.distanceTo(a.position))}),s}buildWaypointMarkerData(t){if(0===this.chartData.length)return[];const i=[];for(const e of this.trail.getWaypoints()){if(e.type!==t||void 0===e.distanceFromStartMeters)continue;const s=this.chartData[this.findClosestPointIndex(e.distanceFromStartMeters)];s&&i.push([s[0],s[1]])}return i}buildWaypointMarkerSeries(t,i){return{type:"scatter",data:this.buildWaypointMarkerData(t),color:i,enableMouseTracking:!1,showInNavigator:!1,dataGrouping:{enabled:!1},marker:{enabled:!1},dataLabels:{enabled:!0,format:"▼",allowOverlap:!0,crop:!1,overflow:"allow",verticalAlign:"bottom",y:4,style:{color:i,fontSize:"11px",textOutline:"none"}}}}buildTrailDataBackgroundPlotBands(){const t=this.chartData[0]?.[0],i=this.chartData[this.chartData.length-1]?.[0];return void 0===t||void 0===i||t>=i?[]:[{id:ji,from:t,to:i,color:"#ffffff",zIndex:0}]}refreshTrailDataBackground(){const t=this.chart?.xAxis[0];if(t){t.removePlotBand(ji);for(const i of this.buildTrailDataBackgroundPlotBands())t.addPlotBand(i)}}getChartDataBounds(){const t=this.chartData[0]?.[0],i=this.chartData[this.chartData.length-1]?.[0];if(void 0===t||void 0===i||i<=t)return null;let e=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY;for(const[,n]of this.chartData)e=Math.min(e,n),s=Math.max(s,n);return Number.isFinite(e)&&Number.isFinite(s)?{firstDistance:t,lastDistance:i,minimumElevation:e,maximumElevation:s,distanceRangeMeters:i-t,elevationRangeMeters:(s-e)*this.getMetersPerElevationUnit()}:null}calculateComparativeLayoutMetrics(t,i,e=this.getChartDataBounds()){const s=e;if(!s||t<=0||i<=0)return null;const n=t/s.distanceRangeMeters,r=s.elevationRangeMeters>0?i/(10*s.elevationRangeMeters):n,o=Math.min(n,r),a=Math.min(1,Math.max(0,10*s.elevationRangeMeters*o/i));return{verticalOccupancy:a,longCompressed:s.distanceRangeMeters>=5e4&&a<.65}}findFirstUsableStageDistance(){const t=this.chartData[0]?.[0];if(void 0===t||this.trailPoints.length!==this.chartData.length)return null;const i=new Set;for(const e of this.trail.getWaypoints()){if(!e.isStage())continue;let t=0,s=Number.POSITIVE_INFINITY;this.trailPoints.forEach((i,n)=>{const r=i.position.lat-e.position.lat,o=i.position.lng-e.position.lng,a=r*r+o*o;a<s&&(s=a,t=n)}),i.add(t)}for(const e of[...i].sort((t,i)=>t-i)){const i=this.chartData[e]?.[0];if(void 0===i)continue;const s=i-t;if(s>=5e3&&s<=5e4)return i}return null}applyInitialLongTrailFocus(t){if(!t?.longCompressed||this.initialLongTrailFocusApplied||!this.chart)return;const i=this.getChartDataBounds(),e=this.chart.xAxis[0],s=this.chart.yAxis[0];if(!i||!e||!s)return;const n=this.findFirstUsableStageDistance(),r=Math.min(5e4,Math.max(1e4,i.distanceRangeMeters*t.verticalOccupancy/.65)),o=Math.min(i.lastDistance,n??i.firstDistance+r);if(o<=i.firstDistance||o>=i.lastDistance)this.initialLongTrailFocusApplied=!0;else{this.initialLongTrailFocusApplied=!0,this.isComparativeFullView=!1,this.isApplyingInitialLongTrailFocus=!0;try{this.setNavigatorVisible(!0),s.setExtremes(void 0,void 0,!1,!1),e.setExtremes(i.firstDistance,o,!0,!1,{trigger:"initial-long-trail-focus"}),this.setResetZoomButtonVisible(!0),this.updateElevationExtremaPlotLines(this.findClosestPointIndex(i.firstDistance),this.findClosestPointIndex(o))}finally{this.isApplyingInitialLongTrailFocus=!1}}}scheduleFullViewComparativeScale(){if(!this.comparativeScale||!this.isComparativeFullView||this.isApplyingComparativeScale||null!==this.comparativeScaleFrame)return;const t=this.chart,i=t?.xAxis[0],e=t?.yAxis[0];this.comparativeScaleFrame=requestAnimationFrame(()=>{this.comparativeScaleFrame=null,this.chart===t&&t?.xAxis[0]===i&&t?.yAxis[0]===e&&this.applyFullViewComparativeScale()})}applyFullViewComparativeScale(){if(!this.chart||!this.isComparativeFullView||this.isApplyingComparativeScale||this.chartData.length<2)return;const t=this.chart.xAxis[0],i=this.chart.yAxis[0],e=this.chart.plotWidth,s=this.chart.plotHeight;if(!t||!i||e<=0||s<=0)return;const n=this.getChartDataBounds();if(!n)return;const r=this.calculateComparativeLayoutMetrics(e,s,n),o=this.getMetersPerElevationUnit(),a=n.distanceRangeMeters*s/(10*e),h=Math.max(n.elevationRangeMeters,a),l=h*e*10/s,c=n.elevationRangeMeters/h*s,u=Math.max(1,s-24),d=Math.max(1,c/u),f=l*d,p=h/o*d,m=(n.firstDistance+n.lastDistance)/2,y=(n.minimumElevation+n.maximumElevation)/2;this.isApplyingComparativeScale=!0;try{t.setExtremes(m-f/2,m+f/2,!1,!1),i.setExtremes(y-p/2,y+p/2,!1,!1),this.chart.redraw(!1)}finally{this.isApplyingComparativeScale=!1}this.applyInitialLongTrailFocus(r)}createChart(){const t=this.trail.getPath(),i=this.trail.getElevationAreas(),s=this.buildChartData(t);let n=[];const o=[];i&&i.length>0&&(n=i.map(t=>{const i={color:`rgb(${t.color})`,fillColor:`rgba(${t.color}, 0.65)`};
1if(void 0!==t.endDistanceMeters&&(i.value=t.endDistanceMeters),void 0!==t.averageSlopePercent){const i={averageSlopePercent:t.averageSlopePercent};void 0!==t.endDistanceMeters&&(i.value=t.endDistanceMeters),o.push(i)}return i})),this.chartData=s,this.trailPoints=t,this.slopeAreas=o;const a=this.primaryColor,h=s.reduce((t,[,i])=>Math.min(t,i),Number.POSITIVE_INFINITY),l=this,c={chart:{type:"area",backgroundColor:"transparent",plotBackgroundColor:"rgba(0,0,0,0.05)",spacing:[0,0,10,10],height:this.options.height||300,zooming:{type:"x",mouseWheel:{enabled:!1}},panning:{enabled:!0,type:"x"},panKey:"shift",events:{render:function(){l.scheduleFullViewComparativeScale()},selection:function(t){return t.xAxis?.length&&(l.suppressNextPointClick=!0,l.setNavigatorVisible(!0)),!0}}},title:{text:""},credits:{enabled:!1},xAxis:{plotBands:this.buildTrailDataBackgroundPlotBands(),showLastLabel:!0,labels:{overflow:"justify",formatter:function(){const t="number"==typeof this.value?this.value:Number(this.value),i=this.axis.getExtremes();return"number"==typeof i.dataMin&&t<i.dataMin||"number"==typeof i.dataMax&&t>i.dataMax?"":`${l.convertDistanceForDisplay(t).toFixed(1)} ${l.getDistanceLabel()}`}},minRange:100,ordinal:!1,events:{afterSetExtremes:function(t){if(l.isApplyingComparativeScale)return;const i=this.getExtremes();if("number"!=typeof i.dataMin||"number"!=typeof i.dataMax)return;const e=i.dataMax-i.dataMin,s=Math.max(1e-9*e,Number.EPSILON);if(i.min>i.dataMin+s||i.max<i.dataMax-s){const e=l.isApplyingInitialLongTrailFocus||"initial-long-trail-focus"===t?.trigger;return l.setNavigatorVisible(!0),l.isComparativeFullView&&(l.isComparativeFullView=!1,this.chart.yAxis[0]?.setExtremes(void 0,void 0,!0,!1)),l.setResetZoomButtonVisible(!0),void(e||l.scheduleRangeSelection(l.findClosestPointIndex(i.min),l.findClosestPointIndex(i.max)))}const n=!l.isComparativeFullView;l.cancelRangeSelection(),l.isComparativeFullView=!0,l.updateElevationExtremaPlotLines(0,l.chartData.length-1),l.scheduleFullViewComparativeScale(),l.setResetZoomButtonVisible(!1),n&&l.options.onResetZoom?.(),l.setNavigatorVisible(!1)&&this.chart.redraw()}}},yAxis:{opposite:!1,gridLineColor:"rgba(0,0,0,0.1)",labels:{align:"right",x:-8,formatter:function(){const t="number"==typeof this.value?this.value:Number(this.value);return h>=0&&t<0?"":`${t} ${l.getElevationLabel()}`}},tickPositioner:function(){const t=this.tickPositions??[];return h<0?t:t.filter(t=>t>=0)},plotLines:this.buildElevationExtremaPlotLines(0,s.length-1)},tooltip:{shared:!0,useHTML:!0,formatter:function(){const t=this.points?.[0];if(!t)return"";const i=t.x,e=l.convertDistanceForDisplay(i),s=t.y??0,n=l.slopeAreas.find(t=>void 0===t.value||i<=t.value);let r='<div style="padding: 5px;">';if(r+=`<b>${Q("elevation.chart.distance")}:</b> ${e.toFixed(2)} ${l.getDistanceLabel()}<br/>`,r+=`<b>${Q("elevation.chart.elevation")}:</b> ${s.toFixed(0)} ${l.getElevationLabel()}<br/>`,n){const t=n.averageSlopePercent>0?"+":"";r+=`<b>${Q("elevation.chart.slope")}:</b> ${t}${n.averageSlopePercent.toFixed(1)}%<br/>`}return r+="</div>",r}},navigator:{enabled:!1,height:40,margin:10,series:{type:"area",lineWidth:1,fillOpacity:.3,dataGrouping:{enabled:!0,forced:!0,groupPixelWidth:2}},xAxis:{labels:{formatter:function(){const t="number"==typeof this.value?this.value:parseFloat(this.value);return`${l.convertDistanceForDisplay(t).toFixed(1)} ${l.getDistanceLabel()}`}}}},scrollbar:{enabled:!1,liveRedraw:!1,height:8,barBorderRadius:4},rangeSelector:{enabled:!1},plotOptions:{area:{fillOpacity:.5,lineWidth:3,dataGrouping:{enabled:!0,forced:!0,groupPixelWidth:2},marker:{enabled:!1,states:{hover:{enabled:!0,radius:5}}},states:{hover:{lineWidth:3}}},series:{states:{inactive:{enabled:!1}},point:{events:{}}}},series:[{type:"area",name:"Altitude",data:s,lineColor:a,lineWidth:3,threshold:null,zoneAxis:"x",zones:n.length>0?n:void 0,fillOpacity:.5},this.buildWaypointMarkerSeries(r.WAYPOINT,"#147EB3"),this.buildWaypointMarkerSeries(r.STAGE,"#E5A81C")],legend:{enabled:!1}};this.chart=e.stockChart(this.chartContainer,c);const u=this.chart,d=u.xAxis[0],f=u.yAxis[0];requestAnimationFrame(()=>{this.chart===u&&u.xAxis[0]===d&&u.yAxis[0]===f&&(u.reflow(),this.scheduleFullViewComparativeScale())}),this.attachHoverListeners()}attachHoverListeners(){if(this.detachHoverListeners(),!this.chart)return;const t=this.options.onHover,i=this.options.onClick,e=t=>{if(!this.chart)return null;const i=t-this.chartContainer.getBoundingClientRect().left,e=this.chart.plotLeft,s=this.chart.plotWidth;if(i<e-5||i>e+s+5)return null;const n=this.chart.xAxis[0];if(!n)return null;const r=n.toValue(i,!1);if("number"!=typeof r||isNaN(r))return null;const o=this.chartData[0]?.[0]??0,a=this.chartData[this.chartData.length-1]?.[0]??0;return Math.max(o,Math.min(a,r))};t&&(this.hoverMoveListener=i=>{this.pendingHoverClientX=i.clientX,null===this.hoverFrame&&(this.hoverFrame=requestAnimationFrame(()=>{this.hoverFrame=null;const i=this.pendingHoverClientX;if(this.pendingHoverClientX=null,null===i)return;const s=e(i);if(null===s)return;const n=this.findClosestPointIndex(s);if(n===this.lastHoveredPointIndex)return;this.lastHoveredPointIndex=n;const r=this.trailPoints[n];r&&t(r,n)}))},this.hoverLeaveListener=()=>{null!==this.hoverFrame&&(cancelAnimationFrame(this.hoverFrame),this.hoverFrame=null),this.pendingHoverClientX=null,-1!==this.lastHoveredPointIndex&&(t(null,-1),this.lastHoveredPointIndex=-1)},this.chartContainer.addEventListener("mousemove",this.hoverMoveListener),this.chartContainer.addEventListener("mouseleave",this.hoverLeaveListener)),i&&(this.clickListener=t=>{if(this.suppressNextPointClick)return void(this.suppressNextPointClick=!1);const s=e(t.clientX);if(null===s)return;const n=this.findClosestPointIndex(s),r=this.trailPoints[n];r&&i(r,n)},this.chartContainer.addEventListener("click",this.clickListener))}detachHoverListeners(){null!==this.hoverFrame&&(cancelAnimationFrame(this.hoverFrame),this.hoverFrame=null),this.pendingHoverClientX=null,this.lastHoveredPointIndex=-1,this.hoverMoveListener&&(this.chartContainer.removeEventListener("mousemove",this.hoverMoveListener),this.hoverMoveListener=null),this.hoverLeaveListener&&(this.chartContainer.removeEventListener("mouseleave",this.hoverLeaveListener),this.hoverLeaveListener=null),this.clickListener&&(this.chartContainer.removeEventListener("click",this.clickListener),this.clickListener=null)}reflow(){this.chart?.reflow(),this.scheduleFullViewComparativeScale()}update(t){if(this.trail=t,!this.chart)return;this.cancelRangeSelection(),this.isComparativeFullView=!0,this.initialLongTrailFocusApplied=!1,this.setNavigatorVisible(!1),this.chart.xAxis[0]?.setExtremes(void 0,void 0,!1,!1),this.chart.yAxis[0]?.setExtremes(void 0,void 0,!1,!1);const i=this.trail.getPath(),e=this.buildChartData(i);this.chartData=e,this.trailPoints=i,this.refreshTrailDataBackgroun
1d(),this.chart.series[1]?.setData(this.buildWaypointMarkerData(r.WAYPOINT),!1),this.chart.series[2]?.setData(this.buildWaypointMarkerData(r.STAGE),!1),this.chart.series[0]?.setData(e,!0),this.updateElevationExtremaPlotLines(0,e.length-1),this.attachHoverListeners()}updateColor(t){this.primaryColor=t,this.chart?.series[0]&&this.chart.series[0].update({color:t,lineColor:t},!0)}destroy(){this.detachHoverListeners(),this.cancelRangeSelection(),null!==this.comparativeScaleFrame&&(cancelAnimationFrame(this.comparativeScaleFrame),this.comparativeScaleFrame=null),this.chart&&(this.chart.destroy(),this.chart=null),this.container.innerHTML=""}}const Wi=Object.freeze(Object.defineProperty({__proto__:null,ElevationChart:Hi},Symbol.toStringTag,{value:"Module"}));class Vi{static CHART_RANGE_FIT_PADDING=80;adapter;distanceUnit;elevationUnit;comparativeScale;elevationChart=null;trailPoints=[];highlightMarkerHandle=null;highlightMarkerElement=null;highlightMarkerPosition=null;constructor(t,i,e,s){this.adapter=t,this.distanceUnit=i,this.elevationUnit=e,this.comparativeScale=s}async createElevationChart(t,i,e){this.elevationChart&&(this.elevationChart.destroy(),this.destroyMapHighlight());const{ElevationChart:s}=await Promise.resolve().then(()=>Wi);this.trailPoints=i.getPath(),this.elevationChart=new s({container:t,trail:i,height:e,distanceUnit:this.distanceUnit,elevationUnit:this.elevationUnit,comparativeScale:this.comparativeScale,onHover:t=>{t?this.highlightPointOnMap(t):this.hideMapHighlight()},onClick:t=>{this.adapter.flyTo({center:[t.position.lng,t.position.lat],zoom:15,duration:1e3})},onRangeSelect:(t,i)=>{this.fitTrailRangeOnMap(t,i)},onResetZoom:()=>{this.fitTrailOnMap()}})}fitTrailRangeOnMap(t,i){const e=this.trailPoints,s=Math.max(0,Math.min(t,i)),n=Math.min(e.length-1,Math.max(t,i));this.fitPointsOnMap(s,n)}fitTrailOnMap(){this.fitPointsOnMap(0,this.trailPoints.length-1)}fitPointsOnMap(t,i){if(!this.adapter.isInitialized()||t>i)return;let e=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY,n=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(let o=t;o<=i;o++){const t=this.trailPoints[o];t&&(e=Math.min(e,t.position.lat),s=Math.max(s,t.position.lat),n=Math.min(n,t.position.lng),r=Math.max(r,t.position.lng))}this.adapter.fitBounds(new y(e,n),new y(s,r),Vi.CHART_RANGE_FIT_PADDING)}highlightPointOnMap(t){if(!this.adapter.isInitialized())return;const i=[t.position.lng,t.position.lat];if(this.highlightMarkerHandle&&this.highlightMarkerElement)return this.highlightMarkerElement.style.display="",void(this.highlightMarkerPosition?.[0]===i[0]&&this.highlightMarkerPosition[1]===i[1]||(this.highlightMarkerHandle.setLngLat(i),this.highlightMarkerPosition=i));const e=document.createElement("div");e.className="elevation-chart-highlight",this.highlightMarkerElement=e,this.highlightMarkerPosition=i,this.highlightMarkerHandle=this.adapter.addDomMarker({lngLat:i,element:e,anchor:"center"})}hideMapHighlight(){this.highlightMarkerElement&&(this.highlightMarkerElement.style.display="none")}destroyMapHighlight(){this.highlightMarkerHandle&&(this.highlightMarkerHandle.remove(),this.highlightMarkerHandle=null),this.highlightMarkerElement=null,this.highlightMarkerPosition=null}}class Ki{adapter;bikeDirectionImageBaseUrl;showTrailOutline;enable3DMode;webViewBridge;trailRenderer=null;waypointRenderer=null;constructor(t,i,e,s,n,r=null){this.adapter=t,this.bikeDirectionImageBaseUrl=i,this.showTrailOutline=e,this.enable3DMode=s,this.webViewBridge=r}initializeRenderers(t,i){if(this.trailRenderer){if(t||i){const e={...this.trailRenderer.getDefaultStyle()};t&&(e.color=t),i&&(e.width=i),this.trailRenderer.setDefaultStyle(e)}}else{let e;(t||i)&&(e={...Pi},t&&(e.color=t),i&&(e.width=i)),this.trailRenderer=new Ai(this.adapter,e)}this.waypointRenderer||(this.waypointRenderer=new Ti(this.adapter,void 0,void 0,this.bikeDirectionImageBaseUrl,this.webViewBridge))}async renderTrail(t,i,e){this.initializeRenderers(i,e);const s=this.showTrailOutline?{}:{outlineWidth:0};this.trailRenderer.render(t,s),await this.waypointRenderer.renderMultiple([...t.getWaypoints()])}fitTrailBounds(t,i,e,s){const n=t.getPath();if(0===n.length)return;const r=n.map(t=>[t.position.lng,t.position.lat]);this.adapter.setTrailPoints(r);let o=e;
1if(!this.enable3DMode||void 0!==e&&0!==e||(o=50),void 0!==o&&o>0)this.adapter.centerOnTrailWithOptimalView(o,s??0,1500);else{const t=n.map(t=>t.position.lat),e=n.map(t=>t.position.lng),r=new y(Math.min(...t),Math.min(...e)),a=new y(Math.max(...t),Math.max(...e));this.adapter.fitBounds(r,a,i,o,s)}}getTrailRenderer(){return this.trailRenderer}getWaypointRenderer(){return this.waypointRenderer}}class Zi{adapter;markerHandle=null;currentLocation=null;options;rotateHandler;constructor(t){this.adapter=t.adapter,this.options={markerColor:t.markerColor??"#4285F4",showAccuracy:t.showAccuracy??!0,accuracyColor:t.accuracyColor??"rgba(66, 133, 244, 0.2)",autoCenter:t.autoCenter??!1,autoCenterZoom:t.autoCenterZoom??16},this.rotateHandler=()=>{this.updateHeadingRotation()},this.adapter.on("rotate",this.rotateHandler)}updateHeadingRotation(){if(!this.markerHandle||void 0===this.currentLocation?.heading)return;const t=this.markerHandle.getElement().querySelector(".user-location-heading");if(t){const i=this.adapter.getBearing(),e=this.currentLocation.heading-i;t.style.transform=`translateX(-50%) rotate(${e}deg)`}}updateLocation(t){this.currentLocation=t,this.markerHandle?this.updateMarker(t):this.createMarker(t),this.options.showAccuracy&&t.accuracy&&this.updateAccuracyCircle(t),this.options.autoCenter&&this.adapter.flyTo({center:[t.longitude,t.latitude],zoom:this.options.autoCenterZoom,duration:500})}createMarker(t){const i=document.createElement("div");if(i.className="user-location-marker",i.style.setProperty("--vrmap-user-location-color",this.options.markerColor),i.innerHTML=`\n      <div class="user-location-dot"></div>\n      <div class="user-location-pulse"></div>\n      ${void 0!==t.heading?'<div class="user-location-heading"></div>':""}\n    `,void 0!==t.heading){const e=i.querySelector(".user-location-heading");if(e){const i=this.adapter.getBearing(),s=t.heading-i;e.style.transform=`translateX(-50%) rotate(${s}deg)`}}let e=[t.longitude,t.latitude];const s=this.adapter.addDomMarker({lngLat:e,element:i,anchor:"center"});this.markerHandle={remove:()=>s.remove(),getElement:()=>i,setLngLat:t=>{e=t,s.remove();const n=this.adapter.addDomMarker({lngLat:t,element:i,anchor:"center"});this.markerHandle.remove=()=>n.remove()}}}updateMarker(t){if(!this.markerHandle)return;this.markerHandle.setLngLat([t.longitude,t.latitude]);const i=this.markerHandle.getElement();if(void 0!==t.heading){const e=i.querySelector(".user-location-heading"),s=this.adapter.getBearing(),n=t.heading-s;if(e)e.style.transform=`translateX(-50%) rotate(${n}deg)`;else{const t=document.createElement("div");t.className="user-location-heading",t.style.transform=`translateX(-50%) rotate(${n}deg)`,i.appendChild(t)}}else i.querySelector(".user-location-heading")?.remove()}updateAccuracyCircle(t){if(!t.accuracy)return;const i="user-location-accuracy",e=t.accuracy/1e3,s=[];for(let r=0;r<64;r++){const i=r/64*2*Math.PI,n=e*Math.cos(i),o=e*Math.sin(i),a=t.latitude+o/111.32,h=t.longitude+n/(111.32*Math.cos(t.latitude*Math.PI/180));s.push([h,a])}s.push(s[0]);const n={type:"Feature",geometry:{type:"Polygon",coordinates:[s]},properties:{}};this.adapter.hasSource(i)?this.adapter.setSourceData(i,n):(this.adapter.addSourceRaw(i,{type:"geojson",data:n}),this.adapter.addLayer({id:"user-location-accuracy-layer",type:"fill",source:i,paint:{"fill-color":this.options.accuracyColor,"fill-opacity":.3}}))}}class qi{adapter;userLocationManager=null;applyOverlaysFn;applyBaseLayerFn;loadAndRenderTrailFn;constructor(t,i,e=t=>{},s=async t=>{}){this.adapter=t,this.loadAndRenderTrailFn=i,this.applyOverlaysFn=e,this.applyBaseLayerFn=s}handle(t,i,e){switch(t){case"updateLocation":this.handleLocationUpdate(i);break;case"createTrail":this.handleCreateTrail(i);break;case"centerOnUserLocation":this.handleCenterOnUserLocation(i,e);break;case"resetOrientation":this.handleResetOrientation(i);break;case"setLayers":this.handleSetLayers(i);break;case"setRecordingTrace":this.handleSetRecordingTrace(i)}}handleLocationUpdate(t){if(t){if(!this.userLocationManager){if(!this.adapter.isInitialized())return;this.userLocationManager=new Zi({adapter:this.adapter,markerColor:"#4285F4",showAccuracy:!0,autoCenter:!1})}this.userLocationManager.updateLocation(t)}}handleCreateTrail(t){const{trailId:i,options:e}=t||{};i&&this.loadAndRenderTrailFn({trailId:i,...e})}async handleCenterOnUserLocation(t,i){const{latitude:e,longitude:s,zoom:n,bearing:r,pitch:o,duration:a,baseLayer:h,overlays:l}=t||{};if("number"!=typeof e||"number"!=typeof s)return;const c={latitude:e,longitude:s,animate:!0};void 0!==n&&(c.zoom=n),void 0!==r&&(c.bearing=r),void 0!==o&&(c.pitch=o),void 0!==a&&(c.duration=a),void 0!==h&&(c.baseLayer=h),void 0!==l&&(c.overlays=l),await i.centerOnUserLocation(c)}handleResetOrientation(t){if(!this.adapter.isInitialized())return;const{duration:i,pitch:e,bearing:s}=t||{};this.adapter.easeTo({pitch:e??50,bearing:s??0,duration:i??1e3})}async handleSetLayers(t){const{baseLayer:i,overlays:e}=t||{};i&&await this.applyBaseLayerFn(i),e&&Array.isArray(e)&&this.applyOverlays(e)}handleSetRecordingTrace(t){const{points:i}=t||{};if(!i||!Array.isArray(i))return;if(!this.adapter.isInitialized())return;const e="recording-trace",s="recording-trace-layer",n="recording-trace-outline-layer";if(0===i.length)return this.adapter.hasSource(e)&&this.adapter.setSourceData(e,{type:"FeatureCollection",features:[]}),this.adapter.hasLayer(s)&&this.adapter.setLayoutProperty(s,"visibility","none"),void(this.adapter.hasLayer(n)&&this.adapter.setLayoutProperty(n,"visibility","none"));const r=i.map(t=>void 0!==t.altitude?[t.longitude,t.latitude,t.altitude]:[t.longitude,t.latitude]).filter(t=>null!==t);if(0===r.length)return;const o={type:"Feature",properties:{},geometry:{type:"LineString",coordinates:r}};this.adapter.hasSource(e)&&this.adapter.setSourceData(e,o),this.adapter.hasLayer(n)&&this.adapter.setLayoutProperty(n,"visibility","visible"),this.adapter.hasLayer(s)&&this.adapter.setLayoutProperty(s,"visibility","visible")}
1applyOverlays(t){this.applyOverlaysFn(t)}}const Yi="ABCDEFGHJKLMNOPQRSTUVWXYZ";class Ji{adapter;coordinateFormat;elevationUnit;tracker;popupHandle=null;isSetup=!1;constructor(t,i,e,s=new it){this.adapter=t,this.coordinateFormat=i,this.elevationUnit=e,this.tracker=s}setupContextMenuListener(){this.isSetup||(this.isSetup=!0,this.adapter.onMapEvent("contextmenu",t=>{t.originalEvent instanceof Event&&t.originalEvent.preventDefault(),t.lngLat&&this.handleContextMenu(t.lngLat.lat,t.lngLat.lng)}))}handleContextMenu(t,i){this.popupHandle&&(this.popupHandle.remove(),this.popupHandle=null),this.tracker.trackEvent("Context menu","Open context menu","Right-click on map");const e=vt(t,i,this.coordinateFormat),s=function(t,i){if(t<49.5||t>61.5||i<-9.5||i>2.5)return null;const[e,s,n]=function(t,i){const e=6378137,s=6356752.3142,n=1-s*s/(e*e),r=t*Math.PI/180,o=i*Math.PI/180,a=Math.sin(r),h=Math.cos(r),l=e/Math.sqrt(1-n*a*a);return[l*h*Math.cos(o),l*h*Math.sin(o),l*(1-n)*a]}(t,i),[r,o,a]=function(t,i,e){const s=-.1502*Math.PI/648e3,n=-.247*Math.PI/648e3,r=-.8421*Math.PI/648e3,o=204894e-10;return[t*(1+o)-446.448-i*r+e*n,125.157+t*r+i*(1+o)-e*s,-542.06-t*n+i*s+e*(1+o)]}(e,s,n),[h,l]=function(t,i,e){const s=6377563.396,n=6356256.909,r=1-n*n/(s*s),o=Math.sqrt(t*t+i*i);let a=Math.atan2(e,o*(1-r));for(let h=0;h<10;h++){const t=Math.sin(a),i=s/Math.sqrt(1-r*t*t),n=Math.atan2(e+r*i*t,o);if(Math.abs(n-a)<1e-12){a=n;break}a=n}return[180*a/Math.PI,180*Math.atan2(i,t)/Math.PI]}(r,o,a),[c,u]=function(t,i){const e=6377563.396,s=6356256.909,n=.9996012717,r=49*Math.PI/180,o=-2*Math.PI/180,a=t*Math.PI/180,h=i*Math.PI/180,l=1-s*s/(e*e),c=(e-s)/(e+s),u=c*c,d=c*c*c,f=Math.sin(a),p=Math.cos(a),m=Math.tan(a),y=f*f,w=m*m,v=w*w,g=e*n/Math.sqrt(1-l*y),b=e*n*(1-l)/Math.pow(1-l*y,1.5),M=g/b-1,S=h-o,C=S*S,L=C*S,$=L*S,F=p*p*p,O=F*p*p;return[4e5+g*p*S+g/6*F*(g/b-w)*L+g/120*O*(5-18*w+v+14*M-58*w*M)*($*S),s*n*(1.0016767257673973*(a-r)-(3*c+3*u+2.625*d)*Math.sin(a-r)*Math.cos(a+r)+(1.875*u+1.875*d)*Math.sin(2*(a-r))*Math.cos(2*(a+r))-35/24*d*Math.sin(3*(a-r))*Math.cos(3*(a+r)))-1e5+g/2*f*p*C+g/24*f*F*(5-w+9*M)*$+g/720*f*O*(61-58*w+v)*Math.pow(S,6)]}(h,l);return function(t,i){const e=Math.round(t),s=Math.round(i);if(e<0||e>7e5||s<0||s>13e5)return null;const n=Math.floor(e/1e5),r=Math.floor(s/1e5),o=19-r-(19-r)%5+Math.floor((n+10)/5),a=Yi[o],h=Yi[5*(19-r)%25+n%5];return a&&h?`${a}${h} ${String(Math.floor(e%1e5/100)).padStart(3,"0")} ${String(Math.floor(s%1e5/100)).padStart(3,"0")}`:null}(c,u)}(t,i),n=`vrmap-ctx-alt-${Date.now()}`,r=this.buildPopupHtml(e,s,n);this.popupHandle=this.adapter.showPopup({lngLat:[i,t],html:r,maxWidth:"300px",className:"vrmap-context-popup",closeButton:!0,closeOnClick:!1}),setTimeout(()=>{this.attachCopyListeners(e,s),this.updateElevation(t,i,n)},0)}buildPopupHtml(t,i,e){const s=Q("map.coordinates"),n=Q("contextMenu.altitude"),r=Q("contextMenu.copy"),o=Q("contextMenu.altitudeLoading"),a=i?`\n  <div class="vrmap-context-popup-block">\n    <span class="vrmap-context-popup-label">${Q("contextMenu.osGrid")}</span>\n    <div class="vrmap-context-popup-row">
1\n      <span class="vrmap-context-popup-value" data-vrmap-osgrid>${i}</span>\n      ${this.buildCopyButton("osgrid",r)}\n    </div>\n  </div>`:"";return`\n<div class="vrmap-context-popup-content">\n  <div class="vrmap-context-popup-block">\n    <span class="vrmap-context-popup-label">${s}</span>\n    <div class="vrmap-context-popup-row">\n      <span class="vrmap-context-popup-value" data-vrmap-coords>${t}</span>\n      ${this.buildCopyButton("coords",r)}\n    </div>\n  </div>${a}\n  <div class="vrmap-context-popup-block">\n    <span class="vrmap-context-popup-label">${n}</span>\n    <span class="vrmap-context-popup-value vrmap-context-popup-altitude vrmap-loading"\n          id="${e}">${o}</span>\n  </div>\n</div>`}buildCopyButton(t,i){return`<button class="vrmap-context-popup-copy-btn" data-vrmap-copy="${t}"\n        title="${i}" aria-label="${i}">\n        <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none"\n             stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n          <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>\n          <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>\n        </svg>\n      </button>`}attachCopyListeners(t,i){const e=document.querySelector(".vrmap-context-popup");if(!e)return;const s=e.querySelector('[data-vrmap-copy="coords"]');if(s&&s.addEventListener("click",()=>{this.copyToClipboard(t,s)}),i){const t=e.querySelector('[data-vrmap-copy="osgrid"]');t&&t.addEventListener("click",()=>{this.copyToClipboard(i,t)})}}async copyToClipboard(t,i){const e=Q("contextMenu.copied");try{if(navigator.clipboard)await navigator.clipboard.writeText(t);else{const i=document.createElement("textarea");i.value=t,i.style.cssText="position:fixed;top:-9999px;left:-9999px;opacity:0",document.body.appendChild(i),i.focus(),i.select(),document.execCommand("copy"),document.body.removeChild(i)}i.classList.add("vrmap-copied"),i.setAttribute("aria-label",e),i.innerHTML='\n              <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none"\n                   stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">\n                <polyline points="20 6 9 17 4 12"></polyline>\n              </svg>',setTimeout(()=>{i.isConnected&&(i.classList.remove("vrmap-copied"),i.setAttribute("aria-label",Q("contextMenu.copy")),i.innerHTML='\n                  <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none"\n                       stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">\n                    <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>\n                    <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>\n                  </svg>')},2e3)}catch{}}async updateElevation(t,i,e){let s,n=null,r=!1;try{n=await this.adapter.getElevationAtPoint(t,i)}catch{r=!0}if(r||null===n||isNaN(n))s=Q("contextMenu.altitudeUnavailable");else if("ft"===this.elevationUnit){const t=f(n,"meters","feet");s=`${Math.round(t)} ft`}else s=`${Math.round(n)} m`;const o=document.getElementById(e);o&&o.isConnected&&(o.classList.remove("vrmap-loading"),o.textContent=s)}}function Xi(t){return t&&t.h&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var Qi,te,ie={exports:{}},ee=(Qi||(Qi=1,te=ie,function(t){const i=function(){const t=(t,i,e)=>`rgb(${Math.round(255*t)}, ${Math.round(255*i)}, ${Math.round(255*e)})`,i={black:t(0,0,0),blue:t(.03,.2,1),brown:t(.59,.32,.11),gray:t(.5,.5,.5),grey:t(.5,.5,.5),green:t(.34,.68,0),orange:t(1,.64,.02),purple:t(.7,.06,.74),red:"#e71d05",white:t(1,1,1),yellow:"#e7c900"},e={circle:t=>{t.lineWidth=.1,t.beginPath(),t.arc(.5,.5,.4,0,2*Math.PI),t.stroke()},frame:t=>{t.lineWidth=.1,t.strokeRect(.15,.15,.7,.7)},round:t=>{t.beginPath(),t.arc(.5,.5,.4,0,2*Math.PI),t.fill()}},s={arch:t=>{t.lineWidth=.22,t.beginPath(),t.moveTo(.25,.9),t.arc(.5,.5,.25,Math.PI,0),t.lineTo(.75,.9),t.stroke()},backslash:t=>{t.beginPath(),t.moveTo(0,0),t.lineTo(1,1),t.stroke()},bar:t=>{t.beginPath(),t.moveTo(0,.5),t.lineTo(1,.5),t.stroke()},circle:t=>{t.lineWidth=.16,t.beginPath(),t.arc(.5,.5,.27,0,2*Math.PI),t.stroke()},corner:t=>{t.beginPath(),t.moveTo(0,0),t.lineTo(1,1),t.lineTo(1,0),t.closePath(),t.fill()},cross:t=>{t.lineWidth=.2,t.beginPath(),t.moveTo(.15,.5),t.lineTo(.85,.5),t.moveTo(.5,.15),t.lineTo(.5,.85),t.stroke()},diamond:t=>{t.beginPath(),t.moveTo(0,.5),t.lineTo(.5,.25),t.lineTo(1,.5),t.lineTo(.5,.75),t.fill()},diamond_line:t=>{t.lineWidth=.15,t.beginPath(),t.moveTo(.1,.5),t.lineTo(.5,.1),t.lineTo(.9,.5),t.lineTo(.5,.9),t.closePath(),t.stroke()},dot:t=>{t.beginPath(),t.arc(.5,.5,.3,0,2*Math.PI),t.fill()},fork:t=>{t.lineWidth=.15,t.beginPath(),t.moveTo(1,.5),t.lineTo(.45,.5),t.lineTo(0,.1),t.moveTo(.45,.5),t.lineTo(0,.9),t.stroke()},hexagon:t=>{t.beginPath(),t.moveTo(.8,.5),t.lineTo(.65,.24),t.lineTo(.35,.24),t.lineTo(.2,.5),t.lineTo(.35,.76),t.lineTo(.65,.76),t.closePath(),t.fill()},lower:t=>{t.fillRect(0,.5,1,.5)},pointer:t=>{t.beginPath(),t.moveTo(.1,.1),t.lineTo(.1,.9),t.lineTo(.9,.5),t.closePath(),t.fill()},rectangle:t=>{t.fillRect(.2,.3,.6,.4)},rectangle_line:t=>{t.lineWidth=.15,t.strokeRect(.25,.25,.5,.5)},right:t=>{t.fillRect(.5,0,.5,1)},slash:t=>{t.beginPath(),t.moveTo(1,0),t.lineTo(0,1),t.stroke()},stripe:t=>{t.beginPath(),t.moveTo(.5,0),t.lineTo(.5,1),t.stroke()},triangle:t=>{t.beginPath(),t.moveTo(.18,.82),t.lineTo(.5,.18),t.lineTo(.82,.82),t.fill()},triangle_line:t=>{t.lineWidth=.15,t.beginPath(),t.moveTo(.2,.8),t.lineTo(.5,.2),t.lineTo(.8,.8),t.closePath(),t.stroke()},triangle_turned:t=>{t.beginPath(),t.moveTo(.2,.2),t.lineTo(.5,.8),t.lineTo(.8,.2),t.fill()},turned_T:t=>{t.lineWidth=.2,t.beginPath(),t.moveTo(.1,.8),t.lineTo(.9,.8),t.moveTo(.5,.2),t.lineTo(.5,.8),t.stroke()},x:t=>{t.lineWidth=.25,t.beginPath(),t.moveTo(1,0),t.lineTo(0,1),t.moveTo(0,0),t.lineTo(1,1),t.stroke()},shell:t=>{t.lineWidth=.06,t.beginPath();const i=[[0,.3],[.1,.5],[.2,.65],[.35,.8],[.5,.85],[.65,.8],[.8,.65],[.9,.5],[1,.3]];for(const[e,s]of i)t.moveTo(.5,.1),t.lineTo(e,s);t.stroke()},shell_modern:t=>{t.lineWidth=.06,t.beginPath();const i=[[.3,0],[.5,.1],[.65,.2],[.8,.35],[.85,.5],[.8,.65],[.65,.8],[.5,.9],[.3,1]];for(const[e,s]of i)t.moveTo(.1,.5),t.lineTo(e,s);t.stroke()},upper:t=>{t.fillRect(0,0,1,.5)},left:t=>{t.fillRect(0,0,.5,1)}};s.turned_triangle=s.triangle_turned;const n={};function r(t){return new Promise((i,e)=>{const s=new Image;s.onload=()=>i(s),s.onerror=e,s.src=t})}function o(t,i){return i=i||r,t?Promise.all(Object.keys(t).map(e=>i(t[e]).then(t=>{n[e]=t}).catch(()=>{}))):Promise.resolve()}function a(t){const e=String(t).split(":").slice(1),n=[];let r="",o="black";for(let a=0;a<e.length;a++){const t=e[a];if(""===t){n.push(null);continue}const[h,...l]=t.split("_");if(i[h])n.push({color:h,shape:l.join("_")});else{if(!s[t]&&"hiker"!==t&&"wheel"!==t){r=t.trim(),r.length>4&&(r=""),e[a+1]&&i[e[a+1]]&&(o=e[a+1]);break}n.push({color:0===t.indexOf("shell")?"yellow":"black",shape:t})}}
1return{background:n[0]||null,foregrounds:n.slice(1).filter(Boolean),text:r,textColor:o}}function h(t,i){const e=s[i.shape];e?e(t):i.shape}"undefined"!=typeof globalThis&&globalThis.OSMC_PICTOGRAMS&&void 0!==globalThis.Image&&o(globalThis.OSMC_PICTOGRAMS);const l=new Set(["bar","stripe","lower","upper","left","right","corner","slash","backslash","rectangle","rectangle_line","frame"]);function c(t,i,e,s){"square"===s?t.setTransform(e,0,0,e,(i-e)/2,0):t.setTransform(i,0,0,e,0,0)}function u(t,i,e,s,n){t.setTransform(1,0,0,1,0,0);const r=s;t.lineWidth=r,t.strokeStyle=n,t.strokeRect(r/2,r/2,i-r,e-r)}return{COLORS:i,BG_SHAPES:e,FG_SHAPES:s,parse:a,render:function(t,s){const r=(s=s||{}).colors||i,o=s.size||22,d=s.ratio||1,f=s.aspect||1,{background:p,foregrounds:m,text:y,textColor:w}=a(t),v=s.createCanvas||((t,i)=>{const e=document.createElement("canvas");return e.width=t,e.height=i,e}),g=Math.round(o*d),b=m.find(t=>"hiker"===t.shape||"wheel"===t.shape);if(b){const t=n[b.color+"_"+b.shape];if(t){const i=v(g,g),e=i.getContext("2d");return e.setTransform(g,0,0,g,0,0),e.drawImage(t,0,0,1,1),s.borderColor&&u(e,g,g,d,s.borderColor),{canvas:i,data:e.getImageData(0,0,i.width,i.height),pixelRatio:d}}}const M=Math.round(g*f),S=v(M,g),C=S.getContext("2d");let L=null;if(p){const t=r[p.color]||r.white;L=e[p.shape]?p.shape:null,c(C,M,g,"span"),C.fillStyle=L?t===r.white?r.black:r.white:t,C.fillRect(0,0,1,1),L&&(c(C,M,g,l.has(L)?"span":"square"),C.fillStyle=C.strokeStyle=t,e[L](C))}for(const i of m)c(C,M,g,l.has(i.shape)?"span":"square"),L&&(C.translate(.2,.2),C.scale(.6,.6)),C.fillStyle=C.strokeStyle=r[i.color]||r.black,C.lineWidth=.3,h(C,i);if(s.borderColor&&p&&u(C,M,g,d,s.borderColor),y){C.setTransform(1,0,0,1,0,0);const t=s.textFont||"sans-serif";let i=.6*g;C.font="bold "+i+"px "+t;const e=C.measureText(y).width,n=.92*M;e>n&&(i*=n/e,C.font="bold "+i+"px "+t),C.textAlign="center",C.textBaseline="alphabetic";const o=C.measureText(y),a=M/2,h=g/2+(null!=o.actualBoundingBoxAscent&&null!=o.actualBoundingBoxDescent?(o.actualBoundingBoxAscent-o.actualBoundingBoxDescent)/2:.35*i),l=r[w]||r.black,[c,u,d]=(t=>{if("#"===t[0]){const i=4===t.length?t.slice(1).replace(/./g,t=>t+t):t.slice(1);return[parseInt(i.slice(0,2),16),parseInt(i.slice(2,4),16),parseInt(i.slice(4,6),16)]}const i=t.match(/\d+/g)||[0,0,0];return[+i[0],+i[1],+i[2]]})(l);C.lineWidth=.18*i,C.lineJoin="round",C.strokeStyle=.299*c+.587*u+.114*d>140?r.black:r.white,C.strokeText(y,a,h),C.fillStyle=l,C.fillText(y,a,h)}return{canvas:S,data:C.getImageData(0,0,S.width,S.height),pixelRatio:d}},loadPictograms:o,pictogramImages:n}}();te.exports?te.exports=i:t.OSMC=i}("undefined"!=typeof self?self:ie.exports)),ie.exports);const se=s({__proto__:null,default:Xi(ee)},[ee]),ne=se.render?se:globalThis.OSMC,re=ne.render;ne.parse,t.Coordinates=y,t.DEFAULT_THEME={name:"default",description:"Classic Visorando theme with orange trails",trail:{color:"#FF6B35",width:4,opacity:.9,showDirection:!0,outlineColor:"#FFFFFF",outlineWidth:2,arrowColor:"#FF6B35",arrowSize:.5,arrowSpacing:150},waypoint:{color:"#2D3142",size:8,textColor:"#FFFFFF",textHaloColor:"#000000",textHaloWidth:1,textSize:12,enablePopup:!0,strokeColor:"#FFFFFF",strokeWidth:2},waypointColors:{start:"#4CAF50",end:"#F44336",waypoint:"#2196F3",bikeDirection:"#4CAF50",bikeDirectionInfo:"#9C27B0",stage:"#FF9800"}},t.Elevation=w,t.ElevationChart=Hi,t.LayerCategory=g,t.LayerType=v,t.MapController=class{adapter;isDestroyed=!1;layerManager=null;trailRenderer=null;waypointRenderer=null;markersRenderer=null;markerTrailPresenter=null;webViewBridge=null;initPromise;osmcSymbolsInstalled=!1;config;mapInitializer;mapEventListeners=null;layerStateManager;elevationChartManager;trailLifecycleManager;webViewEventHandler=null;contextMenuManager=null;constructor(t){this.setupI18n(t),this.adapter=new di;const i=Mi;this.config={api:t.apiBaseUrl??i.apiBaseUrl,bikeDirectionImage:t.bikeDirectionImageBaseUrl??i.bikeDirectionImageBaseUrl,elevationChart:{show:t.showElevationChart??i.showElevationChart,height:t.elevationChartHeight??i.elevationChartHeight,container:t.elevationChartContainer??void 0,comparativeScale:t.comparativeScale??i.comparativeScale},units:{distance:t.distanceUnit??i.distanceUnit,elevation:t.elevationUnit??i.elevationUnit,coordinateFormat:t.coordinateFormat??i.coordinateFormat},display:{trailOutline:t.showTrailOutline??i.showTrailOutline},features:{tracking:t.enableTracking??i.enableTracking,layerSelector:t.enableLayerSelector??i.enableLayerSelector,mode3D:t.enable3DMode??i.enable3DMode,isPremium:t.isPremium??i.isPremium,userGid:t.userGid??i.userGid,loginUrl:t.loginUrl??i.loginUrl,premiumUrl:t.premiumUrl??i.premiumUrl,showOverlayLegends:t.showOverlayLegends??i.showOverlayLegends,contextMenu:!t.webViewPlatform&&(t.enableContextMenu??i.enableContextMenu)}},this.initializeWebView(t),this.initializeManagers(),this.initPromise=this.initializeMap(t)}setupI18n(t){t.translationsBaseUrl&&J(t.translationsBaseUrl),X(t.locale??Mi.locale)}
1initializeManagers(){this.layerManager=new wi({userGid:this.config.features.userGid,isPremium:this.config.features.isPremium}),this.mapInitializer=new Ii(this.adapter,this.layerManager,this.config.features.layerSelector,this.config.features.tracking,this.config.features.isPremium,this.config.features.showOverlayLegends,this.config.features.userGid,this.config.features.loginUrl,this.config.features.premiumUrl),this.layerStateManager=new Gi(this.adapter,this.layerManager,this.config.display.trailOutline,this.config.features.userGid,this.config.features.isPremium),this.elevationChartManager=new Vi(this.adapter,this.config.units.distance,this.config.units.elevation,this.config.elevationChart.comparativeScale),this.trailLifecycleManager=new Ki(this.adapter,this.config.bikeDirectionImage,this.config.display.trailOutline,this.config.features.mode3D,this.elevationChartManager,this.webViewBridge),this.config.features.contextMenu&&(this.contextMenuManager=new Ji(this.adapter,this.config.units.coordinateFormat,this.config.units.elevation,new it(this.config.features.tracking)))}initializeWebView(t){t.webViewPlatform&&(this.webViewBridge=new et(t.webViewPlatform),this.webViewEventHandler=new qi(this.adapter,t=>this.loadAndRenderTrail(t),t=>this.layerManager?.setActiveOverlays(t),t=>this.applyBaseLayerAndWaitForLoad(t)),this.webViewBridge.onMessage((t,i)=>{this.webViewEventHandler?.handle(t,i,this)}),this.mapEventListeners=new Di(this.adapter,this.webViewBridge))}async initializeMap(t){const i=Ii.buildMapConfig(t);await this.adapter.init(i),this.adapter.isInitialized()&&(this.layerStateManager.setupLayerChangeListeners(),this.layerStateManager.setupStyleReloadListener(),this.contextMenuManager?.setupContextMenuListener(),this.setupOsmcSymbols(),this.config.features.layerSelector&&this.mapInitializer.initializeLayerSelectorUI(t.container,t=>{this.handleLayerChange(t)}))}setupOsmcSymbols(){var t;this.osmcSymbolsInstalled||((t=this.adapter).on("styleimagemissing",(...i)=>{const e=i[0]?.id;if(e&&e.startsWith("osmc:")&&!t.hasImage(e))try{const i="undefined"!=typeof window&&window.devicePixelRatio||1,{data:s,pixelRatio:n}=re(e.slice(5),{ratio:i,borderColor:"#000000",aspect:1.5});t.addImage(e,s,{pixelRatio:n})}catch(s){}}),this.osmcSymbolsInstalled=!0)}async createWithTrail(t){return this.loadAndRenderTrail(t)}async createWithMarkers(t){this.ensureActive();const i=(t.geojson?t.geojson.features.map(t=>t.geometry?.coordinates).filter(t=>Array.isArray(t)&&t.length>=2).map(([t,i])=>({lat:i,lng:t})):(t.markers??[]).map(t=>({lat:t.lat,lng:t.lng}))).filter(t=>Number.isFinite(t.lat)&&Number.isFinite(t.lng));if(0===i.length)throw new Error("createWithMarkers requires at least one marker with valid coordinates");const e=i.map(t=>t.lat),s=i.map(t=>t.lng),n=new y(Math.min(...e),Math.min(...s)),r=new y(Math.max(...e),Math.max(...s));if(!this.adapter.isInitialized()){const t=new y((n.lat+r.lat)/2,(n.lng+r.lng)/2);await this.adapter.initializeWithCenter(t,Mi.zoom),this.layerStateManager.setupLayerChangeListeners(),this.layerStateManager.setupStyleReloadListener(),this.contextMenuManager?.setupContextMenuListener(),this.setupOsmcSymbols(),this.config.features.layerSelector&&this.mapInitializer.initializeLayerSelectorUI(this.adapter.getContainer(),t=>{this.handleLayerChange(t)})}await this.waitForLoad(),t.baseLayer&&await this.applyBaseLayerAndWaitForLoad(t.baseLayer),!1===t.showTrailOnClick||this.markerTrailPresenter||(this.markerTrailPresenter=new Ni(this.adapter,{apiBaseUrl:this.config.api,trailColor:t.trailColor,autoClose:t.autoCloseTrail})),this.markersRenderer||(this.markersRenderer=new Ri(this.adapter),this.adapter.on("style.reloaded",()=>{this.markersRenderer?.reRenderAfterStyleReload(),this.markerTrailPresenter?.reRenderAfterStyleReload()}));const o=!1===t.showTrailOnClick?null:this.markerTrailPresenter;this.markersRenderer.render(t.geojson??t.markers??[],{cluster:t.cluster,color:t.markerColor,onMarkerClick:o?(t,i)=>{o.toggle(t,i)}:void 0});const a=r.lat-n.lat,h=r.lng-n.lng;a<.002&&h<.002?this.adapter.setCenter(new y((n.lat+r.lat)/2,(n.lng+r.lng)/2),12):this.adapter.fitBounds(n,r,t.fitBoundsPadding??50)}async loadAndRenderTrail(t){if(this.ensureActive(),!t.trailId)throw new Error("trailId is required for loadAndRenderTrail");const i=new bi({baseUrl:this.config.api}),e=await i.fetchTrail(t.trailId),s=gi.parseTrail(e,t.trailId);if(t.onTrailLoaded&&t.onTrailLoaded(s),!this.adapter.isInitialized()){const i=s.getPath();if(0===i.length)throw new Error("Trail has no path points");const e=i.map(t=>t.position.lat),n=i.map(t=>t.position.lng),r=(Math.min(...e)+Math.max(...e))/2,o=(Math.min(...n)+Math.max(...n))/2,a=new y(r,o),h=void 0!==t.fitBoundsPadding?13:Mi.zoom;await this.adapter.initializeWithCenter(a,h),this.layerStateManager.setupLayerChangeListeners(),this.layerStateManager.setupStyleReloadListener(),this.contextMenuManager?.setupContextMenuListener(),this.setupOsmcSymbols(),this.config.features.layerSelector&&this.mapInitializer.initializeLayerSelectorUI(this.adapter.getContainer(),t=>{this.handleLayerChange(t)}
1)}await this.waitForLoad(),t.baseLayer&&await this.applyBaseLayerAndWaitForLoad(t.baseLayer),this.config.features.mode3D&&(this.adapter.is3DTerrainEnabled()||(await this.adapter.enable3DTerrain(),await new Promise(t=>{const i=()=>{this.adapter.isLoaded()&&this.adapter.isStyleLoaded()?t():setTimeout(i,50)};i()})),this.reExtractLayersAndApplyOverlays(t.overlays)),await this.trailLifecycleManager.renderTrail(s,t.trailColor,t.trailWidth),this.trailRenderer=this.trailLifecycleManager.getTrailRenderer(),this.waypointRenderer=this.trailLifecycleManager.getWaypointRenderer(),this.layerStateManager.setRenderers(this.trailRenderer,this.waypointRenderer,s),t.showElevationChart&&(t.elevationChartContainer&&(this.config.elevationChart.container=t.elevationChartContainer),void 0!==t.elevationChartHeight&&(this.config.elevationChart.height=t.elevationChartHeight),this.config.elevationChart.show=!0,this.config.elevationChart.container&&await this.elevationChartManager.createElevationChart(this.config.elevationChart.container,s,this.config.elevationChart.height));const n=t.fitBoundsPadding??Mi.fitBoundsPadding,r=this.config.features.mode3D?Mi.fitBoundsPitch:0,o=t.fitBoundsPitch??r,a=t.fitBoundsBearing??Mi.fitBoundsBearing;return this.fitTrailBounds(s,n,o,a),t.onRendered&&t.onRendered(s),this.webViewBridge&&this.webViewBridge.sendMapReady({status:"ready",trailId:t.trailId}),s}async waitForLoad(){this.ensureActive(),await this.initPromise,await this.adapter.waitForLoad(),this.layerManager&&(0===this.layerManager.getAllLayers().length&&this.layerStateManager.extractAndRegisterLayers(),this.webViewBridge&&this.mapEventListeners&&!this.mapEventListeners.isMapMoveListenerSetup()&&(this.mapEventListeners.setupMapMoveEndListener(),this.mapEventListeners.setupMapTapListener()))}sendReadyEvent(){this.webViewBridge&&this.webViewBridge.sendCustomEvent("ready",{status:"initialized"})}refreshVectorMapLanguage(){this.adapter.isInitialized()&&this.adapter.localizeVectorMap()}fitTrailBounds(t,i=50,e,s){this.ensureActive(),this.trailLifecycleManager.fitTrailBounds(t,i,e,s)}handleLayerChange(t){if("base-changed"===t.type){const i=this.layerManager.getAllLayers().find(i=>i.id===t.layerId);i&&(this.adapter.setBaseLayerFromMapLayer(i),this.layerManager.markLayerLoaded(i.id))}else if("overlay-shown"===t.type){const i=this.layerManager.getAllLayers().find(i=>i.id===t.layerId);i&&this.showOverlayOnMap(i)}else if("overlay-hidden"===t.type){const i=this.layerManager.getAllLayers().find(i=>i.id===t.layerId);i&&this.hideOverlayOnMap(i)}}showOverlayOnMap(t){if(!this.adapter.isInitialized())return;if(t.styleUrl)return void this.adapter.showCatalogOverlay(t.id,t.styleUrl).catch(t=>{});if(!t.source)return;const i=`${t.id.toLowerCase()}-source`,e=`${t.id.toLowerCase()}-layer`,s=this.adapter.getStyle(),n=s?.layers?.find(t=>"summits-labels"===t.id),r=s?.layers?.find(t=>t.id.startsWith("trail-outline-layer-")||t.id.startsWith("trail-layer-")),o=n?.id??r?.id;if(this.adapter.hasSource(i)||this.adapter.addSourceRaw(i,t.source),this.adapter.hasLayer(e))this.adapter.setLayoutProperty(e,"visibility","visible"),this.adapter.moveLayer(e,o);else{const s={id:e,source:i,type:t.type};t.paint&&(s.paint=t.paint),this.adapter.addLayer(s,o)}}hideOverlayOnMap(t){if(!this.adapter.isInitialized())return;if(t.styleUrl)return void this.adapter.hideCatalogOverlay(t.id);const i=`${t.id.toLowerCase()}-layer`;this.adapter.hasLayer(i)&&this.adapter.setLayoutProperty(i,"visibility","none")}ensureActive(){if(this.isDestroyed)throw new Error("MapController has been destroyed")}getMapInstance(){return this.ensureActive(),this.adapter.getMap()}async centerOnUserLocation(t){this.ensureActive();const{latitude:i,longitude:e,zoom:s,animate:n=!0,duration:r,bearing:o,pitch:a,baseLayer:h,overlays:l}=t;if(void 0===i||void 0===e||null===i||null===e)throw new Error("latitude and longitude are required");const c=s??13;if(!this.adapter.isInitialized()){const t=new y(i,e);await this.adapter.initializeWithCenter(t,c),this.layerStateManager.setupLayerChangeListeners(),this.layerStateManager.setupStyleReloadListener(),this.contextMenuManager?.setupContextMenuListener(),this.setupOsmcSymbols(),this.config.features.layerSelector&&this.mapInitializer.initializeLayerSelectorUI(this.adapter.getContainer(),t=>{this.handleLayerChange(t)}
1)}if(await this.waitForLoad(),h&&await this.applyBaseLayerAndWaitForLoad(h),l&&Array.isArray(l)&&l.length>0&&(h?this.reExtractLayersAndApplyOverlays(l):this.layerManager?.setActiveOverlays(l)),n){const t={center:[e,i],zoom:c};void 0!==r&&(t.duration=r);const s=this.config.features.mode3D?Mi.fitBoundsPitch:0;t.bearing=o??Mi.fitBoundsBearing,t.pitch=a??s,this.adapter.flyTo(t)}else{this.adapter.setCenter(new y(i,e),c);const t=this.config.features.mode3D?Mi.fitBoundsPitch:0,s=o??Mi.fitBoundsBearing,n=a??t;this.adapter.setBearing(s),this.adapter.setPitch(n)}this.webViewBridge&&this.webViewBridge.sendMapReady({status:"ready",latitude:i,longitude:e,zoom:c})}async applyBaseLayerAndWaitForLoad(t){const i=this.layerManager?.getBaseLayers()??[],e=i.find(i=>i.id.toUpperCase()===t.toUpperCase());if(!e&&i.length>0)throw new Error(`Unauthorized or invalid base layer: ${t}`);if(e&&!pi(e,{userGid:this.config.features.userGid,isPremium:this.config.features.isPremium}))throw new Error(`Unauthorized base layer: ${t}`);await this.adapter.setBaseLayer(t),this.adapter.isInitialized()&&(await new Promise(t=>{const i=()=>{this.adapter.isLoaded()&&this.adapter.isStyleLoaded()?t():setTimeout(i,50)};i()}),await new Promise(t=>setTimeout(t,200)))}reExtractLayersAndApplyOverlays(t){this.layerStateManager.reExtractAndApplyOverlays(t)}},t.Trail=n,t.TrailPoint=a,t.Waypoint=o,t.WaypointType=r,t.WebViewBridge=et,t.changeLanguage=async function(t){await Y.changeLanguage(t)},t.getCurrentLanguage=tt,t.getElevationAtPoint=Ct,t.initI18n=X,t.loadCustomStyle=O,t.setTranslationsBaseUrl=J,t.t=Q,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})});

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.