mahal_map 1.7.3 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1535 -1200
- package/dist/index.d.mts +359 -35
- package/dist/index.d.ts +359 -35
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +12 -7
- package/dist/index.mjs.map +1 -1
- package/dist/mahal_map.sdk.js +1 -1
- package/package.json +73 -73
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var Se=Object.defineProperty;var B=(a,e)=>{for(var t in e)Se(a,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 Z="https://geocode.mahal.tj/api/",A=/^([-+]?(?:[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 _="https://mtile.gram.tj/custom-styles/style_maptiler_basic_hn.json",R="https://navi.gram.tj";function F(a,e){return a==="default"?e:`${a}-${e}`}function Ce(a,e,t){let r=new URL(a);return r.searchParams.set(e,t),r.toString()}function Y(a,e){return e?Ce(a,"token",e):a}var H="";function Ie(a){a!==""&&(H=a)}function we(){H=""}var v=()=>H;import xe from"axios";var y=xe.create({baseURL:Z});var X=async a=>{try{return(await y.post("services/geocoder",null,{params:a})).data}catch(e){throw console.error("Error while searching address:",e),e}},Q=async a=>{try{return(await y.post("services/geoorg",null,{params:a})).data}catch(e){throw console.error("Error while searching poi:",e),e}},ee=async a=>{try{return(await y.post("services/gercoderByLocation",null,{params:a})).data}catch(e){throw console.error("Error while searching address by location:",e),e}},te=async a=>{try{return(await y.post("services/checkJSApi",null,{params:a})).data}catch(e){let t=e?.response?.data;if(t&&typeof t.success=="boolean")return t;throw console.error("Error while checking JSApi subscription:",e),e}};var se={};B(se,{checkCoordinates:()=>Pe,debounce:()=>S,geojsonPolyline:()=>O,geometryPolyline:()=>ae,trimValue:()=>Ee});function Pe(a){let e,t;if(A.test(a)){let r=a.match(A);r&&([,e,t]=r)}else if(T.test(a)){let r=a.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 S(a,e){let t;return(...r)=>(t&&clearTimeout(t),new Promise(s=>{t=setTimeout(async()=>{let i=await a(...r);s(i)},e)}))}function O(a){let e=[],t=0,r=a.length,s=0,i=0;for(;t<r;){let n,p=0,o=0;do n=a.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=a.charCodeAt(t++)-63,o|=(n&31)<<p,p+=5;while(n>=32);let u=o&1?~(o>>1):o>>1;i+=u,e.push([i*1e-5,s*1e-5])}return e}function ke(a){let e="",t=0,r=0;for(let s=0;s<a.length;s++){let[i,n]=a[s],p=Math.round(n*1e5),o=Math.round(i*1e5),h=p-t,u=o-r;t=p,r=o,e+=re(h)+re(u)}return e}function re(a){let e=a<<1;return a<0&&(e=~e),De(e)}function De(a){let e="";for(;a>=32;)e+=String.fromCharCode((32|a&31)+63),a>>=5;return e+=String.fromCharCode(a+63),e}var ae=ke;function Ee(a,e){if(e<=0)return"";let t=a.trim();return e>=t.length?t:t.slice(0,e)}async function Be(a,e,t){let r={text:a,token:e,...t};try{return(await X(r)).data}catch(s){throw s}}async function Ae(a,e,t){let r={text:a,token:e,...t};try{return(await Q(r)).data}catch(s){throw s}}var Te=S(Be,500),Re=S(Ae,500);async function ie(a,e,t){if(!e)throw new Error("[MahalMap SDK] Search token is required");return await Te(a,e,t)}async function ne(a,e,t){if(!e)throw new Error("[MahalMap SDK] SearchPoi token is required");return await Re(a,e,t)}async function oe(a){if(!a.token)throw new Error("[MahalMap SDK] SearchByLocation token is required");let e={...a};try{return await ee(e)}catch(t){throw t}}async function C(a){if(!a)throw new Error("[MahalMap SDK] CheckJSApi token is required");return await te({token:a})}var Fe=/<svg[\s>]/i,He=/<(svg|path|g|circle|rect|polygon|line|polyline|ellipse|use)\b/i,I=(a,e,t)=>{let r=new RegExp(`\\s${e}="[^"]*"`,"i");return r.test(a)?a.replace(r,` ${e}="${t}"`):a.replace(/<svg\b/i,`<svg ${e}="${t}"`)},Oe=a=>a.replace(/&/g,"&").replace(/"/g,"""),le=a=>`<image href="${Oe(a)}" x="14" y="12" width="22" height="22" style="filter: brightness(0) invert(1);" />`,Ge=a=>{let e=a.trim();if(Fe.test(e)){let t=I(e,"x","14");return t=I(t,"y","12"),t=I(t,"width","22"),t=I(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>`},$e=({innerSvg:a,innerUrl:e})=>{let t=a?.trim(),r=e?.trim();return t?He.test(t)?Ge(t):le(t):r?le(r):""},pe=(a,e={})=>`<svg
|
|
2
2
|
width="50"
|
|
3
3
|
height="62"
|
|
4
4
|
viewBox="0 0 50 62"
|
|
@@ -10,17 +10,17 @@ var xe=Object.defineProperty;var A=(i,e)=>{for(var t in e)xe(i,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="${
|
|
13
|
+
fill="${a||"#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="${
|
|
18
|
+
fill="${a||"#278960"}"
|
|
19
19
|
stroke="white"
|
|
20
20
|
stroke-width="2"
|
|
21
21
|
/>
|
|
22
22
|
<g clip-path="url(#clip0_367_31358)">
|
|
23
|
-
${
|
|
23
|
+
${$e(e)}
|
|
24
24
|
</g>
|
|
25
25
|
<defs>
|
|
26
26
|
<filter
|
|
@@ -67,7 +67,12 @@ var xe=Object.defineProperty;var A=(i,e)=>{for(var t in e)xe(i,t,{get:e[t],enume
|
|
|
67
67
|
/>
|
|
68
68
|
</clipPath>
|
|
69
69
|
</defs>
|
|
70
|
-
</svg>`;var
|
|
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):pe(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 he(a,e,t){return new a.Marker({element:t.getElement(),draggable:t.isDraggable?.()??!1,anchor:t.getAnchor?.()??"center"}).setLngLat(t.getCoordinates()).addTo(e)}var Je={dark:"#ffffff",light:"#19191a"},ue="buildings",l=class l{constructor(){this.isReady=!1;this.readyCallbacks=[];this.language="tj";this.instanceKey="";this.gramBase=R;this.styleFamily="default";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){l.defaultLanguage=l.normalizeLanguage(e)}static getFallbackStyle(){return Y(_,l.getMapToken())}static getMapToken(){let e=v();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 async ensureJSApiSubscription(e){if(e)return;let t=v();if(!t)return;let r;try{r=await C(t)}catch(s){console.warn("[MahalMap SDK] JSApi subscription check failed, continuing without it:",s);return}if(!r.success)throw new Error(`[MahalMap SDK] JSApi subscription is not active for this key: ${r.message}`)}static async createAsync(e,t,r){return await l.ensureJSApiSubscription(l.getMaps3DCtor(r)),l.create(e,t,r)}static resolveStyleName(e,t,r){return e.style||e.preset||F(t,r)}static buildPlatformMapOptions(e,t,r,s,i){try{return e.mapOptions?e.mapOptions({base:t,apiKey:r,style:s,antialias:i}):{style:e.styleUrl?e.styleUrl(s,t):l.requireAbsoluteStyle(s),transformRequest:e.transformRequest({base:t,apiKey:r}),...i?{canvasContextAttributes:{antialias:!0}}:{}}}catch(n){throw new Error(`[MahalMap SDK] Maps3D rejected the style "${s}": ${n instanceof Error?n.message:String(n)}`)}}static requireAbsoluteStyle(e){if(/^https?:/i.test(e))return e;throw new Error("this Maps3D build has no styleUrl() \u2014 pass options.style as a full URL or upgrade @grammaps/maps3d-web to >=0.5.0")}static create(e,t,r){let s=typeof window<"u"?window.maplibregl:void 0,i=t||s;if(!i)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),p=e.theme==="dark"?"dark":"light",o=new l,h=l.getInstanceKey(e);o.options=e,o.language=n,o.instanceKey=h,o.maplibre=i;let u=l.getMapToken(),d=l.getMaps3DCtor(r);o.gramBase=(e.base||R).replace(/\/+$/,""),o.styleFamily=e.family||"default",o.presetIsExplicit=!!(e.style||e.preset),o.maps3dCtor=d;let c=e.enable3D!==!1&&!!d;o.buildingsEnabled=c,e.enable3D!==!1&&!d&&console.warn("[MahalMap SDK] Maps3D was not found \u2014 falling back to the plain vector style without 3D. Pass Maps3D as the third argument to create() or include it through a script (window.Maps3D).");let g=e.antialias!==void 0?e.antialias:c,m=d?l.buildPlatformMapOptions(d,o.gramBase,u,l.resolveStyleName(e,o.styleFamily,p),g):void 0,b=c?58:0;return o.map=new i.Map({container:e.container||"map",style:m?m.style:l.getFallbackStyle(),center:e.center||[69.624024,40.279687],zoom:e.zoom!==void 0?e.zoom:5,attributionControl:!1,pitch:e.pitch!==void 0?e.pitch:b,...e.bearing!==void 0?{bearing:e.bearing}:{},...m?{transformRequest:m.transformRequest,...m.canvasContextAttributes?{canvasContextAttributes:m.canvasContextAttributes}:{}}:{}}),c&&(o.maps3dLayer=o.createMaps3DLayer(u),o.attachMaps3DLayer(o.maps3dLayer)),o.watchWorkerHealth(),o.addLogo(p),o.map.on("load",()=>{o.isReady=!0,o.camera=new M(o.map),o.readyCallbacks.forEach(be=>be(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 getMaps3DLayer(e){return e.getMaps3DLayer()}static whenMaps3DReady(e){return e.whenMaps3DReady()}static toggle3DBuildings(e,t){e.toggle3DBuildings(t)}static setLayer(e,t,r,s){return e.setLayer(t,r,s)}static getLayerState(e,t){return e.getLayerState(t)}static getLayers(e){return e.getLayers()}static onLayers(e,t){return e.onLayers(t)}static refreshLayers(e){e.refreshLayers()}static getIndoorLevels(e){return e.getIndoorLevels()}static setIndoorLevel(e,t){e.setIndoorLevel(t)}static refreshIndoor(e){e.refreshIndoor()}static showPlace(e,t,r,s,i){e.showPlace(t,r,s,i)}static onBuildingClick(e,t){e.onBuildingClick(t)}static selectBuilding(e,t,r){return e.selectBuilding(t,r)}static clearSelection(e){e.clearSelection()}static selectedBuilding(e){return e.selectedBuilding()}static setSelectionStyle(e,t){e.setSelectionStyle(t)}static onRoadClick(e,t){e.onRoadClick(t)}static roadAt(e,t,r){return e.roadAt(t,r)}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 he(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.theme=e,!(this.presetIsExplicit||!this.maps3dCtor?.styleUrl)&&(this.map.setStyle(this.maps3dCtor.styleUrl(F(this.styleFamily,e),this.gramBase)),this.refreshLayersOnStyleLoad(),this.updateLogoColor(e))}refreshLayersOnStyleLoad(){let e=this.map.once;typeof e=="function"&&e.call(this.map,"style.load",()=>{this.maps3dLayer?.refreshLayers?.()})}setLanguage(e){this.language=l.normalizeLanguage(e),this.options.lang=this.language}getMaps3DLayer(){return this.maps3dLayer}toggle3DBuildings(e){if(!(!this.maps3dLayer&&e&&(this.maps3dCtor=this.maps3dCtor||l.getMaps3DCtor(),!this.maps3dCtor))){if(this.buildingsEnabled=e,!this.maps3dLayer){if(!e)return;this.maps3dLayer=this.createMaps3DLayer(v()||void 0),this.attachMaps3DLayer(this.maps3dLayer);return}this.applyMaps3DBuildingMode(e)}}whenMaps3DReady(){return this.maps3dReady||Promise.resolve(void 0)}setLayer(e,t,r){return e===ue&&(this.buildingsEnabled=t),this.maps3dLayer?.setLayer?.(e,t,r)??!1}getLayerState(e){return this.maps3dLayer?.layer?.(e)??null}getLayers(){return this.maps3dLayer?.layers?.()??[]}onLayers(e){return this.maps3dLayer?.onLayers?.(e)??(()=>{})}refreshLayers(){this.maps3dLayer?.refreshLayers?.()}getIndoorLevels(){return this.maps3dLayer?.indoorLevels??[]}setIndoorLevel(e){this.maps3dLayer?.setIndoorLevel?.(e)}refreshIndoor(){this.maps3dLayer?.refreshIndoor?.()}showPlace(e,t,r,s){this.maps3dLayer?.showPlace?.(e,t,r,s)}onBuildingClick(e){this.maps3dLayer?.onBuildingClick?.(e)}selectBuilding(e,t){return this.maps3dLayer?.selectBuilding?.(e,t)??!1}clearSelection(){this.maps3dLayer?.clearSelection?.()}selectedBuilding(){return this.maps3dLayer?.selectedBuilding?.()??null}setSelectionStyle(e){this.maps3dLayer?.setSelectionStyle?.(e)}onRoadClick(e){this.maps3dLayer?.onRoadClick?.(e)}roadAt(e,t){return this.maps3dLayer?.roadAt?.(e,t)??null}get roadsNamed(){return this.maps3dLayer?.roadsNamed??!1}createMaps3DLayer(e){let t={...this.options.maps3d,apiKey:e,base:this.gramBase};return this.maps3dCtor.enhance?this.maps3dCtor.enhance(this.map,t):new this.maps3dCtor(t)}attachMaps3DLayer(e){let t;try{t=e.ready??e.attach(this.map)}catch(r){t=Promise.reject(r)}this.maps3dReady=Promise.resolve(t).then(()=>{if(this.maps3dLayer!==e){l.teardownMaps3DLayer(e);return}return this.applyMaps3DBuildingMode(this.buildingsEnabled),e}).catch(r=>{l.teardownMaps3DLayer(e),this.maps3dLayer===e&&(this.maps3dLayer=void 0,this.buildingsEnabled=!1,console.error("[MahalMap SDK] Failed to attach Maps3D layer",r))})}static teardownMaps3DLayer(e){l.disposedMaps3DLayers.has(e)||(l.disposedMaps3DLayers.add(e),e.destroy?e.destroy():e.remove?.())}watchWorkerHealth(){let e=this.options.workerCheck;if(e===!1||typeof setTimeout!="function")return;let t=typeof e=="number"?e:l.WORKER_CHECK_DELAY;this.workerCheckTimer=setTimeout(()=>{this.workerCheckTimer=void 0,this.reportBrokenWorker()},t)}reportBrokenWorker(){if(typeof document<"u"&&document.hidden)return;let e=this.map;if(!(!e||typeof e.getStyle!="function"||typeof e.isStyleLoaded!="function"||typeof e.queryRenderedFeatures!="function")){try{let t=e.getStyle()?.sources??{};if(!Object.values(t).some(s=>s?.type==="vector"||s?.type==="geojson")||e.isStyleLoaded()||e.queryRenderedFeatures().length>0)return}catch{return}console.warn(`[MahalMap SDK] \u041A\u0430\u0440\u0442\u0430 \u043F\u0443\u0441\u0442\u0430: \u043D\u0438 \u043E\u0434\u0438\u043D \u0432\u0435\u043A\u0442\u043E\u0440\u043D\u044B\u0439 \u0442\u0430\u0439\u043B \u043D\u0435 \u0440\u0430\u0437\u043E\u0431\u0440\u0430\u043D \u2014 \u043F\u043E\u0445\u043E\u0436\u0435, \u043D\u0435 \u0437\u0430\u043F\u0443\u0441\u0442\u0438\u043B\u0441\u044F \u0432\u0435\u0431-\u0432\u043E\u0440\u043A\u0435\u0440 MapLibre.
|
|
71
|
+
\u041E\u0431\u044B\u0447\u043D\u043E \u0432\u0438\u043D\u043E\u0432\u0430\u0442 \u0441\u0431\u043E\u0440\u0449\u0438\u043A: \u043E\u043D \u043D\u0435 \u043F\u0435\u0440\u0435\u043D\u043E\u0441\u0438\u0442 \u0444\u0430\u0439\u043B \u0432\u043E\u0440\u043A\u0435\u0440\u0430, \u0438 \u0432\u043C\u0435\u0441\u0442\u043E \u0441\u043A\u0440\u0438\u043F\u0442\u0430 \u0441\u0435\u0440\u0432\u0435\u0440 \u043E\u0442\u0434\u0430\u0451\u0442 HTML.
|
|
72
|
+
\u0420\u0435\u0448\u0435\u043D\u0438\u044F:
|
|
73
|
+
1) \u0432\u0437\u044F\u0442\u044C \u0431\u0438\u0431\u043B\u0438\u043E\u0442\u0435\u043A\u0443 \u0443 \u043F\u043B\u0430\u0442\u0444\u043E\u0440\u043C\u044B: const maplibregl = await Maps3D.maplibre({ base });
|
|
74
|
+
2) \u043E\u0441\u0442\u0430\u0432\u0438\u0442\u044C \u0441\u0432\u043E\u044E \u0441\u0431\u043E\u0440\u043A\u0443, \u043D\u043E \u0438\u0441\u043A\u043B\u044E\u0447\u0438\u0442\u044C maplibre-gl \u0438\u0437 \u043E\u043F\u0442\u0438\u043C\u0438\u0437\u0430\u0446\u0438\u0438 (vite: optimizeDeps.exclude: ["maplibre-gl"]) \u0438 \u0443\u043A\u0430\u0437\u0430\u0442\u044C \u0430\u0434\u0440\u0435\u0441 \u0432\u043E\u0440\u043A\u0435\u0440\u0430: maplibregl.setWorkerUrl('/maplibre-gl-worker.mjs').
|
|
75
|
+
\u041F\u0440\u043E\u0432\u0435\u0440\u043A\u0430 \u043E\u0442\u043A\u043B\u044E\u0447\u0430\u0435\u0442\u0441\u044F \u043E\u043F\u0446\u0438\u0435\u0439 workerCheck: false.`)}}applyMaps3DBuildingMode(e){let t=this.maps3dLayer;t&&(t.setLayer?.(ue,e)||(t.setBuildingsEnabled?.(e),t.buildings?.setWindows?.(e)))}setCenter(e){this.map.setCenter(e)}setZoom(e){this.map.setZoom(e)}destroy(){this.workerCheckTimer!==void 0&&(clearTimeout(this.workerCheckTimer),this.workerCheckTimer=void 0),this.maps3dLayer&&l.teardownMaps3DLayer(this.maps3dLayer),this.maps3dLayer=void 0,this.maps3dReady=void 0,this.logoObserver?.disconnect(),this.logoObserver=void 0,this.logoHost?.remove(),this.logoHost=void 0,this.logoShadow=void 0,this.map.remove(),l.instances.delete(this.instanceKey)}addLogo(e){let t=this.map.getContainer(),r=document.createElement("div"),s=r.attachShadow({mode:"closed"});r.setAttribute("role","img"),r.setAttribute("aria-label","Mahal"),r.dataset.mahal=Math.random().toString(36).slice(2),this.logoHost=r,this.logoShadow=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
76
|
<style>
|
|
72
77
|
:host {
|
|
73
78
|
all: initial;
|
|
@@ -87,7 +92,7 @@ var xe=Object.defineProperty;var A=(i,e)=>{for(var t in e)xe(i,t,{get:e[t],enume
|
|
|
87
92
|
}
|
|
88
93
|
</style>
|
|
89
94
|
<span class="logo-wrap" aria-hidden="true">
|
|
90
|
-
${this.getLogoSvg(
|
|
95
|
+
${this.getLogoSvg(Je[e])}
|
|
91
96
|
</span>
|
|
92
97
|
`)}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
98
|
<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 +115,5 @@ var xe=Object.defineProperty;var A=(i,e)=>{for(var t in e)xe(i,t,{get:e[t],enume
|
|
|
110
115
|
</clipPath>
|
|
111
116
|
</defs>
|
|
112
117
|
</svg>
|
|
113
|
-
`}};p.instances=new Map,p.defaultLanguage="tj",p.disposedMaps3DLayers=new WeakSet;var j=p;var ve={};A(ve,{CheckJSApi:()=>w,Router:()=>Me,Search:()=>ue,SearchByLocation:()=>ce,SearchPoi:()=>de,clearKey:()=>He,getApiKey:()=>L,saveKey:()=>Fe});var ye=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}};async function Me(i,e,t){if(!t)throw new Error("[MahalMap SDK] Router token is required");try{let r=await ye(i,t);return r?.data?r.data.map(a=>{let n={...a};return n.route?.routes?.length&&(n.route.routes=n.route.routes.map(h=>({...h,geometry:e==="geojson"&&typeof h.geometry=="string"?V(h.geometry):h.geometry}))),n}):r}catch(r){throw r}}var Pe={};A(Pe,{MeasureTool:()=>B,haversineDistance:()=>W,lineLength:()=>I,midpoint:()=>Z,polygonArea:()=>N,polygonCentroid:()=>q});var U=63710088e-1;function y(i){return i*Math.PI/180}function z(i){return((i+180)%360+360)%360-180}function K(i){return((i+180)%360+360)%360-180}function W(i,e){let[t,r]=i,[s,a]=e,n=y(r),h=y(a),l=y(a-r),o=y(s-t),u=Math.sin(l/2),d=Math.sin(o/2),c=u*u+Math.cos(n)*Math.cos(h)*d*d,g=2*Math.atan2(Math.sqrt(c),Math.sqrt(1-c));return U*g}function I(i){let e=0;for(let t=1;t<i.length;t+=1)e+=W(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],s=i[(t+1)%i.length],a=y(z(s[0]-r[0])),n=y(r[1]),h=y(s[1]);e+=a*(2+Math.sin(n)+Math.sin(h))}return Math.abs(e*U*U/2)}function Le(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 q(i){if(i.length===0)return[0,0];if(i.length<3)return Le(i);let e=i[0]?.[0]??0,t=i.map(([o,u])=>[e+z(o-e),u]),r=0,s=0,a=0;for(let o=0;o<t.length;o+=1){let[u,d]=t[o],[c,g]=t[(o+1)%t.length],m=u*g-c*d;r+=m,s+=(u+c)*m,a+=(d+g)*m}let n=r/2;if(Math.abs(n)<1e-12)return Le(t);let h=s/(6*n),l=a/(6*n);return[K(h),l]}function Z(i){if(i.length===0)return[0,0];if(i.length===1)return i[0];let e=[],t=0;for(let a=1;a<i.length;a+=1){let n=W(i[a-1],i[a]);e.push(n),t+=n}if(t===0)return i[0];let r=t/2,s=0;for(let a=1;a<i.length;a+=1){let n=e[a-1];if(s+n>=r){let h=n===0?0:(r-s)/n,l=i[a-1],o=i[a],u=K(l[0]+z(o[0]-l[0])*h),d=l[1]+(o[1]-l[1])*h;return[u,d]}s+=n}return i[i.length-1]}var Qe=new Set(["svg","g","path","circle","ellipse","rect","line","polyline","polygon"]),et=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"]),tt=new Set(["fill","stroke"]);function rt(i,e){let t=e.trim().toLowerCase();return!(t.includes("javascript:")||t.includes("data:")||t.includes("expression(")||tt.has(i)&&t.includes("url("))}function be(i){return Qe.has(i.tagName.toLowerCase())?(Array.from(i.attributes).forEach(e=>{let t=e.name.toLowerCase();(!et.has(t)||!rt(t,e.value))&&i.removeAttribute(e.name)}),Array.from(i.children).forEach(e=>{be(e)||e.remove()}),!0):!1}function it(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")||!be(t)?null:new XMLSerializer().serializeToString(t)}catch{return null}}function b(i,e){return i?it(i)??e:e}var Se='<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>',st='<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>',at='<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,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=b(r.trash,Se),this.closeButton.innerHTML=b(r.close,st),this.checkButton.innerHTML=b(r.check,at);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)}applyStyle(e){let t=this.wrapper.style.display;this.applyWrapperStyles(e),this.applyValueStyles(e),this.applyButtonStyles(this.trashButton,e),this.applyButtonStyles(this.closeButton,e),this.applyButtonStyles(this.checkButton,e),this.wrapper.style.display=t}applyWrapperStyles(e){let t=this.wrapper.style;t.position="absolute",t.zIndex="5",t.display="flex",t.alignItems="center",t.gap=e.badgeGap??"8px",t.padding="6px 8px",t.background=e.badgeBackground??"#FFFFFF",t.borderRadius=e.badgeBorderRadius??"12px",t.boxShadow=e.badgeBoxShadow??"0 2px 10px rgba(15, 23, 42, 0.18)",t.border=e.badgeBorder??"1px solid rgba(0,0,0,0.06)",t.transform="translate(-50%, -140%)",t.pointerEvents="auto",t.userSelect="none",t.whiteSpace="nowrap"}applyValueStyles(e){let t=this.valueEl.style;t.color=e.badgeTextColor??"#19191A",t.fontSize=e.badgeFontSize??"14px",t.fontWeight=e.badgeFontWeight??"600",t.lineHeight="18px"}applyButtonStyles(e,t){let r=e.style,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()}},k=class{constructor(e,t,r,s){this.wrapper=document.createElement("div"),this.valueEl=document.createElement("span"),this.trashButton=document.createElement("button"),this.applyStyle(t),this.trashButton.type="button",this.trashButton.innerHTML=b(r.trash,Se);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()}),this.wrapper.appendChild(this.valueEl),this.wrapper.appendChild(this.trashButton),e.appendChild(this.wrapper)}applyStyle(e){let t=this.wrapper.style;t.position="absolute",t.zIndex="4",t.display="flex",t.alignItems="center",t.gap=e.badgeGap??"6px",t.padding="5px 7px",t.background=e.badgeBackground??"#FFFFFF",t.borderRadius=e.badgeBorderRadius??"12px",t.boxShadow=e.badgeBoxShadow??"0 2px 10px rgba(15, 23, 42, 0.18)",t.border=e.badgeBorder??"1px solid rgba(0,0,0,0.06)",t.transform="translate(-50%, -50%)",t.pointerEvents="auto",t.userSelect="none",t.whiteSpace="nowrap";let r=this.valueEl.style;r.color=e.badgeTextColor??"#19191A",r.fontSize=e.badgeFontSize??"13px",r.fontWeight=e.badgeFontWeight??"600",r.lineHeight="16px";let s=e.iconButtonSize??"20px",a=this.trashButton.style;a.display="inline-flex",a.alignItems="center",a.justifyContent="center",a.width=s,a.height=s,a.border="none",a.background="transparent",a.cursor="pointer",a.color=e.badgeTextColor??"#535969",a.padding="0"}setValue(e){this.valueEl.textContent=e}setPosition(e,t){this.wrapper.style.left=`${e}px`,this.wrapper.style.top=`${t}px`}destroy(){this.wrapper.remove()}};var nt=0,_=i=>`${i}-${Date.now().toString(36)}-${nt+=1}`,ot=0,lt=()=>`mahal-measure-${ot+=1}`,Ce={pointColor:"#FFFFFF",pointStrokeColor:"#278960",pointStrokeWidth:2,pointRadius:5,lineColor:"#278960",lineWidth:3,fillColor:"#278960",fillOpacity:.15};function X(i,e){return i>=1e3?`${(i/1e3).toFixed(2)} ${e.kilometers??"\u043A\u043C"}`:`${Math.round(i)} ${e.meters??"\u043C"}`}function we(i,e){return i>=1e5?`${(i/1e6).toFixed(2)} ${e.squareKilometers??"\u043A\u043C\xB2"}`:`${Math.round(i)} ${e.squareMeters??"\u043C\xB2"}`}function E(i){return i==="area"?3:2}function D(){return{type:"FeatureCollection",features:[]}}var B=class{constructor(e,t={}){this.layerHandlersBound=!1;this.destroyed=!1;this.ensuringLayers=!1;this.isActive=!1;this.draft=null;this.shapes=[];this.badge=null;this.shapeBadges=new Map;this.draggingPointId=null;this.draggingShapeId=null;this.dragPanWasEnabled=!0;this.suppressNextClick=!1;this.hoverInsert=null;this.handleClick=e=>this.onMapClick(e);this.handlePointMouseDown=e=>this.onPointMouseDown(e);this.handlePointMouseEnter=()=>{this.isActive&&this.setCursor("pointer")};this.handlePointMouseLeave=()=>{this.isActive&&this.setCursor("")};this.handlePointContextMenu=e=>this.onPointContextMenu(e);this.handleLineMouseMove=e=>this.onLineMouseMove(e);this.handleLineMouseLeave=()=>this.clearHoverInsert();this.handleLineMouseDown=e=>this.onLineMouseDown(e);this.handleStyleLoad=()=>this.onStyleLoad();this.handleStyleData=()=>{this.destroyed||this.map.getLayer(this.pointsLayerId)||this.refresh()};this.handleViewportChange=()=>{this.updateBadgePosition(),this.updateShapeBadgePositions()};this.onPointDragMove=e=>{if(!this.draggingShapeId||!this.draggingPointId)return;let t=this.findShape(this.draggingShapeId),r=t?.points.find(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.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??lt(),this.style=t.style??{},this.labels=t.labels??{},this.icons=t.icons??{},this.mode=t.mode??"distance",this.onChange=t.onChange,this.onCloseRequest=t.onCloseRequest,this.pointsSourceId=`${this.prefix}-points`,this.linesSourceId=`${this.prefix}-lines`,this.fillsSourceId=`${this.prefix}-fills`,this.hoverPointSourceId=`${this.prefix}-hover-point`,this.pointsLayerId=`${this.prefix}-points-layer`,this.linesCasingLayerId=`${this.prefix}-lines-casing-layer`,this.linesLayerId=`${this.prefix}-lines-layer`,this.fillsLayerId=`${this.prefix}-fills-layer`,this.hoverPointLayerId=`${this.prefix}-hover-point-layer`,this.badge=new x(e.getContainer(),this.style,this.icons,{onRemove:()=>this.removeShape((this.draft??this.getLastShape())?.id??""),onClose:()=>this.onCloseRequest?.(),onCheck:()=>this.finishDraft()}),this.ensureLayers(),this.map.on("click",this.handleClick),this.map.on("style.load",this.handleStyleLoad),this.map.on("styledata",this.handleStyleData),this.map.on("move",this.handleViewportChange)}bindLayerHandlers(){this.layerHandlersBound||(this.layerHandlersBound=!0,this.map.on("mousedown",this.pointsLayerId,this.handlePointMouseDown),this.map.on("mouseenter",this.pointsLayerId,this.handlePointMouseEnter),this.map.on("mouseleave",this.pointsLayerId,this.handlePointMouseLeave),this.map.on("contextmenu",this.pointsLayerId,this.handlePointContextMenu),this.map.on("mousemove",this.linesCasingLayerId,this.handleLineMouseMove),this.map.on("mouseleave",this.linesCasingLayerId,this.handleLineMouseLeave),this.map.on("mousedown",this.linesCasingLayerId,this.handleLineMouseDown))}unbindLayerHandlers(){this.layerHandlersBound&&(this.layerHandlersBound=!1,this.map.off("mousedown",this.pointsLayerId,this.handlePointMouseDown),this.map.off("mouseenter",this.pointsLayerId,this.handlePointMouseEnter),this.map.off("mouseleave",this.pointsLayerId,this.handlePointMouseLeave),this.map.off("contextmenu",this.pointsLayerId,this.handlePointContextMenu),this.map.off("mousemove",this.linesCasingLayerId,this.handleLineMouseMove),this.map.off("mouseleave",this.linesCasingLayerId,this.handleLineMouseLeave),this.map.off("mousedown",this.linesCasingLayerId,this.handleLineMouseDown))}start(e=this.mode){this.isActive=!0;let t=e!==this.mode;this.setMode(e),t||(this.render(),this.emitChange())}stop(){this.isActive=!1,this.onPointDragUp(),this.badge?.hide(),this.clearHoverInsert(),this.setCursor(this.originalCursor),this.emitChange()}setMode(e){this.mode!==e&&(this.mode=e,this.draft&&(this.draft.mode=e,this.recomputeShape(this.draft)),this.render(),this.emitChange())}finishDraft(){this.commitOrDiscardDraft(),this.render(),this.emitChange()}removeShape(e){e&&(this.draft?.id===e?this.draft=null:this.shapes=this.shapes.filter(t=>t.id!==e),this.hoverInsert?.shapeId===e&&this.clearHoverInsert(),this.render(),this.emitChange())}removePoint(e,t){let r=this.findShape(e);if(!r)return;if(r.points=r.points.filter(a=>a.id!==t),r.points.length===0){this.removeShape(e);return}if(!(this.draft?.id===e)&&r.points.length<E(r.mode)){this.removeShape(e);return}this.recomputeShape(r),this.render(),this.emitChange()}clearAll(){this.draft=null,this.shapes=[],this.clearHoverInsert(),this.render(),this.emitChange()}refresh(){this.destroyed||(this.ensureLayers(),this.render(),this.renderHoverPoint())}setStyleOptions(e){let t=this.style.lineDasharray!==void 0;this.style={...this.style,...e},this.applyPaintStyle(t),this.badge?.applyStyle(this.style),this.shapeBadges.forEach(r=>r.applyStyle(this.style))}getState(){return{active:this.isActive,mode:this.mode,draft:this.draft?this.cloneShape(this.draft):null,shapes:this.shapes.map(e=>this.cloneShape(e))}}destroy(){this.destroyed||(this.destroyed=!0,this.map.off("click",this.handleClick),this.unbindLayerHandlers(),this.map.off("style.load",this.handleStyleLoad),this.map.off("styledata",this.handleStyleData),this.map.off("move",this.handleViewportChange),this.onPointDragUp(),this.setCursor(this.originalCursor),this.badge?.destroy(),this.badge=null,this.shapeBadges.forEach(e=>e.destroy()),this.shapeBadges.clear(),this.removeLayers())}cloneShape(e){return{...e,points:e.points.map(t=>({...t,lngLat:[...t.lngLat]}))}}findShape(e){return this.draft?.id===e?this.draft:this.shapes.find(t=>t.id===e)??null}getLastShape(){return this.shapes[this.shapes.length-1]??null}commitOrDiscardDraft(){this.draft&&(this.draft.points.length>=E(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=I([...t,t[0]]);return}e.closed=!1,e.area=0,e.distance=I(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,s=t?.properties?.pointId;!r||!s||(e.preventDefault(),this.beginPointDrag(r,s))}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 s=r.x-t.x,a=r.y-t.y,n=s*s+a*a;if(n===0)return t;let h=Math.max(0,Math.min(1,((e.x-t.x)*s+(e.y-t.y)*a)/n));return{x:t.x+s*h,y:t.y+a*h}}findClosestPointOnShape(e,t){let r=e.points.map(o=>this.projectPoint(o.lngLat)),s=e.closed?r.length:r.length-1,a=-1,n=null,h=1/0;for(let o=0;o<s;o+=1){let u=r[o],d=r[(o+1)%r.length];if(!u||!d)continue;let c=this.closestPointOnSegment(t,u,d),g=c.x-t.x,m=c.y-t.y,M=Math.sqrt(g*g+m*m);M<h&&(h=M,a=o,n=c)}if(a===-1||!n)return null;let l=this.map.unproject([n.x,n.y]);return{index:a,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,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:_("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.beginPointDrag(r,a.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,s=t?.properties?.pointId;!r||!s||(e.preventDefault(),this.removePoint(r,s))}setCursor(e){this.map.getCanvas().style.cursor=e}onStyleLoad(){this.refresh()}isMapUsable(){return!this.destroyed&&!!this.map.style}emitChange(){this.onChange?.(this.getState())}ensureLayers(){if(!(!this.isMapUsable()||this.ensuringLayers)){this.ensuringLayers=!0;try{this.createMissingLayers()}catch{}finally{this.ensuringLayers=!1}}}createMissingLayers(){let e={...Ce,...this.style};this.map.getSource(this.linesSourceId)||this.map.addSource(this.linesSourceId,{type:"geojson",data:D()}),this.map.getSource(this.fillsSourceId)||this.map.addSource(this.fillsSourceId,{type:"geojson",data:D()}),this.map.getSource(this.pointsSourceId)||this.map.addSource(this.pointsSourceId,{type:"geojson",data:D()}),this.map.getSource(this.hoverPointSourceId)||this.map.addSource(this.hoverPointSourceId,{type:"geojson",data:D()}),this.map.getLayer(this.fillsLayerId)||this.map.addLayer({id:this.fillsLayerId,type:"fill",source:this.fillsSourceId,paint:{"fill-color":e.fillColor,"fill-opacity":e.fillOpacity}}),this.map.getLayer(this.linesCasingLayerId)||this.map.addLayer({id:this.linesCasingLayerId,type:"line",source:this.linesSourceId,layout:{"line-cap":"round","line-join":"round"},paint:{"line-color":"#FFFFFF","line-width":e.lineWidth+3,"line-opacity":.9}}),this.map.getLayer(this.linesLayerId)||this.map.addLayer({id:this.linesLayerId,type:"line",source:this.linesSourceId,layout:{"line-cap":"round","line-join":"round"},paint:{"line-color":e.lineColor,"line-width":e.lineWidth,...this.style.lineDasharray?{"line-dasharray":this.style.lineDasharray}:{}}}),this.map.getLayer(this.hoverPointLayerId)||this.map.addLayer({id:this.hoverPointLayerId,type:"circle",source:this.hoverPointSourceId,paint:{"circle-radius":Math.max(3,e.pointRadius-1),"circle-color":e.pointColor,"circle-stroke-color":e.pointStrokeColor,"circle-stroke-width":e.pointStrokeWidth,"circle-opacity":.8,"circle-stroke-opacity":.8}}),this.map.getLayer(this.pointsLayerId)||this.map.addLayer({id:this.pointsLayerId,type:"circle",source:this.pointsSourceId,paint:{"circle-radius":e.pointRadius,"circle-color":e.pointColor,"circle-stroke-color":e.pointStrokeColor,"circle-stroke-width":e.pointStrokeWidth}}),this.bindLayerHandlers()}applyPaintStyle(e=!1){if(!this.isMapUsable())return;let t={...Ce,...this.style},r=(s,a,n)=>{this.map.getLayer(s)&&this.map.setPaintProperty(s,a,n)};r(this.fillsLayerId,"fill-color",t.fillColor),r(this.fillsLayerId,"fill-opacity",t.fillOpacity),r(this.linesCasingLayerId,"line-width",t.lineWidth+3),r(this.linesLayerId,"line-color",t.lineColor),r(this.linesLayerId,"line-width",t.lineWidth),this.style.lineDasharray!==void 0?r(this.linesLayerId,"line-dasharray",this.style.lineDasharray):e&&r(this.linesLayerId,"line-dasharray",null),r(this.hoverPointLayerId,"circle-radius",Math.max(3,t.pointRadius-1)),r(this.hoverPointLayerId,"circle-color",t.pointColor),r(this.hoverPointLayerId,"circle-stroke-color",t.pointStrokeColor),r(this.hoverPointLayerId,"circle-stroke-width",t.pointStrokeWidth),r(this.pointsLayerId,"circle-radius",t.pointRadius),r(this.pointsLayerId,"circle-color",t.pointColor),r(this.pointsLayerId,"circle-stroke-color",t.pointStrokeColor),r(this.pointsLayerId,"circle-stroke-width",t.pointStrokeWidth)}removeLayers(){[this.pointsLayerId,this.hoverPointLayerId,this.linesLayerId,this.linesCasingLayerId,this.fillsLayerId].forEach(e=>{this.map.getLayer(e)&&this.map.removeLayer(e)}),[this.pointsSourceId,this.hoverPointSourceId,this.linesSourceId,this.fillsSourceId].forEach(e=>{this.map.getSource(e)&&this.map.removeSource(e)})}setSourceData(e,t){this.map.getSource(e)?.setData(t)}buildLineFeature(e){if(e.points.length<2)return null;let t=e.points.map(r=>r.lngLat);return{type:"Feature",id:e.id,properties:{shapeId:e.id},geometry:{type:"LineString",coordinates:e.closed?[...t,t[0]]:t}}}buildFillFeature(e){if(e.mode!=="area"||e.points.length<3)return null;let t=e.points.map(r=>r.lngLat);return{type:"Feature",id:e.id,properties:{shapeId:e.id},geometry:{type:"Polygon",coordinates:[[...t,t[0]]]}}}buildPointFeatures(e){return e.points.map(t=>({type:"Feature",id:t.id,properties:{shapeId:e.id,pointId:t.id},geometry:{type:"Point",coordinates:t.lngLat}}))}getShapeAnchor(e){let t=e.points.map(r=>r.lngLat);return e.mode==="area"?q(t):Z(t)}render(){this.ensureLayers();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<E(t.mode)){this.shapeBadges.get(t.id)?.destroy(),this.shapeBadges.delete(t.id);return}let r=t.mode==="area"?we(t.area,this.labels):X(t.distance,this.labels),s=this.shapeBadges.get(t.id);s||(s=new k(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>=E(this.draft.mode),t=this.draft.mode==="area"?we(this.draft.area,this.labels):X(this.draft.distance,this.labels);this.badge.setValue(e?t:X(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{w as CheckJSApi,j as MahalMap,J as MahalMapDefaultMarker,B as MeasureTool,Me as Router,ue as Search,ce as SearchByLocation,de as SearchPoi,ve as keyUtils,Pe as measureUtils,he as utils};
|
|
118
|
+
`}};l.instances=new Map,l.defaultLanguage="tj",l.disposedMaps3DLayers=new WeakSet,l.WORKER_CHECK_DELAY=8e3;var $=l;var me={};B(me,{CheckJSApi:()=>C,Router:()=>ce,Search:()=>ie,SearchByLocation:()=>oe,SearchPoi:()=>ne,clearKey:()=>we,getApiKey:()=>v,saveKey:()=>Ie});var de=async(a,e)=>{try{let t=[];return a.forEach(s=>{t.push({lng:s[0],lat:s[1]})}),(await y.post("services/getRoutes",{points:t,token:e})).data}catch(t){throw console.error(t),t}};async function ce(a,e,t){if(!t)throw new Error("[MahalMap SDK] Router token is required");try{let r=await de(a,t);return r?.data?r.data.map(i=>{let n={...i};return n.route?.routes?.length&&(n.route.routes=n.route.routes.map(p=>({...p,geometry:e==="geojson"&&typeof p.geometry=="string"?O(p.geometry):p.geometry}))),n}):r}catch(r){throw r}}var Le={};B(Le,{MeasureTool:()=>E,haversineDistance:()=>V,lineLength:()=>w,midpoint:()=>q,polygonArea:()=>K,polygonCentroid:()=>W});var J=63710088e-1;function f(a){return a*Math.PI/180}function j(a){return((a+180)%360+360)%360-180}function U(a){return((a+180)%360+360)%360-180}function V(a,e){let[t,r]=a,[s,i]=e,n=f(r),p=f(i),o=f(i-r),h=f(s-t),u=Math.sin(o/2),d=Math.sin(h/2),c=u*u+Math.cos(n)*Math.cos(p)*d*d,g=2*Math.atan2(Math.sqrt(c),Math.sqrt(1-c));return J*g}function w(a){let e=0;for(let t=1;t<a.length;t+=1)e+=V(a[t-1],a[t]);return e}function K(a){if(a.length<3)return 0;let e=0;for(let t=0;t<a.length;t+=1){let r=a[t],s=a[(t+1)%a.length],i=f(j(s[0]-r[0])),n=f(r[1]),p=f(s[1]);e+=i*(2+Math.sin(n)+Math.sin(p))}return Math.abs(e*J*J/2)}function ge(a){let e=a.reduce((t,r)=>[t[0]+r[0],t[1]+r[1]],[0,0]);return[U(e[0]/a.length),e[1]/a.length]}function W(a){if(a.length===0)return[0,0];if(a.length<3)return ge(a);let e=a[0]?.[0]??0,t=a.map(([h,u])=>[e+j(h-e),u]),r=0,s=0,i=0;for(let h=0;h<t.length;h+=1){let[u,d]=t[h],[c,g]=t[(h+1)%t.length],m=u*g-c*d;r+=m,s+=(u+c)*m,i+=(d+g)*m}let n=r/2;if(Math.abs(n)<1e-12)return ge(t);let p=s/(6*n),o=i/(6*n);return[U(p),o]}function q(a){if(a.length===0)return[0,0];if(a.length===1)return a[0];let e=[],t=0;for(let i=1;i<a.length;i+=1){let n=V(a[i-1],a[i]);e.push(n),t+=n}if(t===0)return a[0];let r=t/2,s=0;for(let i=1;i<a.length;i+=1){let n=e[i-1];if(s+n>=r){let p=n===0?0:(r-s)/n,o=a[i-1],h=a[i],u=U(o[0]+j(h[0]-o[0])*p),d=o[1]+(h[1]-o[1])*p;return[u,d]}s+=n}return a[a.length-1]}var je=new Set(["svg","g","path","circle","ellipse","rect","line","polyline","polygon"]),Ue=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 Ke(a,e){let t=e.trim().toLowerCase();return!(t.includes("javascript:")||t.includes("data:")||t.includes("expression(")||Ve.has(a)&&t.includes("url("))}function ye(a){return je.has(a.tagName.toLowerCase())?(Array.from(a.attributes).forEach(e=>{let t=e.name.toLowerCase();(!Ue.has(t)||!Ke(t,e.value))&&a.removeAttribute(e.name)}),Array.from(a.children).forEach(e=>{ye(e)||e.remove()}),!0):!1}function We(a){if(typeof DOMParser>"u")return null;try{let e=new DOMParser().parseFromString(a,"image/svg+xml"),t=e.documentElement;return!t||t.tagName.toLowerCase()!=="svg"||e.querySelector("parsererror")||!ye(t)?null:new XMLSerializer().serializeToString(t)}catch{return null}}function L(a,e){return a?We(a)??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>',qe='<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>',Ne='<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,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=L(r.trash,fe),this.closeButton.innerHTML=L(r.close,qe),this.checkButton.innerHTML=L(r.check,Ne);let i=n=>{n.preventDefault(),n.stopPropagation()};this.wrapper.addEventListener("mousedown",i),this.wrapper.addEventListener("dblclick",i),this.wrapper.addEventListener("contextmenu",i),this.trashButton.addEventListener("click",n=>{i(n),s.onRemove()}),this.closeButton.addEventListener("click",n=>{i(n),s.onClose()}),this.checkButton.addEventListener("click",n=>{i(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)}applyStyle(e){let t=this.wrapper.style.display;this.applyWrapperStyles(e),this.applyValueStyles(e),this.applyButtonStyles(this.trashButton,e),this.applyButtonStyles(this.closeButton,e),this.applyButtonStyles(this.checkButton,e),this.wrapper.style.display=t}applyWrapperStyles(e){let t=this.wrapper.style;t.position="absolute",t.zIndex="5",t.display="flex",t.alignItems="center",t.gap=e.badgeGap??"8px",t.padding="6px 8px",t.background=e.badgeBackground??"#FFFFFF",t.borderRadius=e.badgeBorderRadius??"12px",t.boxShadow=e.badgeBoxShadow??"0 2px 10px rgba(15, 23, 42, 0.18)",t.border=e.badgeBorder??"1px solid rgba(0,0,0,0.06)",t.transform="translate(-50%, -140%)",t.pointerEvents="auto",t.userSelect="none",t.whiteSpace="nowrap"}applyValueStyles(e){let t=this.valueEl.style;t.color=e.badgeTextColor??"#19191A",t.fontSize=e.badgeFontSize??"14px",t.fontWeight=e.badgeFontWeight??"600",t.lineHeight="18px"}applyButtonStyles(e,t){let r=e.style,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()}},P=class{constructor(e,t,r,s){this.wrapper=document.createElement("div"),this.valueEl=document.createElement("span"),this.trashButton=document.createElement("button"),this.applyStyle(t),this.trashButton.type="button",this.trashButton.innerHTML=L(r.trash,fe);let i=n=>{n.preventDefault(),n.stopPropagation()};this.wrapper.addEventListener("mousedown",i),this.wrapper.addEventListener("dblclick",i),this.wrapper.addEventListener("contextmenu",i),this.trashButton.addEventListener("click",n=>{i(n),s()}),this.wrapper.appendChild(this.valueEl),this.wrapper.appendChild(this.trashButton),e.appendChild(this.wrapper)}applyStyle(e){let t=this.wrapper.style;t.position="absolute",t.zIndex="4",t.display="flex",t.alignItems="center",t.gap=e.badgeGap??"6px",t.padding="5px 7px",t.background=e.badgeBackground??"#FFFFFF",t.borderRadius=e.badgeBorderRadius??"12px",t.boxShadow=e.badgeBoxShadow??"0 2px 10px rgba(15, 23, 42, 0.18)",t.border=e.badgeBorder??"1px solid rgba(0,0,0,0.06)",t.transform="translate(-50%, -50%)",t.pointerEvents="auto",t.userSelect="none",t.whiteSpace="nowrap";let r=this.valueEl.style;r.color=e.badgeTextColor??"#19191A",r.fontSize=e.badgeFontSize??"13px",r.fontWeight=e.badgeFontWeight??"600",r.lineHeight="16px";let s=e.iconButtonSize??"20px",i=this.trashButton.style;i.display="inline-flex",i.alignItems="center",i.justifyContent="center",i.width=s,i.height=s,i.border="none",i.background="transparent",i.cursor="pointer",i.color=e.badgeTextColor??"#535969",i.padding="0"}setValue(e){this.valueEl.textContent=e}setPosition(e,t){this.wrapper.style.left=`${e}px`,this.wrapper.style.top=`${t}px`}destroy(){this.wrapper.remove()}};var ze=0,N=a=>`${a}-${Date.now().toString(36)}-${ze+=1}`,Ze=0,_e=()=>`mahal-measure-${Ze+=1}`,Me={pointColor:"#FFFFFF",pointStrokeColor:"#278960",pointStrokeWidth:2,pointRadius:5,lineColor:"#278960",lineWidth:3,fillColor:"#278960",fillOpacity:.15};function z(a,e){return a>=1e3?`${(a/1e3).toFixed(2)} ${e.kilometers??"\u043A\u043C"}`:`${Math.round(a)} ${e.meters??"\u043C"}`}function ve(a,e){return a>=1e5?`${(a/1e6).toFixed(2)} ${e.squareKilometers??"\u043A\u043C\xB2"}`:`${Math.round(a)} ${e.squareMeters??"\u043C\xB2"}`}function k(a){return a==="area"?3:2}function D(){return{type:"FeatureCollection",features:[]}}var E=class{constructor(e,t={}){this.layerHandlersBound=!1;this.destroyed=!1;this.ensuringLayers=!1;this.isActive=!1;this.draft=null;this.shapes=[];this.badge=null;this.shapeBadges=new Map;this.draggingPointId=null;this.draggingShapeId=null;this.dragPanWasEnabled=!0;this.suppressNextClick=!1;this.hoverInsert=null;this.handleClick=e=>this.onMapClick(e);this.handlePointMouseDown=e=>this.onPointMouseDown(e);this.handlePointMouseEnter=()=>{this.isActive&&this.setCursor("pointer")};this.handlePointMouseLeave=()=>{this.isActive&&this.setCursor("")};this.handlePointContextMenu=e=>this.onPointContextMenu(e);this.handleLineMouseMove=e=>this.onLineMouseMove(e);this.handleLineMouseLeave=()=>this.clearHoverInsert();this.handleLineMouseDown=e=>this.onLineMouseDown(e);this.handleStyleLoad=()=>this.onStyleLoad();this.handleStyleData=()=>{this.destroyed||this.map.getLayer(this.pointsLayerId)||this.refresh()};this.handleViewportChange=()=>{this.updateBadgePosition(),this.updateShapeBadgePositions()};this.onPointDragMove=e=>{if(!this.draggingShapeId||!this.draggingPointId)return;let t=this.findShape(this.draggingShapeId),r=t?.points.find(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.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??_e(),this.style=t.style??{},this.labels=t.labels??{},this.icons=t.icons??{},this.mode=t.mode??"distance",this.onChange=t.onChange,this.onCloseRequest=t.onCloseRequest,this.pointsSourceId=`${this.prefix}-points`,this.linesSourceId=`${this.prefix}-lines`,this.fillsSourceId=`${this.prefix}-fills`,this.hoverPointSourceId=`${this.prefix}-hover-point`,this.pointsLayerId=`${this.prefix}-points-layer`,this.linesCasingLayerId=`${this.prefix}-lines-casing-layer`,this.linesLayerId=`${this.prefix}-lines-layer`,this.fillsLayerId=`${this.prefix}-fills-layer`,this.hoverPointLayerId=`${this.prefix}-hover-point-layer`,this.badge=new x(e.getContainer(),this.style,this.icons,{onRemove:()=>this.removeShape((this.draft??this.getLastShape())?.id??""),onClose:()=>this.onCloseRequest?.(),onCheck:()=>this.finishDraft()}),this.ensureLayers(),this.map.on("click",this.handleClick),this.map.on("style.load",this.handleStyleLoad),this.map.on("styledata",this.handleStyleData),this.map.on("move",this.handleViewportChange)}bindLayerHandlers(){this.layerHandlersBound||(this.layerHandlersBound=!0,this.map.on("mousedown",this.pointsLayerId,this.handlePointMouseDown),this.map.on("mouseenter",this.pointsLayerId,this.handlePointMouseEnter),this.map.on("mouseleave",this.pointsLayerId,this.handlePointMouseLeave),this.map.on("contextmenu",this.pointsLayerId,this.handlePointContextMenu),this.map.on("mousemove",this.linesCasingLayerId,this.handleLineMouseMove),this.map.on("mouseleave",this.linesCasingLayerId,this.handleLineMouseLeave),this.map.on("mousedown",this.linesCasingLayerId,this.handleLineMouseDown))}unbindLayerHandlers(){this.layerHandlersBound&&(this.layerHandlersBound=!1,this.map.off("mousedown",this.pointsLayerId,this.handlePointMouseDown),this.map.off("mouseenter",this.pointsLayerId,this.handlePointMouseEnter),this.map.off("mouseleave",this.pointsLayerId,this.handlePointMouseLeave),this.map.off("contextmenu",this.pointsLayerId,this.handlePointContextMenu),this.map.off("mousemove",this.linesCasingLayerId,this.handleLineMouseMove),this.map.off("mouseleave",this.linesCasingLayerId,this.handleLineMouseLeave),this.map.off("mousedown",this.linesCasingLayerId,this.handleLineMouseDown))}start(e=this.mode){this.isActive=!0;let t=e!==this.mode;this.setMode(e),t||(this.render(),this.emitChange())}stop(){this.isActive=!1,this.onPointDragUp(),this.badge?.hide(),this.clearHoverInsert(),this.setCursor(this.originalCursor),this.emitChange()}setMode(e){this.mode!==e&&(this.mode=e,this.draft&&(this.draft.mode=e,this.recomputeShape(this.draft)),this.render(),this.emitChange())}finishDraft(){this.commitOrDiscardDraft(),this.render(),this.emitChange()}removeShape(e){e&&(this.draft?.id===e?this.draft=null:this.shapes=this.shapes.filter(t=>t.id!==e),this.hoverInsert?.shapeId===e&&this.clearHoverInsert(),this.render(),this.emitChange())}removePoint(e,t){let r=this.findShape(e);if(!r)return;if(r.points=r.points.filter(i=>i.id!==t),r.points.length===0){this.removeShape(e);return}if(!(this.draft?.id===e)&&r.points.length<k(r.mode)){this.removeShape(e);return}this.recomputeShape(r),this.render(),this.emitChange()}clearAll(){this.draft=null,this.shapes=[],this.clearHoverInsert(),this.render(),this.emitChange()}refresh(){this.destroyed||(this.ensureLayers(),this.render(),this.renderHoverPoint())}setStyleOptions(e){let t=this.style.lineDasharray!==void 0;this.style={...this.style,...e},this.applyPaintStyle(t),this.badge?.applyStyle(this.style),this.shapeBadges.forEach(r=>r.applyStyle(this.style))}getState(){return{active:this.isActive,mode:this.mode,draft:this.draft?this.cloneShape(this.draft):null,shapes:this.shapes.map(e=>this.cloneShape(e))}}destroy(){this.destroyed||(this.destroyed=!0,this.map.off("click",this.handleClick),this.unbindLayerHandlers(),this.map.off("style.load",this.handleStyleLoad),this.map.off("styledata",this.handleStyleData),this.map.off("move",this.handleViewportChange),this.onPointDragUp(),this.setCursor(this.originalCursor),this.badge?.destroy(),this.badge=null,this.shapeBadges.forEach(e=>e.destroy()),this.shapeBadges.clear(),this.removeLayers())}cloneShape(e){return{...e,points:e.points.map(t=>({...t,lngLat:[...t.lngLat]}))}}findShape(e){return this.draft?.id===e?this.draft:this.shapes.find(t=>t.id===e)??null}getLastShape(){return this.shapes[this.shapes.length-1]??null}commitOrDiscardDraft(){this.draft&&(this.draft.points.length>=k(this.draft.mode)&&this.shapes.push(this.draft),this.draft=null)}ensureDraft(){return this.draft||(this.draft={id:N("measure-shape"),mode:this.mode,points:[],closed:!1,distance:0,area:0}),this.draft}recomputeShape(e){let t=e.points.map(r=>r.lngLat);if(e.mode==="area"&&t.length>=3){e.closed=!0,e.area=K(t),e.distance=w([...t,t[0]]);return}e.closed=!1,e.area=0,e.distance=w(t)}onMapClick(e){if(!this.isActive)return;if(this.suppressNextClick){this.suppressNextClick=!1;return}if(this.queryPointsLayer(e.point).length>0)return;let r=this.ensureDraft();r.points.push({id:N("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.beginPointDrag(r,s))}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 s=r.x-t.x,i=r.y-t.y,n=s*s+i*i;if(n===0)return t;let p=Math.max(0,Math.min(1,((e.x-t.x)*s+(e.y-t.y)*i)/n));return{x:t.x+s*p,y:t.y+i*p}}findClosestPointOnShape(e,t){let r=e.points.map(h=>this.projectPoint(h.lngLat)),s=e.closed?r.length:r.length-1,i=-1,n=null,p=1/0;for(let h=0;h<s;h+=1){let u=r[h],d=r[(h+1)%r.length];if(!u||!d)continue;let c=this.closestPointOnSegment(t,u,d),g=c.x-t.x,m=c.y-t.y,b=Math.sqrt(g*g+m*m);b<p&&(p=b,i=h,n=c)}if(i===-1||!n)return null;let o=this.map.unproject([n.x,n.y]);return{index:i,lngLat:[+o.lng.toFixed(6),+o.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,s=r?this.findShape(r):null;if(!r||!s)return;let i=this.findClosestPointOnShape(s,e.point);i&&(this.hoverInsert={shapeId:r,index:i.index,lngLat:i.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 i={id:N("measure-point"),lngLat:this.hoverInsert.lngLat};s.points.splice(this.hoverInsert.index+1,0,i),this.recomputeShape(s),this.hoverInsert=null,this.renderHoverPoint(),this.render(),this.emitChange(),this.beginPointDrag(r,i.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,s=t?.properties?.pointId;!r||!s||(e.preventDefault(),this.removePoint(r,s))}setCursor(e){this.map.getCanvas().style.cursor=e}onStyleLoad(){this.refresh()}isMapUsable(){return!this.destroyed&&!!this.map.style}emitChange(){this.onChange?.(this.getState())}ensureLayers(){if(!(!this.isMapUsable()||this.ensuringLayers)){this.ensuringLayers=!0;try{this.createMissingLayers()}catch{}finally{this.ensuringLayers=!1}}}createMissingLayers(){let e={...Me,...this.style};this.map.getSource(this.linesSourceId)||this.map.addSource(this.linesSourceId,{type:"geojson",data:D()}),this.map.getSource(this.fillsSourceId)||this.map.addSource(this.fillsSourceId,{type:"geojson",data:D()}),this.map.getSource(this.pointsSourceId)||this.map.addSource(this.pointsSourceId,{type:"geojson",data:D()}),this.map.getSource(this.hoverPointSourceId)||this.map.addSource(this.hoverPointSourceId,{type:"geojson",data:D()}),this.map.getLayer(this.fillsLayerId)||this.map.addLayer({id:this.fillsLayerId,type:"fill",source:this.fillsSourceId,paint:{"fill-color":e.fillColor,"fill-opacity":e.fillOpacity}}),this.map.getLayer(this.linesCasingLayerId)||this.map.addLayer({id:this.linesCasingLayerId,type:"line",source:this.linesSourceId,layout:{"line-cap":"round","line-join":"round"},paint:{"line-color":"#FFFFFF","line-width":e.lineWidth+3,"line-opacity":.9}}),this.map.getLayer(this.linesLayerId)||this.map.addLayer({id:this.linesLayerId,type:"line",source:this.linesSourceId,layout:{"line-cap":"round","line-join":"round"},paint:{"line-color":e.lineColor,"line-width":e.lineWidth,...this.style.lineDasharray?{"line-dasharray":this.style.lineDasharray}:{}}}),this.map.getLayer(this.hoverPointLayerId)||this.map.addLayer({id:this.hoverPointLayerId,type:"circle",source:this.hoverPointSourceId,paint:{"circle-radius":Math.max(3,e.pointRadius-1),"circle-color":e.pointColor,"circle-stroke-color":e.pointStrokeColor,"circle-stroke-width":e.pointStrokeWidth,"circle-opacity":.8,"circle-stroke-opacity":.8}}),this.map.getLayer(this.pointsLayerId)||this.map.addLayer({id:this.pointsLayerId,type:"circle",source:this.pointsSourceId,paint:{"circle-radius":e.pointRadius,"circle-color":e.pointColor,"circle-stroke-color":e.pointStrokeColor,"circle-stroke-width":e.pointStrokeWidth}}),this.bindLayerHandlers()}applyPaintStyle(e=!1){if(!this.isMapUsable())return;let t={...Me,...this.style},r=(s,i,n)=>{this.map.getLayer(s)&&this.map.setPaintProperty(s,i,n)};r(this.fillsLayerId,"fill-color",t.fillColor),r(this.fillsLayerId,"fill-opacity",t.fillOpacity),r(this.linesCasingLayerId,"line-width",t.lineWidth+3),r(this.linesLayerId,"line-color",t.lineColor),r(this.linesLayerId,"line-width",t.lineWidth),this.style.lineDasharray!==void 0?r(this.linesLayerId,"line-dasharray",this.style.lineDasharray):e&&r(this.linesLayerId,"line-dasharray",null),r(this.hoverPointLayerId,"circle-radius",Math.max(3,t.pointRadius-1)),r(this.hoverPointLayerId,"circle-color",t.pointColor),r(this.hoverPointLayerId,"circle-stroke-color",t.pointStrokeColor),r(this.hoverPointLayerId,"circle-stroke-width",t.pointStrokeWidth),r(this.pointsLayerId,"circle-radius",t.pointRadius),r(this.pointsLayerId,"circle-color",t.pointColor),r(this.pointsLayerId,"circle-stroke-color",t.pointStrokeColor),r(this.pointsLayerId,"circle-stroke-width",t.pointStrokeWidth)}removeLayers(){[this.pointsLayerId,this.hoverPointLayerId,this.linesLayerId,this.linesCasingLayerId,this.fillsLayerId].forEach(e=>{this.map.getLayer(e)&&this.map.removeLayer(e)}),[this.pointsSourceId,this.hoverPointSourceId,this.linesSourceId,this.fillsSourceId].forEach(e=>{this.map.getSource(e)&&this.map.removeSource(e)})}setSourceData(e,t){this.map.getSource(e)?.setData(t)}buildLineFeature(e){if(e.points.length<2)return null;let t=e.points.map(r=>r.lngLat);return{type:"Feature",id:e.id,properties:{shapeId:e.id},geometry:{type:"LineString",coordinates:e.closed?[...t,t[0]]:t}}}buildFillFeature(e){if(e.mode!=="area"||e.points.length<3)return null;let t=e.points.map(r=>r.lngLat);return{type:"Feature",id:e.id,properties:{shapeId:e.id},geometry:{type:"Polygon",coordinates:[[...t,t[0]]]}}}buildPointFeatures(e){return e.points.map(t=>({type:"Feature",id:t.id,properties:{shapeId:e.id,pointId:t.id},geometry:{type:"Point",coordinates:t.lngLat}}))}getShapeAnchor(e){let t=e.points.map(r=>r.lngLat);return e.mode==="area"?W(t):q(t)}render(){this.ensureLayers();let e=this.shapes,t=e.map(i=>this.buildLineFeature(i)).filter(i=>!!i),r=e.map(i=>this.buildFillFeature(i)).filter(i=>!!i),s=e.flatMap(i=>this.buildPointFeatures(i));if(this.draft){let i=this.buildLineFeature(this.draft),n=this.buildFillFeature(this.draft);i&&t.push(i),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<k(t.mode)){this.shapeBadges.get(t.id)?.destroy(),this.shapeBadges.delete(t.id);return}let r=t.mode==="area"?ve(t.area,this.labels):z(t.distance,this.labels),s=this.shapeBadges.get(t.id);s||(s=new P(this.map.getContainer(),this.style,this.icons,()=>this.removeShape(t.id)),this.shapeBadges.set(t.id,s)),s.setValue(r);let i=this.map.project(this.getShapeAnchor(t));s.setPosition(i.x,i.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>=k(this.draft.mode),t=this.draft.mode==="area"?ve(this.draft.area,this.labels):z(this.draft.distance,this.labels);this.badge.setValue(e?t:z(this.draft.distance,this.labels)),this.badge.setCheckEnabled(e),this.badge.show(),this.updateBadgePosition()}updateBadgePosition(){if(!this.badge||!this.draft||this.draft.points.length===0||!this.isActive)return;let e=this.draft.points[this.draft.points.length-1];if(!e)return;let t=this.map.project(e.lngLat);this.badge.setPosition(t.x,t.y)}};export{C as CheckJSApi,$ as MahalMap,G as MahalMapDefaultMarker,E as MeasureTool,ce as Router,ie as Search,oe as SearchByLocation,ne as SearchPoi,me as keyUtils,Le as measureUtils,se as utils};
|
|
114
119
|
//# sourceMappingURL=index.mjs.map
|