mahal_map 1.6.21 → 1.6.22

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 Me=Object.defineProperty;var k=(i,e)=>{for(var t in e)Me(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 X="https://platform.mahal.tj/api/",D=/^([-+]?(?:[1-8]?\d(?:\.\d+)?|90(?:\.0+)?)),\s*([-+]?(?:180(?:\.0+)?|(?:(?:1[0-7]\d)|(?:[1-9]?\d))(?:\.\d+)?))$/,B=/^([-+]?(?:180(?:\.0+)?|(?:(?:1[0-7]\d)|(?:[1-9]?\d))(?:\.\d+)?)),\s*([-+]?(?:[1-8]?\d(?:\.\d+)?|90(?:\.0+)?))$/;var Y="https://mtile.gram.tj/custom-styles/dark-style.json",Q="https://mtile.gram.tj/custom-styles/mapstyle.json",ee="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"};function T(i,e){return`${i}/maps/${e}.json`}function Z(i,e,t){let r=i.includes("?")?"&":"?";return`${i}${r}${e}=${encodeURIComponent(t)}`}function F(i,e,t){let r=i;return t&&(r=Z(r,"token",t)),e==="ru"&&(r=Z(r,"lang","ru")),r}var R="";function Le(i){i!==""&&(R=i)}function be(){R=""}var y=()=>R;var Ce=/<svg[\s>]/i,Se=/<(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}"`)},xe=i=>i.replace(/&/g,"&amp;").replace(/"/g,"&quot;"),te=i=>`<image href="${xe(i)}" x="14" y="12" width="22" height="22" style="filter: brightness(0) invert(1);" />`,we=i=>{let e=i.trim();if(Ce.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>`},Ie=({innerSvg:i,innerUrl:e})=>{let t=i?.trim(),r=e?.trim();return t?Se.test(t)?we(t):te(t):r?te(r):""},re=(i,e={})=>`<svg
1
+ var be=Object.defineProperty;var k=(i,e)=>{for(var t in e)be(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 X="https://platform.mahal.tj/api/",B=/^([-+]?(?:[1-8]?\d(?:\.\d+)?|90(?:\.0+)?)),\s*([-+]?(?:180(?:\.0+)?|(?:(?:1[0-7]\d)|(?:[1-9]?\d))(?:\.\d+)?))$/,T=/^([-+]?(?:180(?:\.0+)?|(?:(?:1[0-7]\d)|(?:[1-9]?\d))(?:\.\d+)?)),\s*([-+]?(?:[1-8]?\d(?:\.\d+)?|90(?:\.0+)?))$/;var Y="https://mtile.gram.tj/custom-styles/dark-style.json",Q="https://mtile.gram.tj/custom-styles/mapstyle.json",ee="https://mtile.gram.tj/custom-styles/style_maptiler_basic_hn.json";var A="https://navi.gram.tj",L={light:"road-urban-lab-v2",dark:"standard-night"},Le=["/maps","/tiles","/objects3d","/traffic","/data","/key"];function R(i,e){return`${i}/maps/${e}.json`}function te(i,e){let t=i.replace(/\/+$/,"");return r=>{if(!r)return;let a=r.startsWith("/"),s=a?`${t}${r}`:r;if(!s.startsWith(t))return;let o=s.slice(t.length).split("?")[0];return!Le.some(l=>o===l||o.startsWith(`${l}/`))||!e||/[?&]key=/.test(s)?a?{url:s}:void 0:{url:D(s,"key",e)}}}function D(i,e,t){let r=i.includes("?")?"&":"?";return`${i}${r}${e}=${encodeURIComponent(t)}`}function F(i,e,t){let r=i;return t&&(r=D(r,"token",t)),e==="ru"&&(r=D(r,"lang","ru")),r}var H="";function Ce(i){i!==""&&(H=i)}function Se(){H=""}var f=()=>H;var xe=/<svg[\s>]/i,we=/<(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}"`)},Ie=i=>i.replace(/&/g,"&amp;").replace(/"/g,"&quot;"),re=i=>`<image href="${Ie(i)}" x="14" y="12" width="22" height="22" style="filter: brightness(0) invert(1);" />`,Pe=i=>{let e=i.trim();if(xe.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>`},Ee=({innerSvg:i,innerUrl:e})=>{let t=i?.trim(),r=e?.trim();return t?we.test(t)?Pe(t):re(t):r?re(r):""},ie=(i,e={})=>`<svg
2
2
  width="50"
3
3
  height="62"
4
4
  viewBox="0 0 50 62"
@@ -20,7 +20,7 @@ var Me=Object.defineProperty;var k=(i,e)=>{for(var t in e)Me(i,t,{get:e[t],enume
20
20
  stroke-width="2"
21
21
  />
22
22
  <g clip-path="url(#clip0_367_31358)">
23
- ${Ie(e)}
23
+ ${Ee(e)}
24
24
  </g>
25
25
  <defs>
26
26
  <filter
@@ -67,7 +67,7 @@ var Me=Object.defineProperty;var k=(i,e)=>{for(var t in e)Me(i,t,{get:e[t],enume
67
67
  />
68
68
  </clipPath>
69
69
  </defs>
70
- </svg>`;var H=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):re(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 ie(i,e,t){return new i.Marker({element:t.getElement(),draggable:t.isDraggable?.()??!1,anchor:t.getAnchor?.()??"center"}).setLngLat(t.getCoordinates()).addTo(e)}var Pe={dark:Y,light:Q},Ee={dark:"#ffffff",light:"#19191a"},h=class h{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.maps3dLayerReady=!1;this.maps3dLayerAttachPending=!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){h.defaultLanguage=h.normalizeLanguage(e)}static getDefaultStyle(e,t){return F(Pe[e],t,h.getMapToken())}static getVectorStyle(){return F(ee,void 0,h.getMapToken())}static getMapToken(){let e=y();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 s=(typeof window<"u"?window.maplibregl:void 0)||t;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=h.normalizeLanguage(e.lang||h.defaultLanguage),p=e.theme==="dark"?"dark":"light",l=e.engine==="3d"?"3d":"legacy",n=new h,u=h.getInstanceKey(e);if(n.options=e,n.language=o,n.instanceKey=u,n.maplibre=s,n.engine=l,l==="3d"){let d=e.enable3D!==!1;n.buildingsEnabled=d,n.gramBase=e.base||A,n.presetIsExplicit=!!e.preset,n.gramPreset=e.preset||b[p],n.maps3dCtor=h.getMaps3DCtor(r);let c=e.style?e.style:T(n.gramBase,n.gramPreset),g=n.maps3dCtor?n.maps3dCtor.transformRequest({base:n.gramBase,apiKey:y()||void 0}):void 0,m=d?58:0;if(n.map=new s.Map({container:e.container||"map",style:c,center:e.center||[69.624024,40.279687],zoom:e.zoom||5,attributionControl:!1,pitch:e.pitch!==void 0?e.pitch:m,...e.bearing!==void 0?{bearing:e.bearing}:{},...g?{transformRequest:g}:{}}),d){if(!n.maps3dCtor)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.maps3dLayer=new n.maps3dCtor({apiKey:y()||void 0,base:n.gramBase,buildings:!0,...e.maps3d}),n.attachMaps3DLayer(n.maps3dLayer),n.map.on("style.load",()=>{n.setNativeBuildingsVisible(!1)})}}else{let d=e.autoAddVectorSource?h.getVectorStyle():e.style?e.style:h.getDefaultStyle(p,o);n.map=new s.Map({container:e.container||"map",style:d,center:e.center||[69.624024,40.279687],zoom:e.zoom||5,attributionControl:!1,...e.pitch!==void 0?{pitch:e.pitch}:{},...e.bearing!==void 0?{bearing:e.bearing}:{}})}return n.addLogo(p),n.map.on("load",()=>{n.isReady=!0,n.camera=new v(n.map),n.readyCallbacks.forEach(d=>d(n.map)),n.readyCallbacks=[]}),h.instances.set(u,n),n}static onReady(e,t){if(!h.instances.has(e)){let a=setInterval(()=>{h.instances.has(e)&&(clearInterval(a),h.onReady(e,t))},50);return}let r=h.getInstance(e);r.isReady?t(r.map):r.readyCallbacks.push(t)}static getInstance(e){let t=h.instances.get(e);if(!t)throw new Error("[MahalMap SDK] Map instance is not created");return t}static hasInstance(e){return h.instances.has(e)}static removeInstance(e){return h.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 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 ie(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(T(this.gramBase,this.gramPreset)),this.updateLogoColor(e);return}this.options.autoAddVectorSource||(this.options.style||this.map.setStyle(h.getDefaultStyle(e,this.language)),this.updateLogoColor(e))}setLanguage(e){if(this.language=h.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(h.getDefaultStyle(t,this.language))}getMaps3DLayer(){return this.maps3dLayer}toggle3DBuildings(e){if(this.engine==="3d"){if(this.buildingsEnabled=e,this.setNativeBuildingsVisible(!e),!this.maps3dLayer){if(!e||!this.maps3dCtor)return;this.maps3dLayer=new this.maps3dCtor({apiKey:y()||void 0,base:this.gramBase,buildings:!0,...this.options.maps3d}),this.attachMaps3DLayer(this.maps3dLayer);return}if(this.maps3dLayer.setBuildingsEnabled){this.applyMaps3DBuildingMode(e);return}e||(this.maps3dLayer.destroy?.(),this.maps3dLayer.remove?.(),this.maps3dLayer=void 0,this.maps3dLayerReady=!1)}}attachMaps3DLayer(e){this.maps3dLayerAttachPending=!0,this.maps3dLayerReady=!1,Promise.resolve(e.attach(this.map)).then(()=>{this.maps3dLayer===e&&(this.maps3dLayerReady=!0,this.maps3dLayerAttachPending=!1,this.applyMaps3DBuildingMode(this.buildingsEnabled))}).catch(t=>{this.maps3dLayer===e&&(this.maps3dLayer=void 0),this.maps3dLayerReady=!1,this.maps3dLayerAttachPending=!1,this.buildingsEnabled=!1,this.setNativeBuildingsVisible(!0),console.error("[MahalMap SDK] Failed to attach Maps3D layer",t)})}applyMaps3DBuildingMode(e){this.maps3dLayer&&(this.maps3dLayer.setBuildingsEnabled?.(e),this.maps3dLayer.buildings?.setWindows?.(e))}setNativeBuildingsVisible(e){let t=this.map.getStyle()?.layers||[];for(let r of t){let a=r.id.startsWith("maps3d-"),s=r.type==="fill-extrusion"||"source-layer"in r&&r.type==="fill"&&r["source-layer"]==="building";if(!(a||!s))try{this.map.setLayoutProperty(r.id,"visibility",e?"visible":"none")}catch{}}}setCenter(e){this.map.setCenter(e)}setZoom(e){this.map.setZoom(e)}destroy(){this.maps3dLayer?.destroy?.(),this.maps3dLayer?.remove?.(),this.maps3dLayer=void 0,this.maps3dLayerReady=!1,this.maps3dLayerAttachPending=!1,this.logoObserver?.disconnect(),this.logoObserver=void 0,this.logoHost?.remove(),this.logoHost=void 0,this.logoShadow=void 0,this.map.remove(),h.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 G=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):ie(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 se(i,e,t){return new i.Marker({element:t.getElement(),draggable:t.isDraggable?.()??!1,anchor:t.getAnchor?.()??"center"}).setLngLat(t.getCoordinates()).addTo(e)}var ke={dark:Y,light:Q},De={dark:"#ffffff",light:"#19191a"},h=class h{constructor(){this.isReady=!1;this.readyCallbacks=[];this.language="tj";this.instanceKey="";this.engine="legacy";this.gramBase=A;this.gramPreset=L.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){h.defaultLanguage=h.normalizeLanguage(e)}static getDefaultStyle(e,t){return F(ke[e],t,h.getMapToken())}static getVectorStyle(){return F(ee,void 0,h.getMapToken())}static getMapToken(){let e=f();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=h.normalizeLanguage(e.lang||h.defaultLanguage),p=e.theme==="dark"?"dark":"light",l=e.engine==="3d"?"3d":"legacy",n=new h,u=h.getInstanceKey(e);if(n.options=e,n.language=o,n.instanceKey=u,n.maplibre=s,n.engine=l,l==="3d"){let d=e.enable3D!==!1;n.buildingsEnabled=d,n.gramBase=e.base||A,n.presetIsExplicit=!!e.preset,n.gramPreset=e.preset||L[p],n.maps3dCtor=h.getMaps3DCtor(r);let c=e.style?e.style:R(n.gramBase,n.gramPreset),g=n.maps3dCtor?n.maps3dCtor.transformRequest({base:n.gramBase,apiKey:f()||void 0}):te(n.gramBase,f()),m=d?58:0;if(n.map=new s.Map({container:e.container||"map",style:c,center:e.center||[69.624024,40.279687],zoom:e.zoom!==void 0?e.zoom:5,attributionControl:!1,pitch:e.pitch!==void 0?e.pitch:m,...e.bearing!==void 0?{bearing:e.bearing}:{},...g?{transformRequest:g}:{}}),n.map.on("style.load",()=>{n.setNativeBuildingsVisible(!n.buildingsEnabled)}),d){if(!n.maps3dCtor)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.maps3dLayer=new n.maps3dCtor({apiKey:f()||void 0,base:n.gramBase,buildings:!0,...e.maps3d}),n.attachMaps3DLayer(n.maps3dLayer)}}else{let d=e.autoAddVectorSource?h.getVectorStyle():e.style?e.style:h.getDefaultStyle(p,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(p),n.map.on("load",()=>{n.isReady=!0,n.camera=new v(n.map),n.readyCallbacks.forEach(d=>d(n.map)),n.readyCallbacks=[]}),h.instances.set(u,n),n}static onReady(e,t){if(!h.instances.has(e)){let a=setInterval(()=>{h.instances.has(e)&&(clearInterval(a),h.onReady(e,t))},50);return}let r=h.getInstance(e);r.isReady?t(r.map):r.readyCallbacks.push(t)}static getInstance(e){let t=h.instances.get(e);if(!t)throw new Error("[MahalMap SDK] Map instance is not created");return t}static hasInstance(e){return h.instances.has(e)}static removeInstance(e){return h.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 se(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=L[e],this.map.setStyle(R(this.gramBase,this.gramPreset)),this.updateLogoColor(e);return}this.options.autoAddVectorSource||(this.options.style||this.map.setStyle(h.getDefaultStyle(e,this.language)),this.updateLogoColor(e))}setLanguage(e){if(this.language=h.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(h.getDefaultStyle(t,this.language))}getMaps3DLayer(){return this.maps3dLayer}toggle3DBuildings(e){if(this.engine==="3d"){if(this.buildingsEnabled=e,this.setNativeBuildingsVisible(!e),!this.maps3dLayer){if(this.maps3dCtor=this.maps3dCtor||h.getMaps3DCtor(),!e||!this.maps3dCtor)return;this.maps3dLayer=new this.maps3dCtor({apiKey:f()||void 0,base:this.gramBase,buildings:!0,...this.options.maps3d}),this.attachMaps3DLayer(this.maps3dLayer);return}if(this.maps3dLayer.setBuildingsEnabled){this.applyMaps3DBuildingMode(e);return}e||(this.maps3dLayer.destroy?.(),this.maps3dLayer.remove?.(),this.maps3dLayer=void 0,this.maps3dReady=void 0)}}whenMaps3DReady(){return this.maps3dReady||Promise.resolve(void 0)}attachMaps3DLayer(e){this.maps3dReady=Promise.resolve(e.attach(this.map)).then(()=>{if(this.maps3dLayer===e)return this.applyMaps3DBuildingMode(this.buildingsEnabled),e}).catch(t=>{this.maps3dLayer===e&&(this.maps3dLayer=void 0),this.buildingsEnabled=!1,this.setNativeBuildingsVisible(!0),console.error("[MahalMap SDK] Failed to attach Maps3D layer",t)})}applyMaps3DBuildingMode(e){this.maps3dLayer&&(this.maps3dLayer.setBuildingsEnabled?.(e),this.maps3dLayer.buildings?.setWindows?.(e))}setNativeBuildingsVisible(e){let t=this.map.getStyle()?.layers||[];for(let r of t){let a=r.id.startsWith("maps3d-"),s="source-layer"in r?r["source-layer"]:void 0,o=(r.type==="fill-extrusion"||r.type==="fill")&&(s==="building"||r.id.toLowerCase().includes("building"));if(!(a||!o))try{this.map.setLayoutProperty(r.id,"visibility",e?"visible":"none")}catch{}}}setCenter(e){this.map.setCenter(e)}setZoom(e){this.map.setZoom(e)}destroy(){this.maps3dLayer?.destroy?.(),this.maps3dLayer?.remove?.(),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(),h.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=`
71
71
  <style>
72
72
  :host {
73
73
  all: initial;
@@ -87,7 +87,7 @@ var Me=Object.defineProperty;var k=(i,e)=>{for(var t in e)Me(i,t,{get:e[t],enume
87
87
  }
88
88
  </style>
89
89
  <span class="logo-wrap" aria-hidden="true">
90
- ${this.getLogoSvg(Ee[e])}
90
+ ${this.getLogoSvg(De[e])}
91
91
  </span>
92
92
  `)}applyLogoHostStyles(){if(!this.logoHost)return;let e=this.logoHost.style;e.setProperty("position","absolute","important"),e.setProperty("right","10px","important"),e.setProperty("bottom","10px","important"),e.setProperty("z-index","1","important"),e.setProperty("display","block","important"),e.setProperty("visibility","visible","important"),e.setProperty("opacity","1","important"),e.setProperty("pointer-events","none","important"),e.setProperty("line-height","0","important"),e.setProperty("width","80px","important"),e.setProperty("height","18.45px","important")}observeLogo(e){this.logoHost&&(this.logoObserver?.disconnect(),this.logoObserver=new MutationObserver(()=>{this.logoHost&&(this.applyLogoHostStyles(),e.contains(this.logoHost)||e.appendChild(this.logoHost))}),this.logoObserver.observe(e,{childList:!0}),this.logoObserver.observe(this.logoHost,{attributes:!0,attributeFilter:["class","style","hidden"]}))}getLogoSvg(e){return`
93
93
  <svg class="logo" width="80" viewBox="0 0 143 33" fill="none" xmlns="http://www.w3.org/2000/svg" style="opacity: 0.95;">
@@ -110,5 +110,5 @@ var Me=Object.defineProperty;var k=(i,e)=>{for(var t in e)Me(i,t,{get:e[t],enume
110
110
  </clipPath>
111
111
  </defs>
112
112
  </svg>
113
- `}};h.instances=new Map,h.defaultLanguage="tj";var G=h;var ce={};k(ce,{Router:()=>le,Search:()=>ue,SearchByLocation:()=>de,clearKey:()=>be,getApiKey:()=>y,saveKey:()=>Le});import ke from"axios";var M=ke.create({baseURL:X});var se=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 oe={};k(oe,{checkCoordinates:()=>De,debounce:()=>O,geojsonPolyline:()=>$,geometryPolyline:()=>ne,trimValue:()=>Te});function De(i){let e,t;if(D.test(i)){let r=i.match(D);r&&([,e,t]=r)}else if(B.test(i)){let r=i.match(B);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 O(i,e){let t;return(...r)=>(t&&clearTimeout(t),new Promise(a=>{t=setTimeout(async()=>{let s=await i(...r);a(s)},e)}))}function $(i){let e=[],t=0,r=i.length,a=0,s=0;for(;t<r;){let o,p=0,l=0;do o=i.charCodeAt(t++)-63,l|=(o&31)<<p,p+=5;while(o>=32);let n=l&1?~(l>>1):l>>1;a+=n,p=0,l=0;do o=i.charCodeAt(t++)-63,l|=(o&31)<<p,p+=5;while(o>=32);let u=l&1?~(l>>1):l>>1;s+=u,e.push([s*1e-5,a*1e-5])}return e}function Be(i){let e="",t=0,r=0;for(let a=0;a<i.length;a++){let[s,o]=i[a],p=Math.round(o*1e5),l=Math.round(s*1e5),n=p-t,u=l-r;t=p,r=l,e+=ae(n)+ae(u)}return e}function ae(i){let e=i<<1;return i<0&&(e=~e),Ae(e)}function Ae(i){let e="";for(;i>=32;)e+=String.fromCharCode((32|i&31)+63),i>>=5;return e+=String.fromCharCode(i+63),e}var ne=Be;function Te(i,e){if(e<=0)return"";let t=i.trim();return e>=t.length?t:t.slice(0,e)}async function le(i,e,t){if(!t)throw new Error("[MahalMap SDK] Router token is required");try{let r=await se(i,t);return r?.data?r.data.map(s=>{let o={...s};return o.route?.routes?.length&&(o.route.routes=o.route.routes.map(p=>({...p,geometry:e==="geojson"&&typeof p.geometry=="string"?$(p.geometry):p.geometry}))),o}):r}catch(r){throw r}}var pe=async i=>{try{return(await M.post("services/getAddress",null,{params:i})).data}catch(e){throw console.error("Error while searching address:",e),e}},he=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 Fe(i,e,t){let r={text:i,token:e,...t};try{return(await pe(r)).data}catch(a){throw a}}var Re=O(Fe,500);async function ue(i,e,t){if(!e)throw new Error("[MahalMap SDK] Search token is required");return await Re(i,e,t)}async function de(i){if(!i.token)throw new Error("[MahalMap SDK] SearchByLocation token is required");let e={...i};try{return await he(e)}catch(t){throw t}}var ve={};k(ve,{MeasureTool:()=>E,haversineDistance:()=>K,lineLength:()=>S,midpoint:()=>J,polygonArea:()=>N,polygonCentroid:()=>z});var V=63710088e-1;function f(i){return i*Math.PI/180}function j(i){return((i+180)%360+360)%360-180}function U(i){return((i+180)%360+360)%360-180}function K(i,e){let[t,r]=i,[a,s]=e,o=f(r),p=f(s),l=f(s-r),n=f(a-t),u=Math.sin(l/2),d=Math.sin(n/2),c=u*u+Math.cos(o)*Math.cos(p)*d*d,g=2*Math.atan2(Math.sqrt(c),Math.sqrt(1-c));return V*g}function S(i){let e=0;for(let t=1;t<i.length;t+=1)e+=K(i[t-1],i[t]);return e}function N(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(j(a[0]-r[0])),o=f(r[1]),p=f(a[1]);e+=s*(2+Math.sin(o)+Math.sin(p))}return Math.abs(e*V*V/2)}function ge(i){let e=i.reduce((t,r)=>[t[0]+r[0],t[1]+r[1]],[0,0]);return[U(e[0]/i.length),e[1]/i.length]}function z(i){if(i.length===0)return[0,0];if(i.length<3)return ge(i);let e=i[0]?.[0]??0,t=i.map(([n,u])=>[e+j(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 ge(t);let p=a/(6*o),l=s/(6*o);return[U(p),l]}function J(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 p=o===0?0:(r-a)/o,l=i[s-1],n=i[s],u=U(l[0]+j(n[0]-l[0])*p),d=l[1]+(n[1]-l[1])*p;return[u,d]}a+=o}return i[i.length-1]}var He=new Set(["svg","g","path","circle","ellipse","rect","line","polyline","polygon"]),Ge=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"]),Oe=new Set(["fill","stroke"]);function $e(i,e){let t=e.trim().toLowerCase();return!(t.includes("javascript:")||t.includes("data:")||t.includes("expression(")||Oe.has(i)&&t.includes("url("))}function me(i){return He.has(i.tagName.toLowerCase())?(Array.from(i.attributes).forEach(e=>{let t=e.name.toLowerCase();(!Ge.has(t)||!$e(t,e.value))&&i.removeAttribute(e.name)}),Array.from(i.children).forEach(e=>{me(e)||e.remove()}),!0):!1}function Ve(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")||!me(t)?null:new XMLSerializer().serializeToString(t)}catch{return null}}function L(i,e){return i?Ve(i)??e:e}var fe='<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>',je='<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>',Ue='<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,fe),this.closeButton.innerHTML=L(r.close,je),this.checkButton.innerHTML=L(r.check,Ue);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)}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()}},w=class{constructor(e,t,r,a){this.wrapper=document.createElement("div"),this.valueEl=document.createElement("span"),this.trashButton=document.createElement("button");let s=this.wrapper.style;s.position="absolute",s.zIndex="4",s.display="flex",s.alignItems="center",s.gap=t.badgeGap??"6px",s.padding="5px 7px",s.background=t.badgeBackground??"#FFFFFF",s.borderRadius=t.badgeBorderRadius??"12px",s.boxShadow=t.badgeBoxShadow??"0 2px 10px rgba(15, 23, 42, 0.18)",s.border=t.badgeBorder??"1px solid rgba(0,0,0,0.06)",s.transform="translate(-50%, -50%)",s.pointerEvents="auto",s.userSelect="none",s.whiteSpace="nowrap";let o=this.valueEl.style;o.color=t.badgeTextColor??"#19191A",o.fontSize=t.badgeFontSize??"13px",o.fontWeight=t.badgeFontWeight??"600",o.lineHeight="16px";let p=t.iconButtonSize??"20px",l=this.trashButton.style;l.display="inline-flex",l.alignItems="center",l.justifyContent="center",l.width=p,l.height=p,l.border="none",l.background="transparent",l.cursor="pointer",l.color=t.badgeTextColor??"#535969",l.padding="0",this.trashButton.type="button",this.trashButton.innerHTML=L(r.trash,fe);let n=u=>{u.preventDefault(),u.stopPropagation()};this.wrapper.addEventListener("mousedown",n),this.wrapper.addEventListener("dblclick",n),this.wrapper.addEventListener("contextmenu",n),this.trashButton.addEventListener("click",u=>{n(u),a()}),this.wrapper.appendChild(this.valueEl),this.wrapper.appendChild(this.trashButton),e.appendChild(this.wrapper)}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 Ke=0,_=i=>`${i}-${Date.now().toString(36)}-${Ke+=1}`,Ne=0,ze=()=>`mahal-measure-${Ne+=1}`,Je={pointColor:"#FFFFFF",pointStrokeColor:"#278960",pointStrokeWidth:2,pointRadius:5,lineColor:"#278960",lineWidth:3,fillColor:"#278960",fillOpacity:.15};function q(i,e){return i>=1e3?`${(i/1e3).toFixed(2)} ${e.kilometers??"\u043A\u043C"}`:`${Math.round(i)} ${e.meters??"\u043C"}`}function ye(i,e){return i>=1e5?`${(i/1e6).toFixed(2)} ${e.squareKilometers??"\u043A\u043C\xB2"}`:`${Math.round(i)} ${e.squareMeters??"\u043C\xB2"}`}function I(i){return i==="area"?3:2}function P(){return{type:"FeatureCollection",features:[]}}var E=class{constructor(e,t={}){this.layerHandlersBound=!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.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??ze(),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.map.isStyleLoaded()&&(this.ensureLayers(),this.bindLayerHandlers()),this.map.on("click",this.handleClick),this.map.on("style.load",this.handleStyleLoad),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<I(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()}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.map.off("click",this.handleClick),this.unbindLayerHandlers(),this.map.off("style.load",this.handleStyleLoad),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>=I(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=N(t),e.distance=S([...t,t[0]]);return}e.closed=!1,e.area=0,e.distance=S(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 p=Math.max(0,Math.min(1,((e.x-t.x)*a+(e.y-t.y)*s)/o));return{x:t.x+a*p,y:t.y+s*p}}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,p=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,W=Math.sqrt(g*g+m*m);W<p&&(p=W,s=n,o=c)}if(s===-1||!o)return null;let l=this.map.unproject([o.x,o.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.ensureLayers(),this.bindLayerHandlers(),this.render()}emitChange(){this.onChange?.(this.getState())}ensureLayers(){let e={...Je,...this.style};this.map.getSource(this.linesSourceId)||this.map.addSource(this.linesSourceId,{type:"geojson",data:P()}),this.map.getSource(this.fillsSourceId)||this.map.addSource(this.fillsSourceId,{type:"geojson",data:P()}),this.map.getSource(this.pointsSourceId)||this.map.addSource(this.pointsSourceId,{type:"geojson",data:P()}),this.map.getSource(this.hoverPointSourceId)||this.map.addSource(this.hoverPointSourceId,{type:"geojson",data:P()}),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}})}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"?z(t):J(t)}render(){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<I(t.mode)){this.shapeBadges.get(t.id)?.destroy(),this.shapeBadges.delete(t.id);return}let r=t.mode==="area"?ye(t.area,this.labels):q(t.distance,this.labels),a=this.shapeBadges.get(t.id);a||(a=new w(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>=I(this.draft.mode),t=this.draft.mode==="area"?ye(this.draft.area,this.labels):q(this.draft.distance,this.labels);this.badge.setValue(e?t:q(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{G as MahalMap,H as MahalMapDefaultMarker,E as MeasureTool,le as Router,ue as Search,de as SearchByLocation,ce as keyUtils,ve as measureUtils,oe as utils};
113
+ `}};h.instances=new Map,h.defaultLanguage="tj";var O=h;var ge={};k(ge,{Router:()=>pe,Search:()=>de,SearchByLocation:()=>ce,clearKey:()=>Se,getApiKey:()=>f,saveKey:()=>Ce});import Be from"axios";var M=Be.create({baseURL:X});var ae=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 le={};k(le,{checkCoordinates:()=>Te,debounce:()=>$,geojsonPolyline:()=>V,geometryPolyline:()=>oe,trimValue:()=>Fe});function Te(i){let e,t;if(B.test(i)){let r=i.match(B);r&&([,e,t]=r)}else if(T.test(i)){let r=i.match(T);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 $(i,e){let t;return(...r)=>(t&&clearTimeout(t),new Promise(a=>{t=setTimeout(async()=>{let s=await i(...r);a(s)},e)}))}function V(i){let e=[],t=0,r=i.length,a=0,s=0;for(;t<r;){let o,p=0,l=0;do o=i.charCodeAt(t++)-63,l|=(o&31)<<p,p+=5;while(o>=32);let n=l&1?~(l>>1):l>>1;a+=n,p=0,l=0;do o=i.charCodeAt(t++)-63,l|=(o&31)<<p,p+=5;while(o>=32);let u=l&1?~(l>>1):l>>1;s+=u,e.push([s*1e-5,a*1e-5])}return e}function Ae(i){let e="",t=0,r=0;for(let a=0;a<i.length;a++){let[s,o]=i[a],p=Math.round(o*1e5),l=Math.round(s*1e5),n=p-t,u=l-r;t=p,r=l,e+=ne(n)+ne(u)}return e}function ne(i){let e=i<<1;return i<0&&(e=~e),Re(e)}function Re(i){let e="";for(;i>=32;)e+=String.fromCharCode((32|i&31)+63),i>>=5;return e+=String.fromCharCode(i+63),e}var oe=Ae;function Fe(i,e){if(e<=0)return"";let t=i.trim();return e>=t.length?t:t.slice(0,e)}async function pe(i,e,t){if(!t)throw new Error("[MahalMap SDK] Router token is required");try{let r=await ae(i,t);return r?.data?r.data.map(s=>{let o={...s};return o.route?.routes?.length&&(o.route.routes=o.route.routes.map(p=>({...p,geometry:e==="geojson"&&typeof p.geometry=="string"?V(p.geometry):p.geometry}))),o}):r}catch(r){throw r}}var he=async i=>{try{return(await M.post("services/getAddress",null,{params:i})).data}catch(e){throw console.error("Error while searching address:",e),e}},ue=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 He(i,e,t){let r={text:i,token:e,...t};try{return(await he(r)).data}catch(a){throw a}}var Ge=$(He,500);async function de(i,e,t){if(!e)throw new Error("[MahalMap SDK] Search token is required");return await Ge(i,e,t)}async function ce(i){if(!i.token)throw new Error("[MahalMap SDK] SearchByLocation token is required");let e={...i};try{return await ue(e)}catch(t){throw t}}var Me={};k(Me,{MeasureTool:()=>E,haversineDistance:()=>z,lineLength:()=>S,midpoint:()=>W,polygonArea:()=>N,polygonCentroid:()=>J});var j=63710088e-1;function y(i){return i*Math.PI/180}function U(i){return((i+180)%360+360)%360-180}function K(i){return((i+180)%360+360)%360-180}function z(i,e){let[t,r]=i,[a,s]=e,o=y(r),p=y(s),l=y(s-r),n=y(a-t),u=Math.sin(l/2),d=Math.sin(n/2),c=u*u+Math.cos(o)*Math.cos(p)*d*d,g=2*Math.atan2(Math.sqrt(c),Math.sqrt(1-c));return j*g}function S(i){let e=0;for(let t=1;t<i.length;t+=1)e+=z(i[t-1],i[t]);return e}function N(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=y(U(a[0]-r[0])),o=y(r[1]),p=y(a[1]);e+=s*(2+Math.sin(o)+Math.sin(p))}return Math.abs(e*j*j/2)}function me(i){let e=i.reduce((t,r)=>[t[0]+r[0],t[1]+r[1]],[0,0]);return[K(e[0]/i.length),e[1]/i.length]}function J(i){if(i.length===0)return[0,0];if(i.length<3)return me(i);let e=i[0]?.[0]??0,t=i.map(([n,u])=>[e+U(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 me(t);let p=a/(6*o),l=s/(6*o);return[K(p),l]}function W(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=z(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 p=o===0?0:(r-a)/o,l=i[s-1],n=i[s],u=K(l[0]+U(n[0]-l[0])*p),d=l[1]+(n[1]-l[1])*p;return[u,d]}a+=o}return i[i.length-1]}var Oe=new Set(["svg","g","path","circle","ellipse","rect","line","polyline","polygon"]),$e=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"]),Ve=new Set(["fill","stroke"]);function je(i,e){let t=e.trim().toLowerCase();return!(t.includes("javascript:")||t.includes("data:")||t.includes("expression(")||Ve.has(i)&&t.includes("url("))}function fe(i){return Oe.has(i.tagName.toLowerCase())?(Array.from(i.attributes).forEach(e=>{let t=e.name.toLowerCase();(!$e.has(t)||!je(t,e.value))&&i.removeAttribute(e.name)}),Array.from(i.children).forEach(e=>{fe(e)||e.remove()}),!0):!1}function Ue(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")||!fe(t)?null:new XMLSerializer().serializeToString(t)}catch{return null}}function b(i,e){return i?Ue(i)??e:e}var ye='<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>',Ke='<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>',ze='<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=b(r.trash,ye),this.closeButton.innerHTML=b(r.close,Ke),this.checkButton.innerHTML=b(r.check,ze);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)}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()}},w=class{constructor(e,t,r,a){this.wrapper=document.createElement("div"),this.valueEl=document.createElement("span"),this.trashButton=document.createElement("button");let s=this.wrapper.style;s.position="absolute",s.zIndex="4",s.display="flex",s.alignItems="center",s.gap=t.badgeGap??"6px",s.padding="5px 7px",s.background=t.badgeBackground??"#FFFFFF",s.borderRadius=t.badgeBorderRadius??"12px",s.boxShadow=t.badgeBoxShadow??"0 2px 10px rgba(15, 23, 42, 0.18)",s.border=t.badgeBorder??"1px solid rgba(0,0,0,0.06)",s.transform="translate(-50%, -50%)",s.pointerEvents="auto",s.userSelect="none",s.whiteSpace="nowrap";let o=this.valueEl.style;o.color=t.badgeTextColor??"#19191A",o.fontSize=t.badgeFontSize??"13px",o.fontWeight=t.badgeFontWeight??"600",o.lineHeight="16px";let p=t.iconButtonSize??"20px",l=this.trashButton.style;l.display="inline-flex",l.alignItems="center",l.justifyContent="center",l.width=p,l.height=p,l.border="none",l.background="transparent",l.cursor="pointer",l.color=t.badgeTextColor??"#535969",l.padding="0",this.trashButton.type="button",this.trashButton.innerHTML=b(r.trash,ye);let n=u=>{u.preventDefault(),u.stopPropagation()};this.wrapper.addEventListener("mousedown",n),this.wrapper.addEventListener("dblclick",n),this.wrapper.addEventListener("contextmenu",n),this.trashButton.addEventListener("click",u=>{n(u),a()}),this.wrapper.appendChild(this.valueEl),this.wrapper.appendChild(this.trashButton),e.appendChild(this.wrapper)}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 Ne=0,_=i=>`${i}-${Date.now().toString(36)}-${Ne+=1}`,Je=0,We=()=>`mahal-measure-${Je+=1}`,_e={pointColor:"#FFFFFF",pointStrokeColor:"#278960",pointStrokeWidth:2,pointRadius:5,lineColor:"#278960",lineWidth:3,fillColor:"#278960",fillOpacity:.15};function q(i,e){return i>=1e3?`${(i/1e3).toFixed(2)} ${e.kilometers??"\u043A\u043C"}`:`${Math.round(i)} ${e.meters??"\u043C"}`}function ve(i,e){return i>=1e5?`${(i/1e6).toFixed(2)} ${e.squareKilometers??"\u043A\u043C\xB2"}`:`${Math.round(i)} ${e.squareMeters??"\u043C\xB2"}`}function I(i){return i==="area"?3:2}function P(){return{type:"FeatureCollection",features:[]}}var E=class{constructor(e,t={}){this.layerHandlersBound=!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.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??We(),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.map.isStyleLoaded()&&(this.ensureLayers(),this.bindLayerHandlers()),this.map.on("click",this.handleClick),this.map.on("style.load",this.handleStyleLoad),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<I(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()}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.map.off("click",this.handleClick),this.unbindLayerHandlers(),this.map.off("style.load",this.handleStyleLoad),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>=I(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=N(t),e.distance=S([...t,t[0]]);return}e.closed=!1,e.area=0,e.distance=S(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 p=Math.max(0,Math.min(1,((e.x-t.x)*a+(e.y-t.y)*s)/o));return{x:t.x+a*p,y:t.y+s*p}}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,p=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,Z=Math.sqrt(g*g+m*m);Z<p&&(p=Z,s=n,o=c)}if(s===-1||!o)return null;let l=this.map.unproject([o.x,o.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.ensureLayers(),this.bindLayerHandlers(),this.render()}emitChange(){this.onChange?.(this.getState())}ensureLayers(){let e={..._e,...this.style};this.map.getSource(this.linesSourceId)||this.map.addSource(this.linesSourceId,{type:"geojson",data:P()}),this.map.getSource(this.fillsSourceId)||this.map.addSource(this.fillsSourceId,{type:"geojson",data:P()}),this.map.getSource(this.pointsSourceId)||this.map.addSource(this.pointsSourceId,{type:"geojson",data:P()}),this.map.getSource(this.hoverPointSourceId)||this.map.addSource(this.hoverPointSourceId,{type:"geojson",data:P()}),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}})}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):W(t)}render(){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<I(t.mode)){this.shapeBadges.get(t.id)?.destroy(),this.shapeBadges.delete(t.id);return}let r=t.mode==="area"?ve(t.area,this.labels):q(t.distance,this.labels),a=this.shapeBadges.get(t.id);a||(a=new w(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>=I(this.draft.mode),t=this.draft.mode==="area"?ve(this.draft.area,this.labels):q(this.draft.distance,this.labels);this.badge.setValue(e?t:q(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{O as MahalMap,G as MahalMapDefaultMarker,E as MeasureTool,pe as Router,de as Search,ce as SearchByLocation,ge as keyUtils,Me as measureUtils,le as utils};
114
114
  //# sourceMappingURL=index.mjs.map