mahal_map 1.7.0 → 1.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var Ce=Object.defineProperty;var D=(i,e)=>{for(var t in e)Ce(i,t,{get:e[t],enumerable:!0})};var v=class{constructor(e){this.map=e}setZoom(e,t=!0){t?this.map.easeTo({zoom:e}):this.map.setZoom(e)}setBearing(e,t=!0){t?this.map.easeTo({bearing:e}):this.map.setBearing(e)}setPitch(e,t=!0){t?this.map.easeTo({pitch:e}):this.map.setPitch(e)}toggle3D(e){this.map.easeTo({pitch:e?60:0,bearing:e?this.map.getBearing():0,duration:800})}resetNorth(){this.map.easeTo({bearing:0,pitch:0,duration:600})}flyTo(e){this.map.flyTo({speed:1.2,curve:1.42,essential:!0,...e})}getPitch(){return this.map.getPitch()}};var Y="https://platform.mahal.tj/api/",T=/^([-+]?(?:[1-8]?\d(?:\.\d+)?|90(?:\.0+)?)),\s*([-+]?(?:180(?:\.0+)?|(?:(?:1[0-7]\d)|(?:[1-9]?\d))(?:\.\d+)?))$/,R=/^([-+]?(?:180(?:\.0+)?|(?:(?:1[0-7]\d)|(?:[1-9]?\d))(?:\.\d+)?)),\s*([-+]?(?:[1-8]?\d(?:\.\d+)?|90(?:\.0+)?))$/;var Q="https://mtile.gram.tj/custom-styles/dark-style.json",ee="https://mtile.gram.tj/custom-styles/mapstyle.json",te="https://mtile.gram.tj/custom-styles/style_maptiler_basic_hn.json";var A="https://navi.gram.tj",b={light:"road-urban-lab-v2",dark:"standard-night"},we=["/maps","/tiles","/tileserver","/sprites","/fonts","/objects3d","/traffic","/data","/key"];function F(i,e){return`${i.replace(/\/+$/,"")}/maps/${e}.json`}function xe(i){try{return new URL(i).origin}catch{return}}var Ie=/^[a-z][a-z0-9+.-]*:/i,Pe=new Set(["http:","https:"]);function ke(){return typeof location<"u"?location.origin:void 0}function Ee(i){try{return new URL(i).pathname.replace(/\/+$/,"")}catch{return""}}function De(i){return we.some(e=>i===e||i.startsWith(`${e}/`))}function re(i,e){let t=i.replace(/\/+$/,""),r=xe(t),a=Ee(t),s=`${t}/`;return o=>{if(!o)return;let l;try{l=new URL(o,s)}catch{return}let h=Ie.test(o);if(!r||!Pe.has(l.protocol))return;l.origin!==r&&l.origin===ke()&&De(l.pathname)&&(l=new URL(`${t}${l.pathname}${l.search}${l.hash}`),h=!1);let n=l.pathname;return!(l.origin===r&&(a===""||n===a||n.startsWith(`${a}/`)))||!e||l.searchParams.has("key")?h?void 0:{url:l.href}:{url:B(l.href,"key",e)}}}function B(i,e,t){let r=new URL(i);return r.searchParams.set(e,t),r.toString()}function H(i,e,t){let r=i;return t&&(r=B(r,"token",t)),e==="ru"&&(r=B(r,"lang","ru")),r}var G="";function Be(i){i!==""&&(G=i)}function Te(){G=""}var S=()=>G;var Re=/<svg[\s>]/i,Ae=/<(svg|path|g|circle|rect|polygon|line|polyline|ellipse|use)\b/i,C=(i,e,t)=>{let r=new RegExp(`\\s${e}="[^"]*"`,"i");return r.test(i)?i.replace(r,` ${e}="${t}"`):i.replace(/<svg\b/i,`<svg ${e}="${t}"`)},Fe=i=>i.replace(/&/g,"&amp;").replace(/"/g,"&quot;"),ie=i=>`<image href="${Fe(i)}" x="14" y="12" width="22" height="22" style="filter: brightness(0) invert(1);" />`,He=i=>{let e=i.trim();if(Re.test(e)){let t=C(e,"x","14");return t=C(t,"y","12"),t=C(t,"width","22"),t=C(t,"height","22"),/\spreserveAspectRatio="/i.test(t)||(t=t.replace(/<svg\b/i,'<svg preserveAspectRatio="xMidYMid meet"')),t}return`<g transform="translate(14 12)">${e}</g>`},Ge=({innerSvg:i,innerUrl:e})=>{let t=i?.trim(),r=e?.trim();return t?Ae.test(t)?He(t):ie(t):r?ie(r):""},se=(i,e={})=>`<svg
1
+ var Ce=Object.defineProperty;var D=(i,e)=>{for(var t in e)Ce(i,t,{get:e[t],enumerable:!0})};var v=class{constructor(e){this.map=e}setZoom(e,t=!0){t?this.map.easeTo({zoom:e}):this.map.setZoom(e)}setBearing(e,t=!0){t?this.map.easeTo({bearing:e}):this.map.setBearing(e)}setPitch(e,t=!0){t?this.map.easeTo({pitch:e}):this.map.setPitch(e)}toggle3D(e){this.map.easeTo({pitch:e?60:0,bearing:e?this.map.getBearing():0,duration:800})}resetNorth(){this.map.easeTo({bearing:0,pitch:0,duration:600})}flyTo(e){this.map.flyTo({speed:1.2,curve:1.42,essential:!0,...e})}getPitch(){return this.map.getPitch()}};var Y="https://geocode.mahal.tj/api/",T=/^([-+]?(?:[1-8]?\d(?:\.\d+)?|90(?:\.0+)?)),\s*([-+]?(?:180(?:\.0+)?|(?:(?:1[0-7]\d)|(?:[1-9]?\d))(?:\.\d+)?))$/,R=/^([-+]?(?:180(?:\.0+)?|(?:(?:1[0-7]\d)|(?:[1-9]?\d))(?:\.\d+)?)),\s*([-+]?(?:[1-8]?\d(?:\.\d+)?|90(?:\.0+)?))$/;var Q="https://mtile.gram.tj/custom-styles/dark-style.json",ee="https://mtile.gram.tj/custom-styles/mapstyle.json",te="https://mtile.gram.tj/custom-styles/style_maptiler_basic_hn.json";var A="https://navi.gram.tj",b={light:"road-urban-lab-v2",dark:"standard-night"},we=["/maps","/tiles","/tileserver","/sprites","/fonts","/objects3d","/traffic","/data","/key"];function F(i,e){return`${i.replace(/\/+$/,"")}/maps/${e}.json`}function xe(i){try{return new URL(i).origin}catch{return}}var Ie=/^[a-z][a-z0-9+.-]*:/i,Pe=new Set(["http:","https:"]);function ke(){return typeof location<"u"?location.origin:void 0}function Ee(i){try{return new URL(i).pathname.replace(/\/+$/,"")}catch{return""}}function De(i){return we.some(e=>i===e||i.startsWith(`${e}/`))}function re(i,e){let t=i.replace(/\/+$/,""),r=xe(t),a=Ee(t),s=`${t}/`;return n=>{if(!n)return;let h=n.startsWith("/")&&!n.startsWith("//"),l;try{l=new URL(n,s)}catch{return}let o=Ie.test(n)||n.startsWith("//");if(!r||!Pe.has(l.protocol))return;(l.origin!==r&&l.origin===ke()||h&&a!=="")&&De(l.pathname)&&(l=new URL(`${t}${l.pathname}${l.search}${l.hash}`),o=!1);let c=l.pathname;return!(l.origin===r&&(a===""||c===a||c.startsWith(`${a}/`)))||!e||l.searchParams.has("key")?o?void 0:{url:l.href}:{url:B(l.href,"key",e)}}}function B(i,e,t){let r=new URL(i);return r.searchParams.set(e,t),r.toString()}function H(i,e,t){let r=i;return t&&(r=B(r,"token",t)),e==="ru"&&(r=B(r,"lang","ru")),r}var G="";function Be(i){i!==""&&(G=i)}function Te(){G=""}var S=()=>G;var Re=/<svg[\s>]/i,Ae=/<(svg|path|g|circle|rect|polygon|line|polyline|ellipse|use)\b/i,C=(i,e,t)=>{let r=new RegExp(`\\s${e}="[^"]*"`,"i");return r.test(i)?i.replace(r,` ${e}="${t}"`):i.replace(/<svg\b/i,`<svg ${e}="${t}"`)},Fe=i=>i.replace(/&/g,"&amp;").replace(/"/g,"&quot;"),ie=i=>`<image href="${Fe(i)}" x="14" y="12" width="22" height="22" style="filter: brightness(0) invert(1);" />`,He=i=>{let e=i.trim();if(Re.test(e)){let t=C(e,"x","14");return t=C(t,"y","12"),t=C(t,"width","22"),t=C(t,"height","22"),/\spreserveAspectRatio="/i.test(t)||(t=t.replace(/<svg\b/i,'<svg preserveAspectRatio="xMidYMid meet"')),t}return`<g transform="translate(14 12)">${e}</g>`},Ge=({innerSvg:i,innerUrl:e})=>{let t=i?.trim(),r=e?.trim();return t?Ae.test(t)?He(t):ie(t):r?ie(r):""},se=(i,e={})=>`<svg
2
2
  width="50"
3
3
  height="62"
4
4
  viewBox="0 0 50 62"
@@ -67,7 +67,7 @@ var Ce=Object.defineProperty;var D=(i,e)=>{for(var t in e)Ce(i,t,{get:e[t],enume
67
67
  />
68
68
  </clipPath>
69
69
  </defs>
70
- </svg>`;var O=class{constructor(e){this.props=e;this.element=this.createElement()}createElement(){let e=document.createElement("div");e.style.cursor="pointer";let t=this.props.svg?this.applyColorToCustomSvg(this.props.svg):se(this.props.color??"#278960",{innerSvg:this.props.innerSvg,innerUrl:this.props.innerUrl});return e.innerHTML=t,this.props.draggable&&(e.draggable=!0),e}applyColorToCustomSvg(e){return this.props.color?e.replace(/fill="[^"]*"/g,`fill="${this.props.color}"`):e}getElement(){return this.element}getCoordinates(){return this.props.coordinates}isDraggable(){return!!this.props.draggable}getAnchor(){return this.props.anchor||"center"}};function ae(i,e,t){return new i.Marker({element:t.getElement(),draggable:t.isDraggable?.()??!1,anchor:t.getAnchor?.()??"center"}).setLngLat(t.getCoordinates()).addTo(e)}var Oe={dark:Q,light:ee},$e={dark:"#ffffff",light:"#19191a"},p=class p{constructor(){this.isReady=!1;this.readyCallbacks=[];this.language="tj";this.instanceKey="";this.engine="legacy";this.gramBase=A;this.gramPreset=b.light;this.presetIsExplicit=!1;this.buildingsEnabled=!1}static getInstanceKey(e){return typeof e.container=="string"&&e.container?e.container:"map"}static normalizeLanguage(e){return e==="ru"?"ru":"tj"}static setDefaultLanguage(e){p.defaultLanguage=p.normalizeLanguage(e)}static getDefaultStyle(e,t){return H(Oe[e],t,p.getMapToken())}static getVectorStyle(){return H(te,void 0,p.getMapToken())}static getMapToken(){let e=S();if(!e)throw new Error("[MahalMap SDK] Map API key is required. Call keyUtils.saveKey() before creating the map or pass apikey in the SDK script URL.");return e}static getMaps3DCtor(e){if(e)return e;if(typeof window>"u")return;let t=window.Maps3D;return typeof t=="function"?t:t?.Maps3D}static create(e,t,r){let a=typeof window<"u"?window.maplibregl:void 0,s=t||a;if(!s)throw new Error("[MahalMap SDK] MapLibre GL was not found. Pass it as the second argument or include it through a script.");let o=p.normalizeLanguage(e.lang||p.defaultLanguage),l=e.theme==="dark"?"dark":"light",h=e.engine==="3d"?"3d":"legacy",n=new p,u=p.getInstanceKey(e);if(n.options=e,n.language=o,n.instanceKey=u,n.maplibre=s,n.engine=h,h==="3d"){let d=e.enable3D!==!1,c=p.getMapToken(),g=p.getMaps3DCtor(r);if(d&&!g)throw new Error("[MahalMap SDK] Maps3D was not found. Pass it as the third argument to create() or include it through a script (window.Maps3D).");n.buildingsEnabled=d,n.gramBase=(e.base||A).replace(/\/+$/,""),n.presetIsExplicit=!!e.preset,n.gramPreset=e.preset||b[l],n.maps3dCtor=g;let m=e.style?e.style:F(n.gramBase,n.gramPreset),y=n.maps3dCtor?n.maps3dCtor.transformRequest({base:n.gramBase,apiKey:c}):re(n.gramBase,c),Se=d?58:0;n.map=new s.Map({container:e.container||"map",style:m,center:e.center||[69.624024,40.279687],zoom:e.zoom!==void 0?e.zoom:5,attributionControl:!1,pitch:e.pitch!==void 0?e.pitch:Se,...e.bearing!==void 0?{bearing:e.bearing}:{},...y?{transformRequest:y}:{}});let X=()=>{n.setNativeBuildingsVisible(!n.buildingsEnabled)};n.map.on("style.load",X),n.map.on("styledata",X),d&&(n.maps3dLayer=new n.maps3dCtor({...e.maps3d,apiKey:c,base:n.gramBase,buildings:!0}),n.attachMaps3DLayer(n.maps3dLayer))}else{let d=e.autoAddVectorSource?p.getVectorStyle():e.style?e.style:p.getDefaultStyle(l,o);n.map=new s.Map({container:e.container||"map",style:d,center:e.center||[69.624024,40.279687],zoom:e.zoom!==void 0?e.zoom:5,attributionControl:!1,...e.pitch!==void 0?{pitch:e.pitch}:{},...e.bearing!==void 0?{bearing:e.bearing}:{}})}return n.addLogo(l),n.map.on("load",()=>{n.isReady=!0,n.camera=new v(n.map),n.readyCallbacks.forEach(d=>d(n.map)),n.readyCallbacks=[]}),p.instances.set(u,n),n}static onReady(e,t){if(!p.instances.has(e)){let a=setInterval(()=>{p.instances.has(e)&&(clearInterval(a),p.onReady(e,t))},50);return}let r=p.getInstance(e);r.isReady?t(r.map):r.readyCallbacks.push(t)}static getInstance(e){let t=p.instances.get(e);if(!t)throw new Error("[MahalMap SDK] Map instance is not created");return t}static hasInstance(e){return p.instances.has(e)}static removeInstance(e){return p.instances.delete(e)}static addMarker(e,t){return e.addMarker(t)}static getCamera(e){return e.getCamera()}static getMap(e){return e.getMap()}static setStyle(e,t){e.setStyle(t)}static getMaps3DLayer(e){return e.getMaps3DLayer()}static whenMaps3DReady(e){return e.whenMaps3DReady()}static toggle3DBuildings(e,t){e.toggle3DBuildings(t)}static setLanguage(e,t){e.setLanguage(t)}static setCenter(e,t){e.setCenter(t)}static setZoom(e,t){e.setZoom(t)}static destroy(e){e.destroy()}addMarker(e){return ae(this.maplibre,this.map,e)}init(e){this.map=e,this.camera=new v(e)}getCamera(){return this.camera}getMap(){return this.map}setStyle(e){if(this.options.theme=e,this.engine==="3d"){if(this.options.style||this.presetIsExplicit)return;this.gramPreset=b[e],this.map.setStyle(F(this.gramBase,this.gramPreset)),this.updateLogoColor(e);return}this.options.autoAddVectorSource||(this.options.style||this.map.setStyle(p.getDefaultStyle(e,this.language)),this.updateLogoColor(e))}setLanguage(e){if(this.language=p.normalizeLanguage(e),this.options.lang=this.language,this.engine==="3d"||this.options.autoAddVectorSource||this.options.style)return;let t=this.options.theme==="dark"?"dark":"light";this.map.setStyle(p.getDefaultStyle(t,this.language))}getMaps3DLayer(){return this.maps3dLayer}toggle3DBuildings(e){if(this.engine==="3d"&&!(!this.maps3dLayer&&e&&(this.maps3dCtor=this.maps3dCtor||p.getMaps3DCtor(),!this.maps3dCtor))){if(this.buildingsEnabled=e,this.setNativeBuildingsVisible(!e),!this.maps3dLayer){this.maps3dLayer=new this.maps3dCtor({...this.options.maps3d,apiKey:S()||void 0,base:this.gramBase,buildings:!0}),this.attachMaps3DLayer(this.maps3dLayer);return}if(this.maps3dLayer.setBuildingsEnabled){this.applyMaps3DBuildingMode(e);return}e||(p.teardownMaps3DLayer(this.maps3dLayer),this.maps3dLayer=void 0,this.maps3dReady=void 0)}}whenMaps3DReady(){return this.maps3dReady||Promise.resolve(void 0)}attachMaps3DLayer(e){let t;try{t=e.attach(this.map)}catch(r){t=Promise.reject(r)}this.maps3dReady=Promise.resolve(t).then(()=>{if(this.maps3dLayer!==e){p.teardownMaps3DLayer(e);return}return this.applyMaps3DBuildingMode(this.buildingsEnabled),e}).catch(r=>{p.teardownMaps3DLayer(e),this.maps3dLayer===e&&(this.maps3dLayer=void 0,this.buildingsEnabled=!1,this.setNativeBuildingsVisible(!0),console.error("[MahalMap SDK] Failed to attach Maps3D layer",r))})}static teardownMaps3DLayer(e){p.disposedMaps3DLayers.has(e)||(p.disposedMaps3DLayers.add(e),e.destroy?e.destroy():e.remove?.())}applyMaps3DBuildingMode(e){this.maps3dLayer&&(this.maps3dLayer.setBuildingsEnabled?.(e),this.maps3dLayer.buildings?.setWindows?.(e))}setNativeBuildingsVisible(e){if(this.options.style)return;let t=this.map.getStyle()?.layers||[];for(let r of t)if(r.id==="building-3d")try{let a=e?"visible":"none";if((this.map.getLayoutProperty(r.id,"visibility")??"visible")===a)continue;this.map.setLayoutProperty(r.id,"visibility",a)}catch{}}setCenter(e){this.map.setCenter(e)}setZoom(e){this.map.setZoom(e)}destroy(){this.maps3dLayer&&p.teardownMaps3DLayer(this.maps3dLayer),this.maps3dLayer=void 0,this.maps3dReady=void 0,this.logoObserver?.disconnect(),this.logoObserver=void 0,this.logoHost?.remove(),this.logoHost=void 0,this.logoShadow=void 0,this.map.remove(),p.instances.delete(this.instanceKey)}addLogo(e){let t=this.map.getContainer(),r=document.createElement("div"),a=r.attachShadow({mode:"closed"});r.setAttribute("aria-label","Mahal"),r.dataset.mahal=Math.random().toString(36).slice(2),this.logoHost=r,this.logoShadow=a,this.applyLogoHostStyles(),this.renderLogo(e),t.appendChild(r),this.observeLogo(t)}updateLogoColor(e){this.logoShadow&&this.renderLogo(e)}renderLogo(e){this.logoShadow&&(this.logoShadow.innerHTML=`
70
+ </svg>`;var O=class{constructor(e){this.props=e;this.element=this.createElement()}createElement(){let e=document.createElement("div");e.style.cursor="pointer";let t=this.props.svg?this.applyColorToCustomSvg(this.props.svg):se(this.props.color??"#278960",{innerSvg:this.props.innerSvg,innerUrl:this.props.innerUrl});return e.innerHTML=t,this.props.draggable&&(e.draggable=!0),e}applyColorToCustomSvg(e){return this.props.color?e.replace(/fill="[^"]*"/g,`fill="${this.props.color}"`):e}getElement(){return this.element}getCoordinates(){return this.props.coordinates}isDraggable(){return!!this.props.draggable}getAnchor(){return this.props.anchor||"center"}};function ae(i,e,t){return new i.Marker({element:t.getElement(),draggable:t.isDraggable?.()??!1,anchor:t.getAnchor?.()??"center"}).setLngLat(t.getCoordinates()).addTo(e)}var Oe={dark:Q,light:ee},$e={dark:"#ffffff",light:"#19191a"},p=class p{constructor(){this.isReady=!1;this.readyCallbacks=[];this.language="tj";this.instanceKey="";this.engine="legacy";this.gramBase=A;this.gramPreset=b.light;this.presetIsExplicit=!1;this.buildingsEnabled=!1}static getInstanceKey(e){return typeof e.container=="string"&&e.container?e.container:"map"}static normalizeLanguage(e){return e==="ru"?"ru":"tj"}static setDefaultLanguage(e){p.defaultLanguage=p.normalizeLanguage(e)}static getDefaultStyle(e,t){return H(Oe[e],t,p.getMapToken())}static getVectorStyle(){return H(te,void 0,p.getMapToken())}static getMapToken(){let e=S();if(!e)throw new Error("[MahalMap SDK] Map API key is required. Call keyUtils.saveKey() before creating the map or pass apikey in the SDK script URL.");return e}static getMaps3DCtor(e){if(e)return e;if(typeof window>"u")return;let t=window.Maps3D;return typeof t=="function"?t:t?.Maps3D}static create(e,t,r){let a=typeof window<"u"?window.maplibregl:void 0,s=t||a;if(!s)throw new Error("[MahalMap SDK] MapLibre GL was not found. Pass it as the second argument or include it through a script.");let n=p.normalizeLanguage(e.lang||p.defaultLanguage),h=e.theme==="dark"?"dark":"light",l=e.engine==="3d"?"3d":"legacy",o=new p,u=p.getInstanceKey(e);if(o.options=e,o.language=n,o.instanceKey=u,o.maplibre=s,o.engine=l,l==="3d"){let d=e.enable3D!==!1,c=p.getMapToken(),g=p.getMaps3DCtor(r);if(d&&!g)throw new Error("[MahalMap SDK] Maps3D was not found. Pass it as the third argument to create() or include it through a script (window.Maps3D).");o.buildingsEnabled=d,o.gramBase=(e.base||A).replace(/\/+$/,""),o.presetIsExplicit=!!e.preset,o.gramPreset=e.preset||b[h],o.maps3dCtor=g;let m=e.style?e.style:F(o.gramBase,o.gramPreset),y=o.maps3dCtor?o.maps3dCtor.transformRequest({base:o.gramBase,apiKey:c}):re(o.gramBase,c),Se=d?58:0;o.map=new s.Map({container:e.container||"map",style:m,center:e.center||[69.624024,40.279687],zoom:e.zoom!==void 0?e.zoom:5,attributionControl:!1,pitch:e.pitch!==void 0?e.pitch:Se,...e.bearing!==void 0?{bearing:e.bearing}:{},...y?{transformRequest:y}:{}});let X=()=>{o.setNativeBuildingsVisible(!o.buildingsEnabled)};o.map.on("style.load",X),o.map.on("styledata",X),d&&(o.maps3dLayer=new o.maps3dCtor({...e.maps3d,apiKey:c,base:o.gramBase,buildings:!0}),o.attachMaps3DLayer(o.maps3dLayer))}else{let d=e.autoAddVectorSource?p.getVectorStyle():e.style?e.style:p.getDefaultStyle(h,n);o.map=new s.Map({container:e.container||"map",style:d,center:e.center||[69.624024,40.279687],zoom:e.zoom!==void 0?e.zoom:5,attributionControl:!1,...e.pitch!==void 0?{pitch:e.pitch}:{},...e.bearing!==void 0?{bearing:e.bearing}:{}})}return o.addLogo(h),o.map.on("load",()=>{o.isReady=!0,o.camera=new v(o.map),o.readyCallbacks.forEach(d=>d(o.map)),o.readyCallbacks=[]}),p.instances.set(u,o),o}static onReady(e,t){if(!p.instances.has(e)){let a=setInterval(()=>{p.instances.has(e)&&(clearInterval(a),p.onReady(e,t))},50);return}let r=p.getInstance(e);r.isReady?t(r.map):r.readyCallbacks.push(t)}static getInstance(e){let t=p.instances.get(e);if(!t)throw new Error("[MahalMap SDK] Map instance is not created");return t}static hasInstance(e){return p.instances.has(e)}static removeInstance(e){return p.instances.delete(e)}static addMarker(e,t){return e.addMarker(t)}static getCamera(e){return e.getCamera()}static getMap(e){return e.getMap()}static setStyle(e,t){e.setStyle(t)}static getMaps3DLayer(e){return e.getMaps3DLayer()}static whenMaps3DReady(e){return e.whenMaps3DReady()}static toggle3DBuildings(e,t){e.toggle3DBuildings(t)}static setLanguage(e,t){e.setLanguage(t)}static setCenter(e,t){e.setCenter(t)}static setZoom(e,t){e.setZoom(t)}static destroy(e){e.destroy()}addMarker(e){return ae(this.maplibre,this.map,e)}init(e){this.map=e,this.camera=new v(e)}getCamera(){return this.camera}getMap(){return this.map}setStyle(e){if(this.options.theme=e,this.engine==="3d"){if(this.options.style||this.presetIsExplicit)return;this.gramPreset=b[e],this.map.setStyle(F(this.gramBase,this.gramPreset)),this.updateLogoColor(e);return}this.options.autoAddVectorSource||(this.options.style||this.map.setStyle(p.getDefaultStyle(e,this.language)),this.updateLogoColor(e))}setLanguage(e){if(this.language=p.normalizeLanguage(e),this.options.lang=this.language,this.engine==="3d"||this.options.autoAddVectorSource||this.options.style)return;let t=this.options.theme==="dark"?"dark":"light";this.map.setStyle(p.getDefaultStyle(t,this.language))}getMaps3DLayer(){return this.maps3dLayer}toggle3DBuildings(e){if(this.engine==="3d"&&!(!this.maps3dLayer&&e&&(this.maps3dCtor=this.maps3dCtor||p.getMaps3DCtor(),!this.maps3dCtor))){if(this.buildingsEnabled=e,this.setNativeBuildingsVisible(!e),!this.maps3dLayer){this.maps3dLayer=new this.maps3dCtor({...this.options.maps3d,apiKey:S()||void 0,base:this.gramBase,buildings:!0}),this.attachMaps3DLayer(this.maps3dLayer);return}if(this.maps3dLayer.setBuildingsEnabled){this.applyMaps3DBuildingMode(e);return}e||(p.teardownMaps3DLayer(this.maps3dLayer),this.maps3dLayer=void 0,this.maps3dReady=void 0)}}whenMaps3DReady(){return this.maps3dReady||Promise.resolve(void 0)}attachMaps3DLayer(e){let t;try{t=e.attach(this.map)}catch(r){t=Promise.reject(r)}this.maps3dReady=Promise.resolve(t).then(()=>{if(this.maps3dLayer!==e){p.teardownMaps3DLayer(e);return}return this.applyMaps3DBuildingMode(this.buildingsEnabled),e}).catch(r=>{p.teardownMaps3DLayer(e),this.maps3dLayer===e&&(this.maps3dLayer=void 0,this.buildingsEnabled=!1,this.setNativeBuildingsVisible(!0),console.error("[MahalMap SDK] Failed to attach Maps3D layer",r))})}static teardownMaps3DLayer(e){p.disposedMaps3DLayers.has(e)||(p.disposedMaps3DLayers.add(e),e.destroy?e.destroy():e.remove?.())}applyMaps3DBuildingMode(e){this.maps3dLayer&&(this.maps3dLayer.setBuildingsEnabled?.(e),this.maps3dLayer.buildings?.setWindows?.(e))}setNativeBuildingsVisible(e){if(this.options.style)return;let t=this.map.getStyle()?.layers||[];for(let r of t)if(r.id==="building-3d")try{let a=e?"visible":"none";if((this.map.getLayoutProperty(r.id,"visibility")??"visible")===a)continue;this.map.setLayoutProperty(r.id,"visibility",a)}catch{}}setCenter(e){this.map.setCenter(e)}setZoom(e){this.map.setZoom(e)}destroy(){this.maps3dLayer&&p.teardownMaps3DLayer(this.maps3dLayer),this.maps3dLayer=void 0,this.maps3dReady=void 0,this.logoObserver?.disconnect(),this.logoObserver=void 0,this.logoHost?.remove(),this.logoHost=void 0,this.logoShadow=void 0,this.map.remove(),p.instances.delete(this.instanceKey)}addLogo(e){let t=this.map.getContainer(),r=document.createElement("div"),a=r.attachShadow({mode:"closed"});r.setAttribute("role","img"),r.setAttribute("aria-label","Mahal"),r.dataset.mahal=Math.random().toString(36).slice(2),this.logoHost=r,this.logoShadow=a,this.applyLogoHostStyles(),this.renderLogo(e),t.appendChild(r),this.observeLogo(t)}updateLogoColor(e){this.logoShadow&&this.renderLogo(e)}renderLogo(e){this.logoShadow&&(this.logoShadow.innerHTML=`
71
71
  <style>
72
72
  :host {
73
73
  all: initial;
@@ -110,5 +110,5 @@ var Ce=Object.defineProperty;var D=(i,e)=>{for(var t in e)Ce(i,t,{get:e[t],enume
110
110
  </clipPath>
111
111
  </defs>
112
112
  </svg>
113
- `}};p.instances=new Map,p.defaultLanguage="tj",p.disposedMaps3DLayers=new WeakSet;var $=p;var me={};D(me,{Router:()=>he,Search:()=>ce,SearchByLocation:()=>ge,clearKey:()=>Te,getApiKey:()=>S,saveKey:()=>Be});import Ve from"axios";var M=Ve.create({baseURL:Y});var ne=async(i,e)=>{try{let t=[];return i.forEach(a=>{t.push({lng:a[0],lat:a[1]})}),(await M.post("services/getRoutes",{points:t,token:e})).data}catch(t){throw console.error(t),t}};var pe={};D(pe,{checkCoordinates:()=>je,debounce:()=>V,geojsonPolyline:()=>j,geometryPolyline:()=>le,trimValue:()=>Ne});function je(i){let e,t;if(T.test(i)){let r=i.match(T);r&&([,e,t]=r)}else if(R.test(i)){let r=i.match(R);r&&([,t,e]=r)}else return console.log("\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0444\u043E\u0440\u043C\u0430\u0442 \u043A\u043E\u043E\u0440\u0434\u0438\u043D\u0430\u0442"),null;return{lat:e,lng:t}}function V(i,e){let t;return(...r)=>(t&&clearTimeout(t),new Promise(a=>{t=setTimeout(async()=>{let s=await i(...r);a(s)},e)}))}function j(i){let e=[],t=0,r=i.length,a=0,s=0;for(;t<r;){let o,l=0,h=0;do o=i.charCodeAt(t++)-63,h|=(o&31)<<l,l+=5;while(o>=32);let n=h&1?~(h>>1):h>>1;a+=n,l=0,h=0;do o=i.charCodeAt(t++)-63,h|=(o&31)<<l,l+=5;while(o>=32);let u=h&1?~(h>>1):h>>1;s+=u,e.push([s*1e-5,a*1e-5])}return e}function Ue(i){let e="",t=0,r=0;for(let a=0;a<i.length;a++){let[s,o]=i[a],l=Math.round(o*1e5),h=Math.round(s*1e5),n=l-t,u=h-r;t=l,r=h,e+=oe(n)+oe(u)}return e}function oe(i){let e=i<<1;return i<0&&(e=~e),ze(e)}function ze(i){let e="";for(;i>=32;)e+=String.fromCharCode((32|i&31)+63),i>>=5;return e+=String.fromCharCode(i+63),e}var le=Ue;function Ne(i,e){if(e<=0)return"";let t=i.trim();return e>=t.length?t:t.slice(0,e)}async function he(i,e,t){if(!t)throw new Error("[MahalMap SDK] Router token is required");try{let r=await ne(i,t);return r?.data?r.data.map(s=>{let o={...s};return o.route?.routes?.length&&(o.route.routes=o.route.routes.map(l=>({...l,geometry:e==="geojson"&&typeof l.geometry=="string"?j(l.geometry):l.geometry}))),o}):r}catch(r){throw r}}var ue=async i=>{try{return(await M.post("services/getAddress",null,{params:i})).data}catch(e){throw console.error("Error while searching address:",e),e}},de=async i=>{try{return(await M.post("services/getAddressByLocation",null,{params:i})).data}catch(e){throw console.error("Error while searching address by location:",e),e}};async function Ke(i,e,t){let r={text:i,token:e,...t};try{return(await ue(r)).data}catch(a){throw a}}var We=V(Ke,500);async function ce(i,e,t){if(!e)throw new Error("[MahalMap SDK] Search token is required");return await We(i,e,t)}async function ge(i){if(!i.token)throw new Error("[MahalMap SDK] SearchByLocation token is required");let e={...i};try{return await de(e)}catch(t){throw t}}var be={};D(be,{MeasureTool:()=>E,haversineDistance:()=>K,lineLength:()=>w,midpoint:()=>q,polygonArea:()=>W,polygonCentroid:()=>J});var U=63710088e-1;function f(i){return i*Math.PI/180}function z(i){return((i+180)%360+360)%360-180}function N(i){return((i+180)%360+360)%360-180}function K(i,e){let[t,r]=i,[a,s]=e,o=f(r),l=f(s),h=f(s-r),n=f(a-t),u=Math.sin(h/2),d=Math.sin(n/2),c=u*u+Math.cos(o)*Math.cos(l)*d*d,g=2*Math.atan2(Math.sqrt(c),Math.sqrt(1-c));return U*g}function w(i){let e=0;for(let t=1;t<i.length;t+=1)e+=K(i[t-1],i[t]);return e}function W(i){if(i.length<3)return 0;let e=0;for(let t=0;t<i.length;t+=1){let r=i[t],a=i[(t+1)%i.length],s=f(z(a[0]-r[0])),o=f(r[1]),l=f(a[1]);e+=s*(2+Math.sin(o)+Math.sin(l))}return Math.abs(e*U*U/2)}function fe(i){let e=i.reduce((t,r)=>[t[0]+r[0],t[1]+r[1]],[0,0]);return[N(e[0]/i.length),e[1]/i.length]}function J(i){if(i.length===0)return[0,0];if(i.length<3)return fe(i);let e=i[0]?.[0]??0,t=i.map(([n,u])=>[e+z(n-e),u]),r=0,a=0,s=0;for(let n=0;n<t.length;n+=1){let[u,d]=t[n],[c,g]=t[(n+1)%t.length],m=u*g-c*d;r+=m,a+=(u+c)*m,s+=(d+g)*m}let o=r/2;if(Math.abs(o)<1e-12)return fe(t);let l=a/(6*o),h=s/(6*o);return[N(l),h]}function q(i){if(i.length===0)return[0,0];if(i.length===1)return i[0];let e=[],t=0;for(let s=1;s<i.length;s+=1){let o=K(i[s-1],i[s]);e.push(o),t+=o}if(t===0)return i[0];let r=t/2,a=0;for(let s=1;s<i.length;s+=1){let o=e[s-1];if(a+o>=r){let l=o===0?0:(r-a)/o,h=i[s-1],n=i[s],u=N(h[0]+z(n[0]-h[0])*l),d=h[1]+(n[1]-h[1])*l;return[u,d]}a+=o}return i[i.length-1]}var Je=new Set(["svg","g","path","circle","ellipse","rect","line","polyline","polygon"]),qe=new Set(["xmlns","viewbox","width","height","fill","fill-rule","fill-opacity","stroke","stroke-width","stroke-linecap","stroke-linejoin","stroke-dasharray","stroke-opacity","opacity","d","cx","cy","r","rx","ry","x","y","x1","y1","x2","y2","points","transform"]),_e=new Set(["fill","stroke"]);function Ze(i,e){let t=e.trim().toLowerCase();return!(t.includes("javascript:")||t.includes("data:")||t.includes("expression(")||_e.has(i)&&t.includes("url("))}function ye(i){return Je.has(i.tagName.toLowerCase())?(Array.from(i.attributes).forEach(e=>{let t=e.name.toLowerCase();(!qe.has(t)||!Ze(t,e.value))&&i.removeAttribute(e.name)}),Array.from(i.children).forEach(e=>{ye(e)||e.remove()}),!0):!1}function Xe(i){if(typeof DOMParser>"u")return null;try{let e=new DOMParser().parseFromString(i,"image/svg+xml"),t=e.documentElement;return!t||t.tagName.toLowerCase()!=="svg"||e.querySelector("parsererror")||!ye(t)?null:new XMLSerializer().serializeToString(t)}catch{return null}}function L(i,e){return i?Xe(i)??e:e}var ve='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>',Ye='<svg width="14" height="14" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4 4l16 16M20 4L4 20" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>',Qe='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4 12l6 6 10-12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',x=class{constructor(e,t,r,a){this.wrapper=document.createElement("div"),this.valueEl=document.createElement("span"),this.trashButton=document.createElement("button"),this.closeButton=document.createElement("button"),this.checkButton=document.createElement("button"),this.applyWrapperStyles(t),this.applyValueStyles(t),this.applyButtonStyles(this.trashButton,t),this.applyButtonStyles(this.closeButton,t),this.applyButtonStyles(this.checkButton,t),this.trashButton.type="button",this.closeButton.type="button",this.checkButton.type="button",this.trashButton.innerHTML=L(r.trash,ve),this.closeButton.innerHTML=L(r.close,Ye),this.checkButton.innerHTML=L(r.check,Qe);let s=o=>{o.preventDefault(),o.stopPropagation()};this.wrapper.addEventListener("mousedown",s),this.wrapper.addEventListener("dblclick",s),this.wrapper.addEventListener("contextmenu",s),this.trashButton.addEventListener("click",o=>{s(o),a.onRemove()}),this.closeButton.addEventListener("click",o=>{s(o),a.onClose()}),this.checkButton.addEventListener("click",o=>{s(o),a.onCheck()}),this.wrapper.appendChild(this.valueEl),this.wrapper.appendChild(this.checkButton),this.wrapper.appendChild(this.trashButton),this.wrapper.appendChild(this.closeButton),this.wrapper.style.display="none",e.appendChild(this.wrapper)}applyStyle(e){let t=this.wrapper.style.display;this.applyWrapperStyles(e),this.applyValueStyles(e),this.applyButtonStyles(this.trashButton,e),this.applyButtonStyles(this.closeButton,e),this.applyButtonStyles(this.checkButton,e),this.wrapper.style.display=t}applyWrapperStyles(e){let t=this.wrapper.style;t.position="absolute",t.zIndex="5",t.display="flex",t.alignItems="center",t.gap=e.badgeGap??"8px",t.padding="6px 8px",t.background=e.badgeBackground??"#FFFFFF",t.borderRadius=e.badgeBorderRadius??"12px",t.boxShadow=e.badgeBoxShadow??"0 2px 10px rgba(15, 23, 42, 0.18)",t.border=e.badgeBorder??"1px solid rgba(0,0,0,0.06)",t.transform="translate(-50%, -140%)",t.pointerEvents="auto",t.userSelect="none",t.whiteSpace="nowrap"}applyValueStyles(e){let t=this.valueEl.style;t.color=e.badgeTextColor??"#19191A",t.fontSize=e.badgeFontSize??"14px",t.fontWeight=e.badgeFontWeight??"600",t.lineHeight="18px"}applyButtonStyles(e,t){let r=e.style,a=t.iconButtonSize??"24px";r.display="inline-flex",r.alignItems="center",r.justifyContent="center",r.width=a,r.height=a,r.border="none",r.background="transparent",r.cursor="pointer",r.color=t.badgeTextColor??"#535969",r.padding="0"}setValue(e){this.valueEl.textContent=e}setCheckEnabled(e){this.checkButton.style.opacity=e?"1":"0.35",this.checkButton.style.pointerEvents=e?"auto":"none"}setPosition(e,t){this.wrapper.style.left=`${e}px`,this.wrapper.style.top=`${t}px`}show(){this.wrapper.style.display="flex"}hide(){this.wrapper.style.display="none"}destroy(){this.wrapper.remove()}},I=class{constructor(e,t,r,a){this.wrapper=document.createElement("div"),this.valueEl=document.createElement("span"),this.trashButton=document.createElement("button"),this.applyStyle(t),this.trashButton.type="button",this.trashButton.innerHTML=L(r.trash,ve);let s=o=>{o.preventDefault(),o.stopPropagation()};this.wrapper.addEventListener("mousedown",s),this.wrapper.addEventListener("dblclick",s),this.wrapper.addEventListener("contextmenu",s),this.trashButton.addEventListener("click",o=>{s(o),a()}),this.wrapper.appendChild(this.valueEl),this.wrapper.appendChild(this.trashButton),e.appendChild(this.wrapper)}applyStyle(e){let t=this.wrapper.style;t.position="absolute",t.zIndex="4",t.display="flex",t.alignItems="center",t.gap=e.badgeGap??"6px",t.padding="5px 7px",t.background=e.badgeBackground??"#FFFFFF",t.borderRadius=e.badgeBorderRadius??"12px",t.boxShadow=e.badgeBoxShadow??"0 2px 10px rgba(15, 23, 42, 0.18)",t.border=e.badgeBorder??"1px solid rgba(0,0,0,0.06)",t.transform="translate(-50%, -50%)",t.pointerEvents="auto",t.userSelect="none",t.whiteSpace="nowrap";let r=this.valueEl.style;r.color=e.badgeTextColor??"#19191A",r.fontSize=e.badgeFontSize??"13px",r.fontWeight=e.badgeFontWeight??"600",r.lineHeight="16px";let a=e.iconButtonSize??"20px",s=this.trashButton.style;s.display="inline-flex",s.alignItems="center",s.justifyContent="center",s.width=a,s.height=a,s.border="none",s.background="transparent",s.cursor="pointer",s.color=e.badgeTextColor??"#535969",s.padding="0"}setValue(e){this.valueEl.textContent=e}setPosition(e,t){this.wrapper.style.left=`${e}px`,this.wrapper.style.top=`${t}px`}destroy(){this.wrapper.remove()}};var et=0,_=i=>`${i}-${Date.now().toString(36)}-${et+=1}`,tt=0,rt=()=>`mahal-measure-${tt+=1}`,Me={pointColor:"#FFFFFF",pointStrokeColor:"#278960",pointStrokeWidth:2,pointRadius:5,lineColor:"#278960",lineWidth:3,fillColor:"#278960",fillOpacity:.15};function Z(i,e){return i>=1e3?`${(i/1e3).toFixed(2)} ${e.kilometers??"\u043A\u043C"}`:`${Math.round(i)} ${e.meters??"\u043C"}`}function Le(i,e){return i>=1e5?`${(i/1e6).toFixed(2)} ${e.squareKilometers??"\u043A\u043C\xB2"}`:`${Math.round(i)} ${e.squareMeters??"\u043C\xB2"}`}function P(i){return i==="area"?3:2}function k(){return{type:"FeatureCollection",features:[]}}var E=class{constructor(e,t={}){this.layerHandlersBound=!1;this.destroyed=!1;this.ensuringLayers=!1;this.isActive=!1;this.draft=null;this.shapes=[];this.badge=null;this.shapeBadges=new Map;this.draggingPointId=null;this.draggingShapeId=null;this.dragPanWasEnabled=!0;this.suppressNextClick=!1;this.hoverInsert=null;this.handleClick=e=>this.onMapClick(e);this.handlePointMouseDown=e=>this.onPointMouseDown(e);this.handlePointMouseEnter=()=>{this.isActive&&this.setCursor("pointer")};this.handlePointMouseLeave=()=>{this.isActive&&this.setCursor("")};this.handlePointContextMenu=e=>this.onPointContextMenu(e);this.handleLineMouseMove=e=>this.onLineMouseMove(e);this.handleLineMouseLeave=()=>this.clearHoverInsert();this.handleLineMouseDown=e=>this.onLineMouseDown(e);this.handleStyleLoad=()=>this.onStyleLoad();this.handleStyleData=()=>{this.destroyed||this.map.getLayer(this.pointsLayerId)||this.refresh()};this.handleViewportChange=()=>{this.updateBadgePosition(),this.updateShapeBadgePositions()};this.onPointDragMove=e=>{if(!this.draggingShapeId||!this.draggingPointId)return;let t=this.findShape(this.draggingShapeId),r=t?.points.find(a=>a.id===this.draggingPointId);!t||!r||(r.lngLat=[+e.lngLat.lng.toFixed(6),+e.lngLat.lat.toFixed(6)],this.recomputeShape(t),this.render(),this.emitChange())};this.onPointDragUp=()=>{this.draggingPointId&&(this.stopDragListeners(),this.dragPanWasEnabled&&this.map.dragPan.enable(),this.setCursor("pointer"),this.suppressNextClick=!0,window.setTimeout(()=>{this.suppressNextClick=!1},0))};this.map=e,this.originalCursor=e.getCanvas().style.cursor,this.prefix=t.sourceIdPrefix??rt(),this.style=t.style??{},this.labels=t.labels??{},this.icons=t.icons??{},this.mode=t.mode??"distance",this.onChange=t.onChange,this.onCloseRequest=t.onCloseRequest,this.pointsSourceId=`${this.prefix}-points`,this.linesSourceId=`${this.prefix}-lines`,this.fillsSourceId=`${this.prefix}-fills`,this.hoverPointSourceId=`${this.prefix}-hover-point`,this.pointsLayerId=`${this.prefix}-points-layer`,this.linesCasingLayerId=`${this.prefix}-lines-casing-layer`,this.linesLayerId=`${this.prefix}-lines-layer`,this.fillsLayerId=`${this.prefix}-fills-layer`,this.hoverPointLayerId=`${this.prefix}-hover-point-layer`,this.badge=new x(e.getContainer(),this.style,this.icons,{onRemove:()=>this.removeShape((this.draft??this.getLastShape())?.id??""),onClose:()=>this.onCloseRequest?.(),onCheck:()=>this.finishDraft()}),this.ensureLayers(),this.map.on("click",this.handleClick),this.map.on("style.load",this.handleStyleLoad),this.map.on("styledata",this.handleStyleData),this.map.on("move",this.handleViewportChange)}bindLayerHandlers(){this.layerHandlersBound||(this.layerHandlersBound=!0,this.map.on("mousedown",this.pointsLayerId,this.handlePointMouseDown),this.map.on("mouseenter",this.pointsLayerId,this.handlePointMouseEnter),this.map.on("mouseleave",this.pointsLayerId,this.handlePointMouseLeave),this.map.on("contextmenu",this.pointsLayerId,this.handlePointContextMenu),this.map.on("mousemove",this.linesCasingLayerId,this.handleLineMouseMove),this.map.on("mouseleave",this.linesCasingLayerId,this.handleLineMouseLeave),this.map.on("mousedown",this.linesCasingLayerId,this.handleLineMouseDown))}unbindLayerHandlers(){this.layerHandlersBound&&(this.layerHandlersBound=!1,this.map.off("mousedown",this.pointsLayerId,this.handlePointMouseDown),this.map.off("mouseenter",this.pointsLayerId,this.handlePointMouseEnter),this.map.off("mouseleave",this.pointsLayerId,this.handlePointMouseLeave),this.map.off("contextmenu",this.pointsLayerId,this.handlePointContextMenu),this.map.off("mousemove",this.linesCasingLayerId,this.handleLineMouseMove),this.map.off("mouseleave",this.linesCasingLayerId,this.handleLineMouseLeave),this.map.off("mousedown",this.linesCasingLayerId,this.handleLineMouseDown))}start(e=this.mode){this.isActive=!0;let t=e!==this.mode;this.setMode(e),t||(this.render(),this.emitChange())}stop(){this.isActive=!1,this.onPointDragUp(),this.badge?.hide(),this.clearHoverInsert(),this.setCursor(this.originalCursor),this.emitChange()}setMode(e){this.mode!==e&&(this.mode=e,this.draft&&(this.draft.mode=e,this.recomputeShape(this.draft)),this.render(),this.emitChange())}finishDraft(){this.commitOrDiscardDraft(),this.render(),this.emitChange()}removeShape(e){e&&(this.draft?.id===e?this.draft=null:this.shapes=this.shapes.filter(t=>t.id!==e),this.hoverInsert?.shapeId===e&&this.clearHoverInsert(),this.render(),this.emitChange())}removePoint(e,t){let r=this.findShape(e);if(!r)return;if(r.points=r.points.filter(s=>s.id!==t),r.points.length===0){this.removeShape(e);return}if(!(this.draft?.id===e)&&r.points.length<P(r.mode)){this.removeShape(e);return}this.recomputeShape(r),this.render(),this.emitChange()}clearAll(){this.draft=null,this.shapes=[],this.clearHoverInsert(),this.render(),this.emitChange()}refresh(){this.destroyed||(this.ensureLayers(),this.render(),this.renderHoverPoint())}setStyleOptions(e){let t=this.style.lineDasharray!==void 0;this.style={...this.style,...e},this.applyPaintStyle(t),this.badge?.applyStyle(this.style),this.shapeBadges.forEach(r=>r.applyStyle(this.style))}getState(){return{active:this.isActive,mode:this.mode,draft:this.draft?this.cloneShape(this.draft):null,shapes:this.shapes.map(e=>this.cloneShape(e))}}destroy(){this.destroyed||(this.destroyed=!0,this.map.off("click",this.handleClick),this.unbindLayerHandlers(),this.map.off("style.load",this.handleStyleLoad),this.map.off("styledata",this.handleStyleData),this.map.off("move",this.handleViewportChange),this.onPointDragUp(),this.setCursor(this.originalCursor),this.badge?.destroy(),this.badge=null,this.shapeBadges.forEach(e=>e.destroy()),this.shapeBadges.clear(),this.removeLayers())}cloneShape(e){return{...e,points:e.points.map(t=>({...t,lngLat:[...t.lngLat]}))}}findShape(e){return this.draft?.id===e?this.draft:this.shapes.find(t=>t.id===e)??null}getLastShape(){return this.shapes[this.shapes.length-1]??null}commitOrDiscardDraft(){this.draft&&(this.draft.points.length>=P(this.draft.mode)&&this.shapes.push(this.draft),this.draft=null)}ensureDraft(){return this.draft||(this.draft={id:_("measure-shape"),mode:this.mode,points:[],closed:!1,distance:0,area:0}),this.draft}recomputeShape(e){let t=e.points.map(r=>r.lngLat);if(e.mode==="area"&&t.length>=3){e.closed=!0,e.area=W(t),e.distance=w([...t,t[0]]);return}e.closed=!1,e.area=0,e.distance=w(t)}onMapClick(e){if(!this.isActive)return;if(this.suppressNextClick){this.suppressNextClick=!1;return}if(this.queryPointsLayer(e.point).length>0)return;let r=this.ensureDraft();r.points.push({id:_("measure-point"),lngLat:[+e.lngLat.lng.toFixed(6),+e.lngLat.lat.toFixed(6)]}),this.recomputeShape(r),this.render(),this.emitChange()}onPointMouseDown(e){if(!this.isActive)return;let t=e.features?.[0],r=t?.properties?.shapeId,a=t?.properties?.pointId;!r||!a||(e.preventDefault(),this.beginPointDrag(r,a))}beginPointDrag(e,t){this.draggingShapeId=e,this.draggingPointId=t,this.dragPanWasEnabled=this.map.dragPan.isEnabled(),this.map.dragPan.disable(),this.setCursor("grabbing"),this.map.on("mousemove",this.onPointDragMove),this.map.on("mouseup",this.onPointDragUp),window.addEventListener("mouseup",this.onPointDragUp)}stopDragListeners(){this.map.off("mousemove",this.onPointDragMove),this.map.off("mouseup",this.onPointDragUp),window.removeEventListener("mouseup",this.onPointDragUp),this.draggingShapeId=null,this.draggingPointId=null}projectPoint(e){let t=this.map.project(e);return{x:t.x,y:t.y}}closestPointOnSegment(e,t,r){let a=r.x-t.x,s=r.y-t.y,o=a*a+s*s;if(o===0)return t;let l=Math.max(0,Math.min(1,((e.x-t.x)*a+(e.y-t.y)*s)/o));return{x:t.x+a*l,y:t.y+s*l}}findClosestPointOnShape(e,t){let r=e.points.map(n=>this.projectPoint(n.lngLat)),a=e.closed?r.length:r.length-1,s=-1,o=null,l=1/0;for(let n=0;n<a;n+=1){let u=r[n],d=r[(n+1)%r.length];if(!u||!d)continue;let c=this.closestPointOnSegment(t,u,d),g=c.x-t.x,m=c.y-t.y,y=Math.sqrt(g*g+m*m);y<l&&(l=y,s=n,o=c)}if(s===-1||!o)return null;let h=this.map.unproject([o.x,o.y]);return{index:s,lngLat:[+h.lng.toFixed(6),+h.lat.toFixed(6)]}}queryPointsLayer(e){return this.map.getLayer(this.pointsLayerId)?this.map.queryRenderedFeatures(e,{layers:[this.pointsLayerId]}):[]}isOverExistingPoint(e){return this.queryPointsLayer(e).length>0}onLineMouseMove(e){if(!this.isActive||this.draggingPointId||this.isOverExistingPoint(e.point)){this.clearHoverInsert();return}let r=e.features?.[0]?.properties?.shapeId,a=r?this.findShape(r):null;if(!r||!a)return;let s=this.findClosestPointOnShape(a,e.point);s&&(this.hoverInsert={shapeId:r,index:s.index,lngLat:s.lngLat},this.renderHoverPoint(),this.setCursor("copy"))}clearHoverInsert(){this.hoverInsert&&(this.hoverInsert=null,this.renderHoverPoint(),this.setCursor(""))}onLineMouseDown(e){if(!this.isActive||!this.hoverInsert)return;let r=e.features?.[0]?.properties?.shapeId;if(!r||r!==this.hoverInsert.shapeId)return;let a=this.findShape(r);if(!a)return;e.preventDefault();let s={id:_("measure-point"),lngLat:this.hoverInsert.lngLat};a.points.splice(this.hoverInsert.index+1,0,s),this.recomputeShape(a),this.hoverInsert=null,this.renderHoverPoint(),this.render(),this.emitChange(),this.beginPointDrag(r,s.id)}renderHoverPoint(){let e=this.hoverInsert?[{type:"Feature",properties:{},geometry:{type:"Point",coordinates:this.hoverInsert.lngLat}}]:[];this.setSourceData(this.hoverPointSourceId,{type:"FeatureCollection",features:e})}onPointContextMenu(e){if(!this.isActive)return;let t=e.features?.[0],r=t?.properties?.shapeId,a=t?.properties?.pointId;!r||!a||(e.preventDefault(),this.removePoint(r,a))}setCursor(e){this.map.getCanvas().style.cursor=e}onStyleLoad(){this.refresh()}isMapUsable(){return!this.destroyed&&!!this.map.style}emitChange(){this.onChange?.(this.getState())}ensureLayers(){if(!(!this.isMapUsable()||this.ensuringLayers)){this.ensuringLayers=!0;try{this.createMissingLayers()}catch{}finally{this.ensuringLayers=!1}}}createMissingLayers(){let e={...Me,...this.style};this.map.getSource(this.linesSourceId)||this.map.addSource(this.linesSourceId,{type:"geojson",data:k()}),this.map.getSource(this.fillsSourceId)||this.map.addSource(this.fillsSourceId,{type:"geojson",data:k()}),this.map.getSource(this.pointsSourceId)||this.map.addSource(this.pointsSourceId,{type:"geojson",data:k()}),this.map.getSource(this.hoverPointSourceId)||this.map.addSource(this.hoverPointSourceId,{type:"geojson",data:k()}),this.map.getLayer(this.fillsLayerId)||this.map.addLayer({id:this.fillsLayerId,type:"fill",source:this.fillsSourceId,paint:{"fill-color":e.fillColor,"fill-opacity":e.fillOpacity}}),this.map.getLayer(this.linesCasingLayerId)||this.map.addLayer({id:this.linesCasingLayerId,type:"line",source:this.linesSourceId,layout:{"line-cap":"round","line-join":"round"},paint:{"line-color":"#FFFFFF","line-width":e.lineWidth+3,"line-opacity":.9}}),this.map.getLayer(this.linesLayerId)||this.map.addLayer({id:this.linesLayerId,type:"line",source:this.linesSourceId,layout:{"line-cap":"round","line-join":"round"},paint:{"line-color":e.lineColor,"line-width":e.lineWidth,...this.style.lineDasharray?{"line-dasharray":this.style.lineDasharray}:{}}}),this.map.getLayer(this.hoverPointLayerId)||this.map.addLayer({id:this.hoverPointLayerId,type:"circle",source:this.hoverPointSourceId,paint:{"circle-radius":Math.max(3,e.pointRadius-1),"circle-color":e.pointColor,"circle-stroke-color":e.pointStrokeColor,"circle-stroke-width":e.pointStrokeWidth,"circle-opacity":.8,"circle-stroke-opacity":.8}}),this.map.getLayer(this.pointsLayerId)||this.map.addLayer({id:this.pointsLayerId,type:"circle",source:this.pointsSourceId,paint:{"circle-radius":e.pointRadius,"circle-color":e.pointColor,"circle-stroke-color":e.pointStrokeColor,"circle-stroke-width":e.pointStrokeWidth}}),this.bindLayerHandlers()}applyPaintStyle(e=!1){if(!this.isMapUsable())return;let t={...Me,...this.style},r=(a,s,o)=>{this.map.getLayer(a)&&this.map.setPaintProperty(a,s,o)};r(this.fillsLayerId,"fill-color",t.fillColor),r(this.fillsLayerId,"fill-opacity",t.fillOpacity),r(this.linesCasingLayerId,"line-width",t.lineWidth+3),r(this.linesLayerId,"line-color",t.lineColor),r(this.linesLayerId,"line-width",t.lineWidth),this.style.lineDasharray!==void 0?r(this.linesLayerId,"line-dasharray",this.style.lineDasharray):e&&r(this.linesLayerId,"line-dasharray",null),r(this.hoverPointLayerId,"circle-radius",Math.max(3,t.pointRadius-1)),r(this.hoverPointLayerId,"circle-color",t.pointColor),r(this.hoverPointLayerId,"circle-stroke-color",t.pointStrokeColor),r(this.hoverPointLayerId,"circle-stroke-width",t.pointStrokeWidth),r(this.pointsLayerId,"circle-radius",t.pointRadius),r(this.pointsLayerId,"circle-color",t.pointColor),r(this.pointsLayerId,"circle-stroke-color",t.pointStrokeColor),r(this.pointsLayerId,"circle-stroke-width",t.pointStrokeWidth)}removeLayers(){[this.pointsLayerId,this.hoverPointLayerId,this.linesLayerId,this.linesCasingLayerId,this.fillsLayerId].forEach(e=>{this.map.getLayer(e)&&this.map.removeLayer(e)}),[this.pointsSourceId,this.hoverPointSourceId,this.linesSourceId,this.fillsSourceId].forEach(e=>{this.map.getSource(e)&&this.map.removeSource(e)})}setSourceData(e,t){this.map.getSource(e)?.setData(t)}buildLineFeature(e){if(e.points.length<2)return null;let t=e.points.map(r=>r.lngLat);return{type:"Feature",id:e.id,properties:{shapeId:e.id},geometry:{type:"LineString",coordinates:e.closed?[...t,t[0]]:t}}}buildFillFeature(e){if(e.mode!=="area"||e.points.length<3)return null;let t=e.points.map(r=>r.lngLat);return{type:"Feature",id:e.id,properties:{shapeId:e.id},geometry:{type:"Polygon",coordinates:[[...t,t[0]]]}}}buildPointFeatures(e){return e.points.map(t=>({type:"Feature",id:t.id,properties:{shapeId:e.id,pointId:t.id},geometry:{type:"Point",coordinates:t.lngLat}}))}getShapeAnchor(e){let t=e.points.map(r=>r.lngLat);return e.mode==="area"?J(t):q(t)}render(){this.ensureLayers();let e=this.shapes,t=e.map(s=>this.buildLineFeature(s)).filter(s=>!!s),r=e.map(s=>this.buildFillFeature(s)).filter(s=>!!s),a=e.flatMap(s=>this.buildPointFeatures(s));if(this.draft){let s=this.buildLineFeature(this.draft),o=this.buildFillFeature(this.draft);s&&t.push(s),o&&r.push(o),a.push(...this.buildPointFeatures(this.draft))}this.setSourceData(this.linesSourceId,{type:"FeatureCollection",features:t}),this.setSourceData(this.fillsSourceId,{type:"FeatureCollection",features:r}),this.setSourceData(this.pointsSourceId,{type:"FeatureCollection",features:a}),this.updateBadge(),this.syncShapeBadges()}syncShapeBadges(){let e=new Set(this.shapes.map(t=>t.id));Array.from(this.shapeBadges.keys()).forEach(t=>{e.has(t)||(this.shapeBadges.get(t)?.destroy(),this.shapeBadges.delete(t))}),this.shapes.forEach(t=>{if(t.points.length<P(t.mode)){this.shapeBadges.get(t.id)?.destroy(),this.shapeBadges.delete(t.id);return}let r=t.mode==="area"?Le(t.area,this.labels):Z(t.distance,this.labels),a=this.shapeBadges.get(t.id);a||(a=new I(this.map.getContainer(),this.style,this.icons,()=>this.removeShape(t.id)),this.shapeBadges.set(t.id,a)),a.setValue(r);let s=this.map.project(this.getShapeAnchor(t));a.setPosition(s.x,s.y)})}updateShapeBadgePositions(){this.shapes.forEach(e=>{let t=this.shapeBadges.get(e.id);if(!t)return;let r=this.map.project(this.getShapeAnchor(e));t.setPosition(r.x,r.y)})}updateBadge(){if(!this.badge)return;if(!this.isActive||!this.draft||this.draft.points.length===0){this.badge.hide();return}let e=this.draft.points.length>=P(this.draft.mode),t=this.draft.mode==="area"?Le(this.draft.area,this.labels):Z(this.draft.distance,this.labels);this.badge.setValue(e?t:Z(this.draft.distance,this.labels)),this.badge.setCheckEnabled(e),this.badge.show(),this.updateBadgePosition()}updateBadgePosition(){if(!this.badge||!this.draft||this.draft.points.length===0||!this.isActive)return;let e=this.draft.points[this.draft.points.length-1];if(!e)return;let t=this.map.project(e.lngLat);this.badge.setPosition(t.x,t.y)}};export{$ as MahalMap,O as MahalMapDefaultMarker,E as MeasureTool,he as Router,ce as Search,ge as SearchByLocation,me as keyUtils,be as measureUtils,pe as utils};
113
+ `}};p.instances=new Map,p.defaultLanguage="tj",p.disposedMaps3DLayers=new WeakSet;var $=p;var me={};D(me,{Router:()=>he,Search:()=>ce,SearchByLocation:()=>ge,clearKey:()=>Te,getApiKey:()=>S,saveKey:()=>Be});import Ve from"axios";var M=Ve.create({baseURL:Y});var ne=async(i,e)=>{try{let t=[];return i.forEach(a=>{t.push({lng:a[0],lat:a[1]})}),(await M.post("services/getRoutes",{points:t,token:e})).data}catch(t){throw console.error(t),t}};var pe={};D(pe,{checkCoordinates:()=>je,debounce:()=>V,geojsonPolyline:()=>j,geometryPolyline:()=>le,trimValue:()=>We});function je(i){let e,t;if(T.test(i)){let r=i.match(T);r&&([,e,t]=r)}else if(R.test(i)){let r=i.match(R);r&&([,t,e]=r)}else return console.log("\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0444\u043E\u0440\u043C\u0430\u0442 \u043A\u043E\u043E\u0440\u0434\u0438\u043D\u0430\u0442"),null;return{lat:e,lng:t}}function V(i,e){let t;return(...r)=>(t&&clearTimeout(t),new Promise(a=>{t=setTimeout(async()=>{let s=await i(...r);a(s)},e)}))}function j(i){let e=[],t=0,r=i.length,a=0,s=0;for(;t<r;){let n,h=0,l=0;do n=i.charCodeAt(t++)-63,l|=(n&31)<<h,h+=5;while(n>=32);let o=l&1?~(l>>1):l>>1;a+=o,h=0,l=0;do n=i.charCodeAt(t++)-63,l|=(n&31)<<h,h+=5;while(n>=32);let u=l&1?~(l>>1):l>>1;s+=u,e.push([s*1e-5,a*1e-5])}return e}function Ue(i){let e="",t=0,r=0;for(let a=0;a<i.length;a++){let[s,n]=i[a],h=Math.round(n*1e5),l=Math.round(s*1e5),o=h-t,u=l-r;t=h,r=l,e+=oe(o)+oe(u)}return e}function oe(i){let e=i<<1;return i<0&&(e=~e),ze(e)}function ze(i){let e="";for(;i>=32;)e+=String.fromCharCode((32|i&31)+63),i>>=5;return e+=String.fromCharCode(i+63),e}var le=Ue;function We(i,e){if(e<=0)return"";let t=i.trim();return e>=t.length?t:t.slice(0,e)}async function he(i,e,t){if(!t)throw new Error("[MahalMap SDK] Router token is required");try{let r=await ne(i,t);return r?.data?r.data.map(s=>{let n={...s};return n.route?.routes?.length&&(n.route.routes=n.route.routes.map(h=>({...h,geometry:e==="geojson"&&typeof h.geometry=="string"?j(h.geometry):h.geometry}))),n}):r}catch(r){throw r}}var ue=async i=>{try{return(await M.post("services/getAddress",null,{params:i})).data}catch(e){throw console.error("Error while searching address:",e),e}},de=async i=>{try{return(await M.post("services/getAddressByLocation",null,{params:i})).data}catch(e){throw console.error("Error while searching address by location:",e),e}};async function Ne(i,e,t){let r={text:i,token:e,...t};try{return(await ue(r)).data}catch(a){throw a}}var Ke=V(Ne,500);async function ce(i,e,t){if(!e)throw new Error("[MahalMap SDK] Search token is required");return await Ke(i,e,t)}async function ge(i){if(!i.token)throw new Error("[MahalMap SDK] SearchByLocation token is required");let e={...i};try{return await de(e)}catch(t){throw t}}var be={};D(be,{MeasureTool:()=>E,haversineDistance:()=>N,lineLength:()=>w,midpoint:()=>q,polygonArea:()=>K,polygonCentroid:()=>J});var U=63710088e-1;function f(i){return i*Math.PI/180}function z(i){return((i+180)%360+360)%360-180}function W(i){return((i+180)%360+360)%360-180}function N(i,e){let[t,r]=i,[a,s]=e,n=f(r),h=f(s),l=f(s-r),o=f(a-t),u=Math.sin(l/2),d=Math.sin(o/2),c=u*u+Math.cos(n)*Math.cos(h)*d*d,g=2*Math.atan2(Math.sqrt(c),Math.sqrt(1-c));return U*g}function w(i){let e=0;for(let t=1;t<i.length;t+=1)e+=N(i[t-1],i[t]);return e}function K(i){if(i.length<3)return 0;let e=0;for(let t=0;t<i.length;t+=1){let r=i[t],a=i[(t+1)%i.length],s=f(z(a[0]-r[0])),n=f(r[1]),h=f(a[1]);e+=s*(2+Math.sin(n)+Math.sin(h))}return Math.abs(e*U*U/2)}function fe(i){let e=i.reduce((t,r)=>[t[0]+r[0],t[1]+r[1]],[0,0]);return[W(e[0]/i.length),e[1]/i.length]}function J(i){if(i.length===0)return[0,0];if(i.length<3)return fe(i);let e=i[0]?.[0]??0,t=i.map(([o,u])=>[e+z(o-e),u]),r=0,a=0,s=0;for(let o=0;o<t.length;o+=1){let[u,d]=t[o],[c,g]=t[(o+1)%t.length],m=u*g-c*d;r+=m,a+=(u+c)*m,s+=(d+g)*m}let n=r/2;if(Math.abs(n)<1e-12)return fe(t);let h=a/(6*n),l=s/(6*n);return[W(h),l]}function q(i){if(i.length===0)return[0,0];if(i.length===1)return i[0];let e=[],t=0;for(let s=1;s<i.length;s+=1){let n=N(i[s-1],i[s]);e.push(n),t+=n}if(t===0)return i[0];let r=t/2,a=0;for(let s=1;s<i.length;s+=1){let n=e[s-1];if(a+n>=r){let h=n===0?0:(r-a)/n,l=i[s-1],o=i[s],u=W(l[0]+z(o[0]-l[0])*h),d=l[1]+(o[1]-l[1])*h;return[u,d]}a+=n}return i[i.length-1]}var Je=new Set(["svg","g","path","circle","ellipse","rect","line","polyline","polygon"]),qe=new Set(["xmlns","viewbox","width","height","fill","fill-rule","fill-opacity","stroke","stroke-width","stroke-linecap","stroke-linejoin","stroke-dasharray","stroke-opacity","opacity","d","cx","cy","r","rx","ry","x","y","x1","y1","x2","y2","points","transform"]),_e=new Set(["fill","stroke"]);function Ze(i,e){let t=e.trim().toLowerCase();return!(t.includes("javascript:")||t.includes("data:")||t.includes("expression(")||_e.has(i)&&t.includes("url("))}function ye(i){return Je.has(i.tagName.toLowerCase())?(Array.from(i.attributes).forEach(e=>{let t=e.name.toLowerCase();(!qe.has(t)||!Ze(t,e.value))&&i.removeAttribute(e.name)}),Array.from(i.children).forEach(e=>{ye(e)||e.remove()}),!0):!1}function Xe(i){if(typeof DOMParser>"u")return null;try{let e=new DOMParser().parseFromString(i,"image/svg+xml"),t=e.documentElement;return!t||t.tagName.toLowerCase()!=="svg"||e.querySelector("parsererror")||!ye(t)?null:new XMLSerializer().serializeToString(t)}catch{return null}}function L(i,e){return i?Xe(i)??e:e}var ve='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>',Ye='<svg width="14" height="14" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4 4l16 16M20 4L4 20" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>',Qe='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M4 12l6 6 10-12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',x=class{constructor(e,t,r,a){this.wrapper=document.createElement("div"),this.valueEl=document.createElement("span"),this.trashButton=document.createElement("button"),this.closeButton=document.createElement("button"),this.checkButton=document.createElement("button"),this.applyWrapperStyles(t),this.applyValueStyles(t),this.applyButtonStyles(this.trashButton,t),this.applyButtonStyles(this.closeButton,t),this.applyButtonStyles(this.checkButton,t),this.trashButton.type="button",this.closeButton.type="button",this.checkButton.type="button",this.trashButton.innerHTML=L(r.trash,ve),this.closeButton.innerHTML=L(r.close,Ye),this.checkButton.innerHTML=L(r.check,Qe);let s=n=>{n.preventDefault(),n.stopPropagation()};this.wrapper.addEventListener("mousedown",s),this.wrapper.addEventListener("dblclick",s),this.wrapper.addEventListener("contextmenu",s),this.trashButton.addEventListener("click",n=>{s(n),a.onRemove()}),this.closeButton.addEventListener("click",n=>{s(n),a.onClose()}),this.checkButton.addEventListener("click",n=>{s(n),a.onCheck()}),this.wrapper.appendChild(this.valueEl),this.wrapper.appendChild(this.checkButton),this.wrapper.appendChild(this.trashButton),this.wrapper.appendChild(this.closeButton),this.wrapper.style.display="none",e.appendChild(this.wrapper)}applyStyle(e){let t=this.wrapper.style.display;this.applyWrapperStyles(e),this.applyValueStyles(e),this.applyButtonStyles(this.trashButton,e),this.applyButtonStyles(this.closeButton,e),this.applyButtonStyles(this.checkButton,e),this.wrapper.style.display=t}applyWrapperStyles(e){let t=this.wrapper.style;t.position="absolute",t.zIndex="5",t.display="flex",t.alignItems="center",t.gap=e.badgeGap??"8px",t.padding="6px 8px",t.background=e.badgeBackground??"#FFFFFF",t.borderRadius=e.badgeBorderRadius??"12px",t.boxShadow=e.badgeBoxShadow??"0 2px 10px rgba(15, 23, 42, 0.18)",t.border=e.badgeBorder??"1px solid rgba(0,0,0,0.06)",t.transform="translate(-50%, -140%)",t.pointerEvents="auto",t.userSelect="none",t.whiteSpace="nowrap"}applyValueStyles(e){let t=this.valueEl.style;t.color=e.badgeTextColor??"#19191A",t.fontSize=e.badgeFontSize??"14px",t.fontWeight=e.badgeFontWeight??"600",t.lineHeight="18px"}applyButtonStyles(e,t){let r=e.style,a=t.iconButtonSize??"24px";r.display="inline-flex",r.alignItems="center",r.justifyContent="center",r.width=a,r.height=a,r.border="none",r.background="transparent",r.cursor="pointer",r.color=t.badgeTextColor??"#535969",r.padding="0"}setValue(e){this.valueEl.textContent=e}setCheckEnabled(e){this.checkButton.style.opacity=e?"1":"0.35",this.checkButton.style.pointerEvents=e?"auto":"none"}setPosition(e,t){this.wrapper.style.left=`${e}px`,this.wrapper.style.top=`${t}px`}show(){this.wrapper.style.display="flex"}hide(){this.wrapper.style.display="none"}destroy(){this.wrapper.remove()}},I=class{constructor(e,t,r,a){this.wrapper=document.createElement("div"),this.valueEl=document.createElement("span"),this.trashButton=document.createElement("button"),this.applyStyle(t),this.trashButton.type="button",this.trashButton.innerHTML=L(r.trash,ve);let s=n=>{n.preventDefault(),n.stopPropagation()};this.wrapper.addEventListener("mousedown",s),this.wrapper.addEventListener("dblclick",s),this.wrapper.addEventListener("contextmenu",s),this.trashButton.addEventListener("click",n=>{s(n),a()}),this.wrapper.appendChild(this.valueEl),this.wrapper.appendChild(this.trashButton),e.appendChild(this.wrapper)}applyStyle(e){let t=this.wrapper.style;t.position="absolute",t.zIndex="4",t.display="flex",t.alignItems="center",t.gap=e.badgeGap??"6px",t.padding="5px 7px",t.background=e.badgeBackground??"#FFFFFF",t.borderRadius=e.badgeBorderRadius??"12px",t.boxShadow=e.badgeBoxShadow??"0 2px 10px rgba(15, 23, 42, 0.18)",t.border=e.badgeBorder??"1px solid rgba(0,0,0,0.06)",t.transform="translate(-50%, -50%)",t.pointerEvents="auto",t.userSelect="none",t.whiteSpace="nowrap";let r=this.valueEl.style;r.color=e.badgeTextColor??"#19191A",r.fontSize=e.badgeFontSize??"13px",r.fontWeight=e.badgeFontWeight??"600",r.lineHeight="16px";let a=e.iconButtonSize??"20px",s=this.trashButton.style;s.display="inline-flex",s.alignItems="center",s.justifyContent="center",s.width=a,s.height=a,s.border="none",s.background="transparent",s.cursor="pointer",s.color=e.badgeTextColor??"#535969",s.padding="0"}setValue(e){this.valueEl.textContent=e}setPosition(e,t){this.wrapper.style.left=`${e}px`,this.wrapper.style.top=`${t}px`}destroy(){this.wrapper.remove()}};var et=0,_=i=>`${i}-${Date.now().toString(36)}-${et+=1}`,tt=0,rt=()=>`mahal-measure-${tt+=1}`,Me={pointColor:"#FFFFFF",pointStrokeColor:"#278960",pointStrokeWidth:2,pointRadius:5,lineColor:"#278960",lineWidth:3,fillColor:"#278960",fillOpacity:.15};function Z(i,e){return i>=1e3?`${(i/1e3).toFixed(2)} ${e.kilometers??"\u043A\u043C"}`:`${Math.round(i)} ${e.meters??"\u043C"}`}function Le(i,e){return i>=1e5?`${(i/1e6).toFixed(2)} ${e.squareKilometers??"\u043A\u043C\xB2"}`:`${Math.round(i)} ${e.squareMeters??"\u043C\xB2"}`}function P(i){return i==="area"?3:2}function k(){return{type:"FeatureCollection",features:[]}}var E=class{constructor(e,t={}){this.layerHandlersBound=!1;this.destroyed=!1;this.ensuringLayers=!1;this.isActive=!1;this.draft=null;this.shapes=[];this.badge=null;this.shapeBadges=new Map;this.draggingPointId=null;this.draggingShapeId=null;this.dragPanWasEnabled=!0;this.suppressNextClick=!1;this.hoverInsert=null;this.handleClick=e=>this.onMapClick(e);this.handlePointMouseDown=e=>this.onPointMouseDown(e);this.handlePointMouseEnter=()=>{this.isActive&&this.setCursor("pointer")};this.handlePointMouseLeave=()=>{this.isActive&&this.setCursor("")};this.handlePointContextMenu=e=>this.onPointContextMenu(e);this.handleLineMouseMove=e=>this.onLineMouseMove(e);this.handleLineMouseLeave=()=>this.clearHoverInsert();this.handleLineMouseDown=e=>this.onLineMouseDown(e);this.handleStyleLoad=()=>this.onStyleLoad();this.handleStyleData=()=>{this.destroyed||this.map.getLayer(this.pointsLayerId)||this.refresh()};this.handleViewportChange=()=>{this.updateBadgePosition(),this.updateShapeBadgePositions()};this.onPointDragMove=e=>{if(!this.draggingShapeId||!this.draggingPointId)return;let t=this.findShape(this.draggingShapeId),r=t?.points.find(a=>a.id===this.draggingPointId);!t||!r||(r.lngLat=[+e.lngLat.lng.toFixed(6),+e.lngLat.lat.toFixed(6)],this.recomputeShape(t),this.render(),this.emitChange())};this.onPointDragUp=()=>{this.draggingPointId&&(this.stopDragListeners(),this.dragPanWasEnabled&&this.map.dragPan.enable(),this.setCursor("pointer"),this.suppressNextClick=!0,window.setTimeout(()=>{this.suppressNextClick=!1},0))};this.map=e,this.originalCursor=e.getCanvas().style.cursor,this.prefix=t.sourceIdPrefix??rt(),this.style=t.style??{},this.labels=t.labels??{},this.icons=t.icons??{},this.mode=t.mode??"distance",this.onChange=t.onChange,this.onCloseRequest=t.onCloseRequest,this.pointsSourceId=`${this.prefix}-points`,this.linesSourceId=`${this.prefix}-lines`,this.fillsSourceId=`${this.prefix}-fills`,this.hoverPointSourceId=`${this.prefix}-hover-point`,this.pointsLayerId=`${this.prefix}-points-layer`,this.linesCasingLayerId=`${this.prefix}-lines-casing-layer`,this.linesLayerId=`${this.prefix}-lines-layer`,this.fillsLayerId=`${this.prefix}-fills-layer`,this.hoverPointLayerId=`${this.prefix}-hover-point-layer`,this.badge=new x(e.getContainer(),this.style,this.icons,{onRemove:()=>this.removeShape((this.draft??this.getLastShape())?.id??""),onClose:()=>this.onCloseRequest?.(),onCheck:()=>this.finishDraft()}),this.ensureLayers(),this.map.on("click",this.handleClick),this.map.on("style.load",this.handleStyleLoad),this.map.on("styledata",this.handleStyleData),this.map.on("move",this.handleViewportChange)}bindLayerHandlers(){this.layerHandlersBound||(this.layerHandlersBound=!0,this.map.on("mousedown",this.pointsLayerId,this.handlePointMouseDown),this.map.on("mouseenter",this.pointsLayerId,this.handlePointMouseEnter),this.map.on("mouseleave",this.pointsLayerId,this.handlePointMouseLeave),this.map.on("contextmenu",this.pointsLayerId,this.handlePointContextMenu),this.map.on("mousemove",this.linesCasingLayerId,this.handleLineMouseMove),this.map.on("mouseleave",this.linesCasingLayerId,this.handleLineMouseLeave),this.map.on("mousedown",this.linesCasingLayerId,this.handleLineMouseDown))}unbindLayerHandlers(){this.layerHandlersBound&&(this.layerHandlersBound=!1,this.map.off("mousedown",this.pointsLayerId,this.handlePointMouseDown),this.map.off("mouseenter",this.pointsLayerId,this.handlePointMouseEnter),this.map.off("mouseleave",this.pointsLayerId,this.handlePointMouseLeave),this.map.off("contextmenu",this.pointsLayerId,this.handlePointContextMenu),this.map.off("mousemove",this.linesCasingLayerId,this.handleLineMouseMove),this.map.off("mouseleave",this.linesCasingLayerId,this.handleLineMouseLeave),this.map.off("mousedown",this.linesCasingLayerId,this.handleLineMouseDown))}start(e=this.mode){this.isActive=!0;let t=e!==this.mode;this.setMode(e),t||(this.render(),this.emitChange())}stop(){this.isActive=!1,this.onPointDragUp(),this.badge?.hide(),this.clearHoverInsert(),this.setCursor(this.originalCursor),this.emitChange()}setMode(e){this.mode!==e&&(this.mode=e,this.draft&&(this.draft.mode=e,this.recomputeShape(this.draft)),this.render(),this.emitChange())}finishDraft(){this.commitOrDiscardDraft(),this.render(),this.emitChange()}removeShape(e){e&&(this.draft?.id===e?this.draft=null:this.shapes=this.shapes.filter(t=>t.id!==e),this.hoverInsert?.shapeId===e&&this.clearHoverInsert(),this.render(),this.emitChange())}removePoint(e,t){let r=this.findShape(e);if(!r)return;if(r.points=r.points.filter(s=>s.id!==t),r.points.length===0){this.removeShape(e);return}if(!(this.draft?.id===e)&&r.points.length<P(r.mode)){this.removeShape(e);return}this.recomputeShape(r),this.render(),this.emitChange()}clearAll(){this.draft=null,this.shapes=[],this.clearHoverInsert(),this.render(),this.emitChange()}refresh(){this.destroyed||(this.ensureLayers(),this.render(),this.renderHoverPoint())}setStyleOptions(e){let t=this.style.lineDasharray!==void 0;this.style={...this.style,...e},this.applyPaintStyle(t),this.badge?.applyStyle(this.style),this.shapeBadges.forEach(r=>r.applyStyle(this.style))}getState(){return{active:this.isActive,mode:this.mode,draft:this.draft?this.cloneShape(this.draft):null,shapes:this.shapes.map(e=>this.cloneShape(e))}}destroy(){this.destroyed||(this.destroyed=!0,this.map.off("click",this.handleClick),this.unbindLayerHandlers(),this.map.off("style.load",this.handleStyleLoad),this.map.off("styledata",this.handleStyleData),this.map.off("move",this.handleViewportChange),this.onPointDragUp(),this.setCursor(this.originalCursor),this.badge?.destroy(),this.badge=null,this.shapeBadges.forEach(e=>e.destroy()),this.shapeBadges.clear(),this.removeLayers())}cloneShape(e){return{...e,points:e.points.map(t=>({...t,lngLat:[...t.lngLat]}))}}findShape(e){return this.draft?.id===e?this.draft:this.shapes.find(t=>t.id===e)??null}getLastShape(){return this.shapes[this.shapes.length-1]??null}commitOrDiscardDraft(){this.draft&&(this.draft.points.length>=P(this.draft.mode)&&this.shapes.push(this.draft),this.draft=null)}ensureDraft(){return this.draft||(this.draft={id:_("measure-shape"),mode:this.mode,points:[],closed:!1,distance:0,area:0}),this.draft}recomputeShape(e){let t=e.points.map(r=>r.lngLat);if(e.mode==="area"&&t.length>=3){e.closed=!0,e.area=K(t),e.distance=w([...t,t[0]]);return}e.closed=!1,e.area=0,e.distance=w(t)}onMapClick(e){if(!this.isActive)return;if(this.suppressNextClick){this.suppressNextClick=!1;return}if(this.queryPointsLayer(e.point).length>0)return;let r=this.ensureDraft();r.points.push({id:_("measure-point"),lngLat:[+e.lngLat.lng.toFixed(6),+e.lngLat.lat.toFixed(6)]}),this.recomputeShape(r),this.render(),this.emitChange()}onPointMouseDown(e){if(!this.isActive)return;let t=e.features?.[0],r=t?.properties?.shapeId,a=t?.properties?.pointId;!r||!a||(e.preventDefault(),this.beginPointDrag(r,a))}beginPointDrag(e,t){this.draggingShapeId=e,this.draggingPointId=t,this.dragPanWasEnabled=this.map.dragPan.isEnabled(),this.map.dragPan.disable(),this.setCursor("grabbing"),this.map.on("mousemove",this.onPointDragMove),this.map.on("mouseup",this.onPointDragUp),window.addEventListener("mouseup",this.onPointDragUp)}stopDragListeners(){this.map.off("mousemove",this.onPointDragMove),this.map.off("mouseup",this.onPointDragUp),window.removeEventListener("mouseup",this.onPointDragUp),this.draggingShapeId=null,this.draggingPointId=null}projectPoint(e){let t=this.map.project(e);return{x:t.x,y:t.y}}closestPointOnSegment(e,t,r){let a=r.x-t.x,s=r.y-t.y,n=a*a+s*s;if(n===0)return t;let h=Math.max(0,Math.min(1,((e.x-t.x)*a+(e.y-t.y)*s)/n));return{x:t.x+a*h,y:t.y+s*h}}findClosestPointOnShape(e,t){let r=e.points.map(o=>this.projectPoint(o.lngLat)),a=e.closed?r.length:r.length-1,s=-1,n=null,h=1/0;for(let o=0;o<a;o+=1){let u=r[o],d=r[(o+1)%r.length];if(!u||!d)continue;let c=this.closestPointOnSegment(t,u,d),g=c.x-t.x,m=c.y-t.y,y=Math.sqrt(g*g+m*m);y<h&&(h=y,s=o,n=c)}if(s===-1||!n)return null;let l=this.map.unproject([n.x,n.y]);return{index:s,lngLat:[+l.lng.toFixed(6),+l.lat.toFixed(6)]}}queryPointsLayer(e){return this.map.getLayer(this.pointsLayerId)?this.map.queryRenderedFeatures(e,{layers:[this.pointsLayerId]}):[]}isOverExistingPoint(e){return this.queryPointsLayer(e).length>0}onLineMouseMove(e){if(!this.isActive||this.draggingPointId||this.isOverExistingPoint(e.point)){this.clearHoverInsert();return}let r=e.features?.[0]?.properties?.shapeId,a=r?this.findShape(r):null;if(!r||!a)return;let s=this.findClosestPointOnShape(a,e.point);s&&(this.hoverInsert={shapeId:r,index:s.index,lngLat:s.lngLat},this.renderHoverPoint(),this.setCursor("copy"))}clearHoverInsert(){this.hoverInsert&&(this.hoverInsert=null,this.renderHoverPoint(),this.setCursor(""))}onLineMouseDown(e){if(!this.isActive||!this.hoverInsert)return;let r=e.features?.[0]?.properties?.shapeId;if(!r||r!==this.hoverInsert.shapeId)return;let a=this.findShape(r);if(!a)return;e.preventDefault();let s={id:_("measure-point"),lngLat:this.hoverInsert.lngLat};a.points.splice(this.hoverInsert.index+1,0,s),this.recomputeShape(a),this.hoverInsert=null,this.renderHoverPoint(),this.render(),this.emitChange(),this.beginPointDrag(r,s.id)}renderHoverPoint(){let e=this.hoverInsert?[{type:"Feature",properties:{},geometry:{type:"Point",coordinates:this.hoverInsert.lngLat}}]:[];this.setSourceData(this.hoverPointSourceId,{type:"FeatureCollection",features:e})}onPointContextMenu(e){if(!this.isActive)return;let t=e.features?.[0],r=t?.properties?.shapeId,a=t?.properties?.pointId;!r||!a||(e.preventDefault(),this.removePoint(r,a))}setCursor(e){this.map.getCanvas().style.cursor=e}onStyleLoad(){this.refresh()}isMapUsable(){return!this.destroyed&&!!this.map.style}emitChange(){this.onChange?.(this.getState())}ensureLayers(){if(!(!this.isMapUsable()||this.ensuringLayers)){this.ensuringLayers=!0;try{this.createMissingLayers()}catch{}finally{this.ensuringLayers=!1}}}createMissingLayers(){let e={...Me,...this.style};this.map.getSource(this.linesSourceId)||this.map.addSource(this.linesSourceId,{type:"geojson",data:k()}),this.map.getSource(this.fillsSourceId)||this.map.addSource(this.fillsSourceId,{type:"geojson",data:k()}),this.map.getSource(this.pointsSourceId)||this.map.addSource(this.pointsSourceId,{type:"geojson",data:k()}),this.map.getSource(this.hoverPointSourceId)||this.map.addSource(this.hoverPointSourceId,{type:"geojson",data:k()}),this.map.getLayer(this.fillsLayerId)||this.map.addLayer({id:this.fillsLayerId,type:"fill",source:this.fillsSourceId,paint:{"fill-color":e.fillColor,"fill-opacity":e.fillOpacity}}),this.map.getLayer(this.linesCasingLayerId)||this.map.addLayer({id:this.linesCasingLayerId,type:"line",source:this.linesSourceId,layout:{"line-cap":"round","line-join":"round"},paint:{"line-color":"#FFFFFF","line-width":e.lineWidth+3,"line-opacity":.9}}),this.map.getLayer(this.linesLayerId)||this.map.addLayer({id:this.linesLayerId,type:"line",source:this.linesSourceId,layout:{"line-cap":"round","line-join":"round"},paint:{"line-color":e.lineColor,"line-width":e.lineWidth,...this.style.lineDasharray?{"line-dasharray":this.style.lineDasharray}:{}}}),this.map.getLayer(this.hoverPointLayerId)||this.map.addLayer({id:this.hoverPointLayerId,type:"circle",source:this.hoverPointSourceId,paint:{"circle-radius":Math.max(3,e.pointRadius-1),"circle-color":e.pointColor,"circle-stroke-color":e.pointStrokeColor,"circle-stroke-width":e.pointStrokeWidth,"circle-opacity":.8,"circle-stroke-opacity":.8}}),this.map.getLayer(this.pointsLayerId)||this.map.addLayer({id:this.pointsLayerId,type:"circle",source:this.pointsSourceId,paint:{"circle-radius":e.pointRadius,"circle-color":e.pointColor,"circle-stroke-color":e.pointStrokeColor,"circle-stroke-width":e.pointStrokeWidth}}),this.bindLayerHandlers()}applyPaintStyle(e=!1){if(!this.isMapUsable())return;let t={...Me,...this.style},r=(a,s,n)=>{this.map.getLayer(a)&&this.map.setPaintProperty(a,s,n)};r(this.fillsLayerId,"fill-color",t.fillColor),r(this.fillsLayerId,"fill-opacity",t.fillOpacity),r(this.linesCasingLayerId,"line-width",t.lineWidth+3),r(this.linesLayerId,"line-color",t.lineColor),r(this.linesLayerId,"line-width",t.lineWidth),this.style.lineDasharray!==void 0?r(this.linesLayerId,"line-dasharray",this.style.lineDasharray):e&&r(this.linesLayerId,"line-dasharray",null),r(this.hoverPointLayerId,"circle-radius",Math.max(3,t.pointRadius-1)),r(this.hoverPointLayerId,"circle-color",t.pointColor),r(this.hoverPointLayerId,"circle-stroke-color",t.pointStrokeColor),r(this.hoverPointLayerId,"circle-stroke-width",t.pointStrokeWidth),r(this.pointsLayerId,"circle-radius",t.pointRadius),r(this.pointsLayerId,"circle-color",t.pointColor),r(this.pointsLayerId,"circle-stroke-color",t.pointStrokeColor),r(this.pointsLayerId,"circle-stroke-width",t.pointStrokeWidth)}removeLayers(){[this.pointsLayerId,this.hoverPointLayerId,this.linesLayerId,this.linesCasingLayerId,this.fillsLayerId].forEach(e=>{this.map.getLayer(e)&&this.map.removeLayer(e)}),[this.pointsSourceId,this.hoverPointSourceId,this.linesSourceId,this.fillsSourceId].forEach(e=>{this.map.getSource(e)&&this.map.removeSource(e)})}setSourceData(e,t){this.map.getSource(e)?.setData(t)}buildLineFeature(e){if(e.points.length<2)return null;let t=e.points.map(r=>r.lngLat);return{type:"Feature",id:e.id,properties:{shapeId:e.id},geometry:{type:"LineString",coordinates:e.closed?[...t,t[0]]:t}}}buildFillFeature(e){if(e.mode!=="area"||e.points.length<3)return null;let t=e.points.map(r=>r.lngLat);return{type:"Feature",id:e.id,properties:{shapeId:e.id},geometry:{type:"Polygon",coordinates:[[...t,t[0]]]}}}buildPointFeatures(e){return e.points.map(t=>({type:"Feature",id:t.id,properties:{shapeId:e.id,pointId:t.id},geometry:{type:"Point",coordinates:t.lngLat}}))}getShapeAnchor(e){let t=e.points.map(r=>r.lngLat);return e.mode==="area"?J(t):q(t)}render(){this.ensureLayers();let e=this.shapes,t=e.map(s=>this.buildLineFeature(s)).filter(s=>!!s),r=e.map(s=>this.buildFillFeature(s)).filter(s=>!!s),a=e.flatMap(s=>this.buildPointFeatures(s));if(this.draft){let s=this.buildLineFeature(this.draft),n=this.buildFillFeature(this.draft);s&&t.push(s),n&&r.push(n),a.push(...this.buildPointFeatures(this.draft))}this.setSourceData(this.linesSourceId,{type:"FeatureCollection",features:t}),this.setSourceData(this.fillsSourceId,{type:"FeatureCollection",features:r}),this.setSourceData(this.pointsSourceId,{type:"FeatureCollection",features:a}),this.updateBadge(),this.syncShapeBadges()}syncShapeBadges(){let e=new Set(this.shapes.map(t=>t.id));Array.from(this.shapeBadges.keys()).forEach(t=>{e.has(t)||(this.shapeBadges.get(t)?.destroy(),this.shapeBadges.delete(t))}),this.shapes.forEach(t=>{if(t.points.length<P(t.mode)){this.shapeBadges.get(t.id)?.destroy(),this.shapeBadges.delete(t.id);return}let r=t.mode==="area"?Le(t.area,this.labels):Z(t.distance,this.labels),a=this.shapeBadges.get(t.id);a||(a=new I(this.map.getContainer(),this.style,this.icons,()=>this.removeShape(t.id)),this.shapeBadges.set(t.id,a)),a.setValue(r);let s=this.map.project(this.getShapeAnchor(t));a.setPosition(s.x,s.y)})}updateShapeBadgePositions(){this.shapes.forEach(e=>{let t=this.shapeBadges.get(e.id);if(!t)return;let r=this.map.project(this.getShapeAnchor(e));t.setPosition(r.x,r.y)})}updateBadge(){if(!this.badge)return;if(!this.isActive||!this.draft||this.draft.points.length===0){this.badge.hide();return}let e=this.draft.points.length>=P(this.draft.mode),t=this.draft.mode==="area"?Le(this.draft.area,this.labels):Z(this.draft.distance,this.labels);this.badge.setValue(e?t:Z(this.draft.distance,this.labels)),this.badge.setCheckEnabled(e),this.badge.show(),this.updateBadgePosition()}updateBadgePosition(){if(!this.badge||!this.draft||this.draft.points.length===0||!this.isActive)return;let e=this.draft.points[this.draft.points.length-1];if(!e)return;let t=this.map.project(e.lngLat);this.badge.setPosition(t.x,t.y)}};export{$ as MahalMap,O as MahalMapDefaultMarker,E as MeasureTool,he as Router,ce as Search,ge as SearchByLocation,me as keyUtils,be as measureUtils,pe as utils};
114
114
  //# sourceMappingURL=index.mjs.map