mahal_map 1.6.4 → 1.6.6

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 ne=Object.defineProperty;var v=(r,e)=>{for(var t in e)ne(r,t,{get:e[t],enumerable:!0})};var c=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 O="https://platform.mahal.tj/api/",b=/^([-+]?(?:[1-8]?\d(?:\.\d+)?|90(?:\.0+)?)),\s*([-+]?(?:180(?:\.0+)?|(?:(?:1[0-7]\d)|(?:[1-9]?\d))(?:\.\d+)?))$/,S=/^([-+]?(?:180(?:\.0+)?|(?:(?:1[0-7]\d)|(?:[1-9]?\d))(?:\.\d+)?)),\s*([-+]?(?:[1-8]?\d(?:\.\d+)?|90(?:\.0+)?))$/;var V="https://mtile.gram.tj/custom-styles/dark-style.json",J="https://mtile.gram.tj/custom-styles/mapstyle.json",j="https://mtile.gram.tj/custom-styles/style_maptiler_basic_hn.json";function $(r,e,t){let i=r.includes("?")?"&":"?";return`${r}${i}${e}=${encodeURIComponent(t)}`}function L(r,e,t){let i=r;return t&&(i=$(i,"token",t)),e==="ru"&&(i=$(i,"lang","ru")),i}var x="";function le(r){r!==""&&(x=r)}function pe(){x=""}var I=()=>x;var he=/<svg[\s>]/i,ue=/<(svg|path|g|circle|rect|polygon|line|polyline|ellipse|use)\b/i,m=(r,e,t)=>{let i=new RegExp(`\\s${e}="[^"]*"`,"i");return i.test(r)?r.replace(i,` ${e}="${t}"`):r.replace(/<svg\b/i,`<svg ${e}="${t}"`)},de=r=>r.replace(/&/g,"&amp;").replace(/"/g,"&quot;"),U=r=>`<image href="${de(r)}" x="14" y="12" width="22" height="22" style="filter: brightness(0) invert(1);" />`,ce=r=>{let e=r.trim();if(he.test(e)){let t=m(e,"x","14");return t=m(t,"y","12"),t=m(t,"width","22"),t=m(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:r,innerUrl:e})=>{let t=r?.trim(),i=e?.trim();return t?ue.test(t)?ce(t):U(t):i?U(i):""},K=(r,e={})=>`<svg
1
+ var ue=Object.defineProperty;var x=(i,e)=>{for(var t in e)ue(i,t,{get:e[t],enumerable:!0})};var m=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 K="https://platform.mahal.tj/api/",I=/^([-+]?(?:[1-8]?\d(?:\.\d+)?|90(?:\.0+)?)),\s*([-+]?(?:180(?:\.0+)?|(?:(?:1[0-7]\d)|(?:[1-9]?\d))(?:\.\d+)?))$/,w=/^([-+]?(?:180(?:\.0+)?|(?:(?:1[0-7]\d)|(?:[1-9]?\d))(?:\.\d+)?)),\s*([-+]?(?:[1-8]?\d(?:\.\d+)?|90(?:\.0+)?))$/;var N="https://mtile.gram.tj/custom-styles/dark-style.json",z="https://mtile.gram.tj/custom-styles/mapstyle.json",q="https://mtile.gram.tj/custom-styles/style_maptiler_basic_hn.json";function J(i,e,t){let r=i.includes("?")?"&":"?";return`${i}${r}${e}=${encodeURIComponent(t)}`}function P(i,e,t){let r=i;return t&&(r=J(r,"token",t)),e==="ru"&&(r=J(r,"lang","ru")),r}var k="";function de(i){i!==""&&(k=i)}function ce(){k=""}var E=()=>k;var ge=/<svg[\s>]/i,me=/<(svg|path|g|circle|rect|polygon|line|polyline|ellipse|use)\b/i,v=(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;"),Z=i=>`<image href="${fe(i)}" x="14" y="12" width="22" height="22" style="filter: brightness(0) invert(1);" />`,ye=i=>{let e=i.trim();if(ge.test(e)){let t=v(e,"x","14");return t=v(t,"y","12"),t=v(t,"width","22"),t=v(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>`},ve=({innerSvg:i,innerUrl:e})=>{let t=i?.trim(),r=e?.trim();return t?me.test(t)?ye(t):Z(t):r?Z(r):""},_=(i,e={})=>`<svg
2
2
  width="50"
3
3
  height="62"
4
4
  viewBox="0 0 50 62"
@@ -10,17 +10,17 @@ var ne=Object.defineProperty;var v=(r,e)=>{for(var t in e)ne(r,t,{get:e[t],enume
10
10
  fill-rule="evenodd"
11
11
  clip-rule="evenodd"
12
12
  d="M25 2C36.598 2 46 11.402 46 23C46 33.1603 38.7844 41.6353 29.198 43.5803L25.6524 48.6575C25.5788 48.7633 25.4812 48.8497 25.3676 48.9093C25.254 48.9689 25.128 49 25 49C24.872 49 24.746 48.9689 24.6324 48.9093C24.5188 48.8497 24.4212 48.7633 24.3476 48.6575L20.802 43.5803C11.2156 41.6353 4 33.1603 4 23C4 11.402 13.402 2 25 2Z"
13
- fill="${r||"#278960"}"
13
+ fill="${i||"#278960"}"
14
14
  />
15
15
  </g>
16
16
  <path
17
17
  d="M25 51C27.7614 51 30 53.2386 30 56C30 58.7614 27.7614 61 25 61C22.2386 61 20 58.7614 20 56C20 53.2386 22.2386 51 25 51Z"
18
- fill="${r||"#278960"}"
18
+ fill="${i||"#278960"}"
19
19
  stroke="white"
20
20
  stroke-width="2"
21
21
  />
22
22
  <g clip-path="url(#clip0_367_31358)">
23
- ${ge(e)}
23
+ ${ve(e)}
24
24
  </g>
25
25
  <defs>
26
26
  <filter
@@ -67,7 +67,7 @@ var ne=Object.defineProperty;var v=(r,e)=>{for(var t in e)ne(r,t,{get:e[t],enume
67
67
  />
68
68
  </clipPath>
69
69
  </defs>
70
- </svg>`;var w=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):K(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 N(r,e,t){return new r.Marker({element:t.getElement(),draggable:t.isDraggable?.()??!1,anchor:t.getAnchor?.()??"center"}).setLngLat(t.getCoordinates()).addTo(e)}var me={dark:V,light:J},fe={dark:"#ffffff",light:"#19191a"},l=class l{constructor(){this.isReady=!1;this.readyCallbacks=[];this.language="tj";this.instanceKey=""}static getInstanceKey(e){return typeof e.container=="string"&&e.container?e.container:"map"}static normalizeLanguage(e){return e==="ru"?"ru":"tj"}static setDefaultLanguage(e){l.defaultLanguage=l.normalizeLanguage(e)}static getDefaultStyle(e,t){return L(me[e],t,l.getMapToken())}static getVectorStyle(){return L(j,void 0,l.getMapToken())}static getMapToken(){let e=I();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 create(e,t){let a=(typeof window<"u"?window.maplibregl:void 0)||t;if(!a)throw new Error("[MahalMap SDK] MapLibre GL was not found. Pass it as the second argument or include it through a script.");let n=l.normalizeLanguage(e.lang||l.defaultLanguage),s=e.theme==="dark"?"dark":"light",p=e.autoAddVectorSource?l.getVectorStyle():e.style?e.style:l.getDefaultStyle(s,n),o=new l,h=l.getInstanceKey(e);return o.options=e,o.language=n,o.instanceKey=h,o.maplibre=a,o.map=new a.Map({container:e.container||"map",style:p,center:e.center||[69.624024,40.279687],zoom:e.zoom||5,attributionControl:!1}),o.addLogo(s),o.map.on("load",()=>{o.isReady=!0,o.camera=new c(o.map),o.readyCallbacks.forEach(u=>u(o.map)),o.readyCallbacks=[]}),l.instances.set(h,o),o}static onReady(e,t){if(!l.instances.has(e)){let a=setInterval(()=>{l.instances.has(e)&&(clearInterval(a),l.onReady(e,t))},50);return}let i=l.getInstance(e);i.isReady?t(i.map):i.readyCallbacks.push(t)}static getInstance(e){let t=l.instances.get(e);if(!t)throw new Error("[MahalMap SDK] Map instance is not created");return t}static hasInstance(e){return l.instances.has(e)}static removeInstance(e){return l.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 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 N(this.maplibre,this.map,e)}init(e){this.map=e,this.camera=new c(e)}getCamera(){return this.camera}getMap(){return this.map}setStyle(e){this.options.autoAddVectorSource||(this.options.theme=e,this.options.style||this.map.setStyle(l.getDefaultStyle(e,this.language)),this.updateLogoColor(e))}setLanguage(e){if(this.language=l.normalizeLanguage(e),this.options.lang=this.language,this.options.autoAddVectorSource||this.options.style)return;let t=this.options.theme==="dark"?"dark":"light";this.map.setStyle(l.getDefaultStyle(t,this.language))}setCenter(e){this.map.setCenter(e)}setZoom(e){this.map.setZoom(e)}destroy(){this.logoObserver?.disconnect(),this.logoObserver=void 0,this.logoHost?.remove(),this.logoHost=void 0,this.logoShadow=void 0,this.map.remove(),l.instances.delete(this.instanceKey)}addLogo(e){let t=this.map.getContainer(),i=document.createElement("div"),a=i.attachShadow({mode:"closed"});i.setAttribute("aria-label","Mahal"),i.dataset.mahal=Math.random().toString(36).slice(2),this.logoHost=i,this.logoShadow=a,this.applyLogoHostStyles(),this.renderLogo(e),t.appendChild(i),this.observeLogo(t)}updateLogoColor(e){this.logoShadow&&this.renderLogo(e)}renderLogo(e){this.logoShadow&&(this.logoShadow.innerHTML=`
70
+ </svg>`;var B=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):_(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 W(i,e,t){return new i.Marker({element:t.getElement(),draggable:t.isDraggable?.()??!1,anchor:t.getAnchor?.()??"center"}).setLngLat(t.getCoordinates()).addTo(e)}var Me={dark:N,light:z},be={dark:"#ffffff",light:"#19191a"},l=class l{constructor(){this.isReady=!1;this.readyCallbacks=[];this.language="tj";this.instanceKey=""}static getInstanceKey(e){return typeof e.container=="string"&&e.container?e.container:"map"}static normalizeLanguage(e){return e==="ru"?"ru":"tj"}static setDefaultLanguage(e){l.defaultLanguage=l.normalizeLanguage(e)}static getDefaultStyle(e,t){return P(Me[e],t,l.getMapToken())}static getVectorStyle(){return P(q,void 0,l.getMapToken())}static getMapToken(){let e=E();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 create(e,t){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 a=l.normalizeLanguage(e.lang||l.defaultLanguage),n=e.theme==="dark"?"dark":"light",p=e.autoAddVectorSource?l.getVectorStyle():e.style?e.style:l.getDefaultStyle(n,a),o=new l,h=l.getInstanceKey(e);return o.options=e,o.language=a,o.instanceKey=h,o.maplibre=s,o.map=new s.Map({container:e.container||"map",style:p,center:e.center||[69.624024,40.279687],zoom:e.zoom||5,attributionControl:!1}),o.addLogo(n),o.map.on("load",()=>{o.isReady=!0,o.camera=new m(o.map),o.readyCallbacks.forEach(u=>u(o.map)),o.readyCallbacks=[]}),l.instances.set(h,o),o}static onReady(e,t){if(!l.instances.has(e)){let s=setInterval(()=>{l.instances.has(e)&&(clearInterval(s),l.onReady(e,t))},50);return}let r=l.getInstance(e);r.isReady?t(r.map):r.readyCallbacks.push(t)}static getInstance(e){let t=l.instances.get(e);if(!t)throw new Error("[MahalMap SDK] Map instance is not created");return t}static hasInstance(e){return l.instances.has(e)}static removeInstance(e){return l.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 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 W(this.maplibre,this.map,e)}init(e){this.map=e,this.camera=new m(e)}getCamera(){return this.camera}getMap(){return this.map}setStyle(e){this.options.autoAddVectorSource||(this.options.theme=e,this.options.style||this.map.setStyle(l.getDefaultStyle(e,this.language)),this.updateLogoColor(e))}setLanguage(e){if(this.language=l.normalizeLanguage(e),this.options.lang=this.language,this.options.autoAddVectorSource||this.options.style)return;let t=this.options.theme==="dark"?"dark":"light";this.map.setStyle(l.getDefaultStyle(t,this.language))}setCenter(e){this.map.setCenter(e)}setZoom(e){this.map.setZoom(e)}destroy(){this.logoObserver?.disconnect(),this.logoObserver=void 0,this.logoHost?.remove(),this.logoHost=void 0,this.logoShadow=void 0,this.map.remove(),l.instances.delete(this.instanceKey)}addLogo(e){let t=this.map.getContainer(),r=document.createElement("div"),s=r.attachShadow({mode:"closed"});r.setAttribute("aria-label","Mahal"),r.dataset.mahal=Math.random().toString(36).slice(2),this.logoHost=r,this.logoShadow=s,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 ne=Object.defineProperty;var v=(r,e)=>{for(var t in e)ne(r,t,{get:e[t],enume
87
87
  }
88
88
  </style>
89
89
  <span class="logo-wrap" aria-hidden="true">
90
- ${this.getLogoSvg(fe[e])}
90
+ ${this.getLogoSvg(be[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 ne=Object.defineProperty;var v=(r,e)=>{for(var t in e)ne(r,t,{get:e[t],enume
110
110
  </clipPath>
111
111
  </defs>
112
112
  </svg>
113
- `}};l.instances=new Map,l.defaultLanguage="tj";var P=l;var te={};v(te,{Router:()=>W,Search:()=>Q,SearchByLocation:()=>ee,clearKey:()=>pe,getApiKey:()=>I,saveKey:()=>le});import ye from"axios";var g=ye.create({baseURL:O});var Z=async(r,e)=>{try{let t=[];return r.forEach(a=>{t.push({lng:a[0],lat:a[1]})}),(await g.post("services/getRoutes",{points:t,token:e})).data}catch(t){throw console.error(t),t}};var q={};v(q,{checkCoordinates:()=>Me,debounce:()=>k,geojsonPolyline:()=>F,geometryPolyline:()=>z,trimValue:()=>be});function Me(r){let e,t;if(b.test(r)){let i=r.match(b);i&&([,e,t]=i)}else if(S.test(r)){let i=r.match(S);i&&([,t,e]=i)}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 k(r,e){let t;return(...i)=>(t&&clearTimeout(t),new Promise(a=>{t=setTimeout(async()=>{let n=await r(...i);a(n)},e)}))}function F(r){let e=[],t=0,i=r.length,a=0,n=0;for(;t<i;){let s,p=0,o=0;do s=r.charCodeAt(t++)-63,o|=(s&31)<<p,p+=5;while(s>=32);let h=o&1?~(o>>1):o>>1;a+=h,p=0,o=0;do s=r.charCodeAt(t++)-63,o|=(s&31)<<p,p+=5;while(s>=32);let u=o&1?~(o>>1):o>>1;n+=u,e.push([n*1e-5,a*1e-5])}return e}function Ce(r){let e="",t=0,i=0;for(let a=0;a<r.length;a++){let[n,s]=r[a],p=Math.round(s*1e5),o=Math.round(n*1e5),h=p-t,u=o-i;t=p,i=o,e+=_(h)+_(u)}return e}function _(r){let e=r<<1;return r<0&&(e=~e),ve(e)}function ve(r){let e="";for(;r>=32;)e+=String.fromCharCode((32|r&31)+63),r>>=5;return e+=String.fromCharCode(r+63),e}var z=Ce;function be(r,e){if(e<=0)return"";let t=r.trim();return e>=t.length?t:t.slice(0,e)}async function W(r,e,t){if(!t)throw new Error("[MahalMap SDK] Router token is required");try{let i=await Z(r,t);return i?.data?i.data.map(n=>{let s={...n};return s.route?.routes?.length&&(s.route.routes=s.route.routes.map(p=>({...p,geometry:e==="geojson"&&typeof p.geometry=="string"?F(p.geometry):p.geometry}))),s}):i}catch(i){throw i}}var X=async r=>{try{return(await g.post("services/getAddress",null,{params:r})).data}catch(e){throw console.error("Error while searching address:",e),e}},Y=async r=>{try{return(await g.post("services/getAddressByLocation",null,{params:r})).data}catch(e){throw console.error("Error while searching address by location:",e),e}};async function Se(r,e,t){let i={text:r,token:e,...t};try{return(await X(i)).data}catch(a){throw a}}var Le=k(Se,500);async function Q(r,e,t){if(!e)throw new Error("[MahalMap SDK] Search token is required");return await Le(r,e,t)}async function ee(r){if(!r.token)throw new Error("[MahalMap SDK] SearchByLocation token is required");let e={...r};try{return await Y(e)}catch(t){throw t}}var se={};v(se,{MeasureTool:()=>C,haversineDistance:()=>re,lineLength:()=>f,midpoint:()=>B,polygonArea:()=>T,polygonCentroid:()=>A});var E=63710088e-1;function d(r){return r*Math.PI/180}function re(r,e){let[t,i]=r,[a,n]=e,s=d(i),p=d(n),o=d(n-i),h=d(a-t),u=Math.sin(o/2),G=Math.sin(h/2),H=u*u+Math.cos(s)*Math.cos(p)*G*G,oe=2*Math.atan2(Math.sqrt(H),Math.sqrt(1-H));return E*oe}function f(r){let e=0;for(let t=1;t<r.length;t+=1)e+=re(r[t-1],r[t]);return e}function T(r){if(r.length<3)return 0;let e=0;for(let t=0;t<r.length;t+=1){let i=r[t],a=r[(t+1)%r.length],n=d(i[0]),s=d(i[1]),p=d(a[0]),o=d(a[1]);e+=(p-n)*(2+Math.sin(s)+Math.sin(o))}return Math.abs(e*E*E/2)}function A(r){let e=r.reduce((t,i)=>[t[0]+i[0],t[1]+i[1]],[0,0]);return[e[0]/r.length,e[1]/r.length]}function B(r){return r.length===0?[0,0]:r[Math.floor((r.length-1)/2)]}var xe='<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>',Ie='<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>',we='<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>',y=class{constructor(e,t,i,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=i.trash??xe,this.closeButton.innerHTML=i.close??Ie,this.checkButton.innerHTML=i.check??we;let n=s=>{s.preventDefault(),s.stopPropagation()};this.wrapper.addEventListener("mousedown",n),this.wrapper.addEventListener("dblclick",n),this.wrapper.addEventListener("contextmenu",n),this.trashButton.addEventListener("click",s=>{n(s),a.onRemove()}),this.closeButton.addEventListener("click",s=>{n(s),a.onClose()}),this.checkButton.addEventListener("click",s=>{n(s),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 i=e.style,a=t.iconButtonSize??"24px";i.display="inline-flex",i.alignItems="center",i.justifyContent="center",i.width=a,i.height=a,i.border="none",i.background="transparent",i.cursor="pointer",i.color=t.badgeTextColor??"#535969",i.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()}};var Pe=0,ie=r=>`${r}-${Date.now().toString(36)}-${Pe+=1}`,ke={pointColor:"#FFFFFF",pointStrokeColor:"#278960",pointStrokeWidth:2,pointRadius:5,lineColor:"#278960",lineWidth:3,fillColor:"#278960",fillOpacity:.15,labelColor:"#19191A",labelHaloColor:"#FFFFFF"};function D(r,e){return r>=1e3?`${(r/1e3).toFixed(2)} ${e.kilometers??"\u043A\u043C"}`:`${Math.round(r)} ${e.meters??"\u043C"}`}function ae(r,e){return r>=1e5?`${(r/1e6).toFixed(2)} ${e.squareKilometers??"\u043A\u043C\xB2"}`:`${Math.round(r)} ${e.squareMeters??"\u043C\xB2"}`}function R(r){return r==="area"?3:2}function M(){return{type:"FeatureCollection",features:[]}}var C=class{constructor(e,t={}){this.isActive=!1;this.draft=null;this.shapes=[];this.badge=null;this.draggingPointId=null;this.draggingShapeId=null;this.suppressNextClick=!1;this.handleClick=e=>this.onMapClick(e);this.handlePointMouseDown=e=>this.onPointMouseDown(e);this.handlePointMouseEnter=()=>this.setCursor("pointer");this.handlePointMouseLeave=()=>this.setCursor("");this.handlePointContextMenu=e=>this.onPointContextMenu(e);this.handleStyleLoad=()=>this.onStyleLoad();this.handleViewportChange=()=>this.updateBadgePosition();this.onPointDragMove=e=>{if(!this.draggingShapeId||!this.draggingPointId)return;let t=this.findShape(this.draggingShapeId),i=t?.points.find(a=>a.id===this.draggingPointId);!t||!i||(i.lngLat=[+e.lngLat.lng.toFixed(6),+e.lngLat.lat.toFixed(6)],this.recomputeShape(t),this.render(),this.emitChange())};this.onPointDragUp=()=>{this.stopDragListeners(),this.map.dragPan.enable(),this.setCursor("pointer"),this.suppressNextClick=!0};this.map=e,this.prefix=t.sourceIdPrefix??"mahal-measure",this.style=t.style??{},this.labels=t.labels??{},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.labelsSourceId=`${this.prefix}-labels`,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.labelsLayerId=`${this.prefix}-labels-layer`,this.ensureLayers(),this.badge=new y(e.getContainer(),this.style,t.icons??{},{onRemove:()=>this.removeShape((this.draft??this.getLastShape())?.id??""),onClose:()=>this.onCloseRequest?.(),onCheck:()=>this.finishDraft()}),this.map.on("click",this.handleClick),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("style.load",this.handleStyleLoad),this.map.on("move",this.handleViewportChange)}start(e=this.mode){this.isActive=!0,this.setMode(e),this.render(),this.emitChange()}stop(){this.isActive=!1,this.badge?.hide(),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.render(),this.emitChange())}removePoint(e,t){let i=this.findShape(e);if(i){if(i.points=i.points.filter(a=>a.id!==t),i.points.length===0){this.removeShape(e);return}this.recomputeShape(i),this.render(),this.emitChange()}}clearAll(){this.draft=null,this.shapes=[],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.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("style.load",this.handleStyleLoad),this.map.off("move",this.handleViewportChange),this.stopDragListeners(),this.badge?.destroy(),this.badge=null,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>=R(this.draft.mode)&&this.shapes.push(this.draft),this.draft=null)}ensureDraft(){return this.draft||(this.draft={id:ie("measure-shape"),mode:this.mode,points:[],closed:!1,distance:0,area:0}),this.draft}recomputeShape(e){let t=e.points.map(i=>i.lngLat);if(e.mode==="area"&&t.length>=3){e.closed=!0,e.area=T(t),e.distance=f([...t,t[0]]);return}e.closed=!1,e.area=0,e.distance=f(t)}onMapClick(e){if(!this.isActive)return;if(this.suppressNextClick){this.suppressNextClick=!1;return}if(this.map.queryRenderedFeatures(e.point,{layers:[this.pointsLayerId]}).length>0)return;let i=this.ensureDraft();i.points.push({id:ie("measure-point"),lngLat:[+e.lngLat.lng.toFixed(6),+e.lngLat.lat.toFixed(6)]}),this.recomputeShape(i),this.render(),this.emitChange()}onPointMouseDown(e){if(!this.isActive)return;let t=e.features?.[0],i=t?.properties?.shapeId,a=t?.properties?.pointId;!i||!a||(e.preventDefault(),this.draggingShapeId=i,this.draggingPointId=a,this.map.dragPan.disable(),this.setCursor("grabbing"),this.map.on("mousemove",this.onPointDragMove),this.map.on("mouseup",this.onPointDragUp))}stopDragListeners(){this.map.off("mousemove",this.onPointDragMove),this.map.off("mouseup",this.onPointDragUp),this.draggingShapeId=null,this.draggingPointId=null}onPointContextMenu(e){if(!this.isActive)return;let t=e.features?.[0],i=t?.properties?.shapeId,a=t?.properties?.pointId;!i||!a||(e.preventDefault(),this.removePoint(i,a))}setCursor(e){this.map.getCanvas().style.cursor=e}onStyleLoad(){this.ensureLayers(),this.render()}emitChange(){this.onChange?.(this.getState())}ensureLayers(){let e={...ke,...this.style};this.map.getSource(this.linesSourceId)||this.map.addSource(this.linesSourceId,{type:"geojson",data:M()}),this.map.getSource(this.fillsSourceId)||this.map.addSource(this.fillsSourceId,{type:"geojson",data:M()}),this.map.getSource(this.pointsSourceId)||this.map.addSource(this.pointsSourceId,{type:"geojson",data:M()}),this.map.getSource(this.labelsSourceId)||this.map.addSource(this.labelsSourceId,{type:"geojson",data:M()}),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.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.map.getLayer(this.labelsLayerId)||this.map.addLayer({id:this.labelsLayerId,type:"symbol",source:this.labelsSourceId,layout:{"text-field":["get","label"],"text-size":13,"text-font":["Noto Sans Regular"]},paint:{"text-color":e.labelColor,"text-halo-color":e.labelHaloColor,"text-halo-width":1.4}})}removeLayers(){[this.labelsLayerId,this.pointsLayerId,this.linesLayerId,this.linesCasingLayerId,this.fillsLayerId].forEach(e=>{this.map.getLayer(e)&&this.map.removeLayer(e)}),[this.labelsSourceId,this.pointsSourceId,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(i=>i.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(i=>i.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}}))}buildLabelFeature(e){if(e.points.length<R(e.mode))return null;let t=e.points.map(n=>n.lngLat),i=e.mode==="area"?A(t):B(t),a=e.mode==="area"?ae(e.area,this.labels):D(e.distance,this.labels);return{type:"Feature",id:e.id,properties:{shapeId:e.id,label:a},geometry:{type:"Point",coordinates:i}}}render(){let e=this.shapes,t=e.map(s=>this.buildLineFeature(s)).filter(s=>!!s),i=e.map(s=>this.buildFillFeature(s)).filter(s=>!!s),a=e.flatMap(s=>this.buildPointFeatures(s)),n=e.map(s=>this.buildLabelFeature(s)).filter(s=>!!s);if(this.draft){let s=this.buildLineFeature(this.draft),p=this.buildFillFeature(this.draft);s&&t.push(s),p&&i.push(p),a.push(...this.buildPointFeatures(this.draft))}this.setSourceData(this.linesSourceId,{type:"FeatureCollection",features:t}),this.setSourceData(this.fillsSourceId,{type:"FeatureCollection",features:i}),this.setSourceData(this.pointsSourceId,{type:"FeatureCollection",features:a}),this.setSourceData(this.labelsSourceId,{type:"FeatureCollection",features:n}),this.updateBadge()}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>=R(this.draft.mode),t=this.draft.mode==="area"?ae(this.draft.area,this.labels):D(this.draft.distance,this.labels);this.badge.setValue(e?t:D(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{P as MahalMap,w as MahalMapDefaultMarker,C as MeasureTool,W as Router,Q as Search,ee as SearchByLocation,te as keyUtils,se as measureUtils,q as utils};
113
+ `}};l.instances=new Map,l.defaultLanguage="tj";var F=l;var oe={};x(oe,{Router:()=>te,Search:()=>se,SearchByLocation:()=>ae,clearKey:()=>ce,getApiKey:()=>E,saveKey:()=>de});import Le from"axios";var f=Le.create({baseURL:K});var X=async(i,e)=>{try{let t=[];return i.forEach(s=>{t.push({lng:s[0],lat:s[1]})}),(await f.post("services/getRoutes",{points:t,token:e})).data}catch(t){throw console.error(t),t}};var ee={};x(ee,{checkCoordinates:()=>Ce,debounce:()=>T,geojsonPolyline:()=>D,geometryPolyline:()=>Q,trimValue:()=>Ie});function Ce(i){let e,t;if(I.test(i)){let r=i.match(I);r&&([,e,t]=r)}else if(w.test(i)){let r=i.match(w);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 T(i,e){let t;return(...r)=>(t&&clearTimeout(t),new Promise(s=>{t=setTimeout(async()=>{let a=await i(...r);s(a)},e)}))}function D(i){let e=[],t=0,r=i.length,s=0,a=0;for(;t<r;){let n,p=0,o=0;do n=i.charCodeAt(t++)-63,o|=(n&31)<<p,p+=5;while(n>=32);let h=o&1?~(o>>1):o>>1;s+=h,p=0,o=0;do n=i.charCodeAt(t++)-63,o|=(n&31)<<p,p+=5;while(n>=32);let u=o&1?~(o>>1):o>>1;a+=u,e.push([a*1e-5,s*1e-5])}return e}function Se(i){let e="",t=0,r=0;for(let s=0;s<i.length;s++){let[a,n]=i[s],p=Math.round(n*1e5),o=Math.round(a*1e5),h=p-t,u=o-r;t=p,r=o,e+=Y(h)+Y(u)}return e}function Y(i){let e=i<<1;return i<0&&(e=~e),xe(e)}function xe(i){let e="";for(;i>=32;)e+=String.fromCharCode((32|i&31)+63),i>>=5;return e+=String.fromCharCode(i+63),e}var Q=Se;function Ie(i,e){if(e<=0)return"";let t=i.trim();return e>=t.length?t:t.slice(0,e)}async function te(i,e,t){if(!t)throw new Error("[MahalMap SDK] Router token is required");try{let r=await X(i,t);return r?.data?r.data.map(a=>{let n={...a};return n.route?.routes?.length&&(n.route.routes=n.route.routes.map(p=>({...p,geometry:e==="geojson"&&typeof p.geometry=="string"?D(p.geometry):p.geometry}))),n}):r}catch(r){throw r}}var re=async i=>{try{return(await f.post("services/getAddress",null,{params:i})).data}catch(e){throw console.error("Error while searching address:",e),e}},ie=async i=>{try{return(await f.post("services/getAddressByLocation",null,{params:i})).data}catch(e){throw console.error("Error while searching address by location:",e),e}};async function we(i,e,t){let r={text:i,token:e,...t};try{return(await re(r)).data}catch(s){throw s}}var Pe=T(we,500);async function se(i,e,t){if(!e)throw new Error("[MahalMap SDK] Search token is required");return await Pe(i,e,t)}async function ae(i){if(!i.token)throw new Error("[MahalMap SDK] SearchByLocation token is required");let e={...i};try{return await ie(e)}catch(t){throw t}}var he={};x(he,{MeasureTool:()=>S,haversineDistance:()=>ne,lineLength:()=>M,midpoint:()=>G,polygonArea:()=>R,polygonCentroid:()=>H});var A=63710088e-1;function d(i){return i*Math.PI/180}function ne(i,e){let[t,r]=i,[s,a]=e,n=d(r),p=d(a),o=d(a-r),h=d(s-t),u=Math.sin(o/2),g=Math.sin(h/2),c=u*u+Math.cos(n)*Math.cos(p)*g*g,y=2*Math.atan2(Math.sqrt(c),Math.sqrt(1-c));return A*y}function M(i){let e=0;for(let t=1;t<i.length;t+=1)e+=ne(i[t-1],i[t]);return e}function R(i){if(i.length<3)return 0;let e=0;for(let t=0;t<i.length;t+=1){let r=i[t],s=i[(t+1)%i.length],a=d(r[0]),n=d(r[1]),p=d(s[0]),o=d(s[1]);e+=(p-a)*(2+Math.sin(n)+Math.sin(o))}return Math.abs(e*A*A/2)}function H(i){let e=i.reduce((t,r)=>[t[0]+r[0],t[1]+r[1]],[0,0]);return[e[0]/i.length,e[1]/i.length]}function G(i){return i.length===0?[0,0]:i[Math.floor((i.length-1)/2)]}var pe='<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>',Ee='<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>',b=class{constructor(e,t,r,s){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=r.trash??pe,this.closeButton.innerHTML=r.close??ke,this.checkButton.innerHTML=r.check??Ee;let a=n=>{n.preventDefault(),n.stopPropagation()};this.wrapper.addEventListener("mousedown",a),this.wrapper.addEventListener("dblclick",a),this.wrapper.addEventListener("contextmenu",a),this.trashButton.addEventListener("click",n=>{a(n),s.onRemove()}),this.closeButton.addEventListener("click",n=>{a(n),s.onClose()}),this.checkButton.addEventListener("click",n=>{a(n),s.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,s=t.iconButtonSize??"24px";r.display="inline-flex",r.alignItems="center",r.justifyContent="center",r.width=s,r.height=s,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()}},L=class{constructor(e,t,r,s){this.wrapper=document.createElement("div"),this.valueEl=document.createElement("span"),this.trashButton=document.createElement("button");let a=this.wrapper.style;a.position="absolute",a.zIndex="4",a.display="flex",a.alignItems="center",a.gap=t.badgeGap??"6px",a.padding="5px 7px",a.background=t.badgeBackground??"#FFFFFF",a.borderRadius=t.badgeBorderRadius??"12px",a.boxShadow=t.badgeBoxShadow??"0 2px 10px rgba(15, 23, 42, 0.18)",a.border=t.badgeBorder??"1px solid rgba(0,0,0,0.06)",a.transform="translate(-50%, -50%)",a.pointerEvents="auto",a.userSelect="none",a.whiteSpace="nowrap";let n=this.valueEl.style;n.color=t.badgeTextColor??"#19191A",n.fontSize=t.badgeFontSize??"13px",n.fontWeight=t.badgeFontWeight??"600",n.lineHeight="16px";let p=t.iconButtonSize??"20px",o=this.trashButton.style;o.display="inline-flex",o.alignItems="center",o.justifyContent="center",o.width=p,o.height=p,o.border="none",o.background="transparent",o.cursor="pointer",o.color=t.badgeTextColor??"#535969",o.padding="0",this.trashButton.type="button",this.trashButton.innerHTML=r.trash??pe;let h=u=>{u.preventDefault(),u.stopPropagation()};this.wrapper.addEventListener("mousedown",h),this.wrapper.addEventListener("dblclick",h),this.wrapper.addEventListener("contextmenu",h),this.trashButton.addEventListener("click",u=>{h(u),s()}),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 Be=0,O=i=>`${i}-${Date.now().toString(36)}-${Be+=1}`,Fe={pointColor:"#FFFFFF",pointStrokeColor:"#278960",pointStrokeWidth:2,pointRadius:5,lineColor:"#278960",lineWidth:3,fillColor:"#278960",fillOpacity:.15,labelColor:"#19191A",labelHaloColor:"#FFFFFF"};function $(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 V(i){return i==="area"?3:2}function C(){return{type:"FeatureCollection",features:[]}}var S=class{constructor(e,t={}){this.isActive=!1;this.draft=null;this.shapes=[];this.badge=null;this.shapeBadges=new Map;this.draggingPointId=null;this.draggingShapeId=null;this.suppressNextClick=!1;this.hoverInsert=null;this.handleClick=e=>this.onMapClick(e);this.handlePointMouseDown=e=>this.onPointMouseDown(e);this.handlePointMouseEnter=()=>this.setCursor("pointer");this.handlePointMouseLeave=()=>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(s=>s.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.stopDragListeners(),this.map.dragPan.enable(),this.setCursor("pointer"),this.suppressNextClick=!0};this.map=e,this.prefix=t.sourceIdPrefix??"mahal-measure",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.ensureLayers(),this.badge=new b(e.getContainer(),this.style,this.icons,{onRemove:()=>this.removeShape((this.draft??this.getLastShape())?.id??""),onClose:()=>this.onCloseRequest?.(),onCheck:()=>this.finishDraft()}),this.map.on("click",this.handleClick),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),this.map.on("style.load",this.handleStyleLoad),this.map.on("move",this.handleViewportChange)}start(e=this.mode){this.isActive=!0,this.setMode(e),this.render(),this.emitChange()}stop(){this.isActive=!1,this.badge?.hide(),this.clearHoverInsert(),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.render(),this.emitChange())}removePoint(e,t){let r=this.findShape(e);if(r){if(r.points=r.points.filter(s=>s.id!==t),r.points.length===0){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.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),this.map.off("style.load",this.handleStyleLoad),this.map.off("move",this.handleViewportChange),this.stopDragListeners(),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>=V(this.draft.mode)&&this.shapes.push(this.draft),this.draft=null)}ensureDraft(){return this.draft||(this.draft={id:O("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=R(t),e.distance=M([...t,t[0]]);return}e.closed=!1,e.area=0,e.distance=M(t)}onMapClick(e){if(!this.isActive)return;if(this.suppressNextClick){this.suppressNextClick=!1;return}if(this.map.queryRenderedFeatures(e.point,{layers:[this.pointsLayerId]}).length>0)return;let r=this.ensureDraft();r.points.push({id:O("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,s=t?.properties?.pointId;!r||!s||(e.preventDefault(),this.draggingShapeId=r,this.draggingPointId=s,this.map.dragPan.disable(),this.setCursor("grabbing"),this.map.on("mousemove",this.onPointDragMove),this.map.on("mouseup",this.onPointDragUp))}stopDragListeners(){this.map.off("mousemove",this.onPointDragMove),this.map.off("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 s=r.x-t.x,a=r.y-t.y,n=s*s+a*a;if(n===0)return t;let p=Math.max(0,Math.min(1,((e.x-t.x)*s+(e.y-t.y)*a)/n));return{x:t.x+s*p,y:t.y+a*p}}findClosestPointOnShape(e,t){let r=e.points.map(h=>this.projectPoint(h.lngLat)),s=e.closed?r.length:r.length-1,a=-1,n=null,p=1/0;for(let h=0;h<s;h+=1){let u=r[h],g=r[(h+1)%r.length];if(!u||!g)continue;let c=this.closestPointOnSegment(t,u,g),y=c.x-t.x,j=c.y-t.y,U=Math.sqrt(y*y+j*j);U<p&&(p=U,a=h,n=c)}if(a===-1||!n)return null;let o=this.map.unproject([n.x,n.y]);return{index:a,lngLat:[+o.lng.toFixed(6),+o.lat.toFixed(6)]}}isOverExistingPoint(e){return this.map.queryRenderedFeatures(e,{layers:[this.pointsLayerId]}).length>0}onLineMouseMove(e){if(!this.isActive||this.draggingPointId||this.isOverExistingPoint(e.point)){this.clearHoverInsert();return}let r=e.features?.[0]?.properties?.shapeId,s=r?this.findShape(r):null;if(!r||!s)return;let a=this.findClosestPointOnShape(s,e.point);a&&(this.hoverInsert={shapeId:r,index:a.index,lngLat:a.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 s=this.findShape(r);if(!s)return;e.preventDefault();let a={id:O("measure-point"),lngLat:this.hoverInsert.lngLat};s.points.splice(this.hoverInsert.index+1,0,a),this.recomputeShape(s),this.hoverInsert=null,this.renderHoverPoint(),this.render(),this.emitChange(),this.draggingShapeId=r,this.draggingPointId=a.id,this.map.dragPan.disable(),this.setCursor("grabbing"),this.map.on("mousemove",this.onPointDragMove),this.map.on("mouseup",this.onPointDragUp)}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,s=t?.properties?.pointId;!r||!s||(e.preventDefault(),this.removePoint(r,s))}setCursor(e){this.map.getCanvas().style.cursor=e}onStyleLoad(){this.ensureLayers(),this.render()}emitChange(){this.onChange?.(this.getState())}ensureLayers(){let e={...Fe,...this.style};this.map.getSource(this.linesSourceId)||this.map.addSource(this.linesSourceId,{type:"geojson",data:C()}),this.map.getSource(this.fillsSourceId)||this.map.addSource(this.fillsSourceId,{type:"geojson",data:C()}),this.map.getSource(this.pointsSourceId)||this.map.addSource(this.pointsSourceId,{type:"geojson",data:C()}),this.map.getSource(this.hoverPointSourceId)||this.map.addSource(this.hoverPointSourceId,{type:"geojson",data:C()}),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"?H(t):G(t)}render(){let e=this.shapes,t=e.map(a=>this.buildLineFeature(a)).filter(a=>!!a),r=e.map(a=>this.buildFillFeature(a)).filter(a=>!!a),s=e.flatMap(a=>this.buildPointFeatures(a));if(this.draft){let a=this.buildLineFeature(this.draft),n=this.buildFillFeature(this.draft);a&&t.push(a),n&&r.push(n),s.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:s}),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<V(t.mode)){this.shapeBadges.get(t.id)?.destroy(),this.shapeBadges.delete(t.id);return}let r=t.mode==="area"?le(t.area,this.labels):$(t.distance,this.labels),s=this.shapeBadges.get(t.id);s||(s=new L(this.map.getContainer(),this.style,this.icons,()=>this.removeShape(t.id)),this.shapeBadges.set(t.id,s)),s.setValue(r);let a=this.map.project(this.getShapeAnchor(t));s.setPosition(a.x,a.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>=V(this.draft.mode),t=this.draft.mode==="area"?le(this.draft.area,this.labels):$(this.draft.distance,this.labels);this.badge.setValue(e?t:$(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{F as MahalMap,B as MahalMapDefaultMarker,S as MeasureTool,te as Router,se as Search,ae as SearchByLocation,oe as keyUtils,he as measureUtils,ee as utils};
114
114
  //# sourceMappingURL=index.mjs.map