@maptiler/client 1.5.0 → 1.7.0
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/maptiler-client.cjs +482 -309
- package/dist/maptiler-client.cjs.map +1 -1
- package/dist/maptiler-client.d.ts +177 -13
- package/dist/maptiler-client.min.mjs +1 -1
- package/dist/maptiler-client.mjs +471 -309
- package/dist/maptiler-client.mjs.map +1 -1
- package/dist/maptiler-client.umd.js +483 -310
- package/dist/maptiler-client.umd.js.map +1 -1
- package/dist/maptiler-client.umd.min.js +1 -1
- package/examples/test-node.js +9 -9
- package/package.json +25 -18
- package/readme.md +1 -1
- package/rollup.config.js +3 -3
- package/src/callFetch.ts +2 -2
- package/src/config.ts +4 -1
- package/src/demProfiler/getElevation.ts +46 -0
- package/src/demProfiler/index.ts +240 -0
- package/src/demProfiler/tileCover.ts +96 -0
- package/src/geometry/area.ts +96 -0
- package/src/geometry/distance.ts +45 -0
- package/src/geometry/index.ts +3 -0
- package/src/geometry/util.ts +34 -0
- package/src/index.ts +3 -0
- package/src/language.ts +1 -1
- package/src/mapstyle.ts +5 -5
- package/src/services/ServiceError.ts +5 -2
- package/src/services/coordinates.ts +14 -9
- package/src/services/data.ts +3 -3
- package/src/services/geocoding.ts +113 -32
- package/src/services/geolocation.ts +2 -2
- package/src/services/simplify.ts +3 -3
- package/src/services/staticMaps.ts +9 -9
- package/tsconfig.json +1 -1
- package/docs/.nojekyll +0 -1
- package/docs/assets/custom.css +0 -118
- package/docs/assets/highlight.css +0 -85
- package/docs/assets/main.js +0 -58
- package/docs/assets/search.js +0 -1
- package/docs/assets/style.css +0 -1280
- package/docs/classes/config.ClientConfig.html +0 -132
- package/docs/classes/services_ServiceError.ServiceError.html +0 -103
- package/docs/functions/language.getAutoLanguageGeocoding.html +0 -60
- package/docs/functions/services_simplify.default.html +0 -65
- package/docs/images/JS-logo.svg +0 -4
- package/docs/images/TS-logo.svg +0 -6
- package/docs/images/maptiler-client-logo.afdesign +0 -0
- package/docs/images/maptiler-client-logo.svg +0 -75
- package/docs/images/maptiler-logo-256.png +0 -0
- package/docs/images/maptiler-logo.svg +0 -23
- package/docs/images/screenshots/static-bounded-europe-1024.png +0 -0
- package/docs/images/screenshots/static-bounded-europe-2048.png +0 -0
- package/docs/images/screenshots/static-bounded-portugal-1024x2048.png +0 -0
- package/docs/images/screenshots/static-bounded-portugal-2048x2048.png +0 -0
- package/docs/images/screenshots/static-with-path.png +0 -0
- package/docs/index.html +0 -340
- package/docs/modules/config.html +0 -71
- package/docs/modules/language.html +0 -71
- package/docs/modules/services_ServiceError.html +0 -61
- package/docs/modules/services_coordinates.html +0 -84
- package/docs/modules/services_data.html +0 -66
- package/docs/modules/services_geocoding.html +0 -82
- package/docs/modules/services_geolocation.html +0 -68
- package/docs/modules/services_simplify.html +0 -61
- package/docs/modules/services_staticMaps.html +0 -74
- package/docs/modules.html +0 -59
- package/docs/types/config.FetchFunction.html +0 -71
- package/docs/types/language.LanguageGeocodingString.html +0 -58
- package/docs/types/services_coordinates.CoordinateExport.html +0 -71
- package/docs/types/services_coordinates.CoordinateGrid.html +0 -69
- package/docs/types/services_coordinates.CoordinateId.html +0 -71
- package/docs/types/services_coordinates.CoordinateSearch.html +0 -93
- package/docs/types/services_coordinates.CoordinateSearchResult.html +0 -75
- package/docs/types/services_coordinates.CoordinateTransformResult.html +0 -76
- package/docs/types/services_coordinates.CoordinateTransformation.html +0 -89
- package/docs/types/services_coordinates.CoordinatesSearchOptions.html +0 -83
- package/docs/types/services_coordinates.CoordinatesTransformOptions.html +0 -85
- package/docs/types/services_coordinates.XYZ.html +0 -73
- package/docs/types/services_data.GetDataOptions.html +0 -64
- package/docs/types/services_geocoding.ByIdGeocodingOptions.html +0 -63
- package/docs/types/services_geocoding.CommonForwardAndReverseGeocodingOptions.html +0 -63
- package/docs/types/services_geocoding.Coordinates.html +0 -63
- package/docs/types/services_geocoding.FeatureHierarchy.html +0 -74
- package/docs/types/services_geocoding.GeocodingFeature.html +0 -63
- package/docs/types/services_geocoding.GeocodingOptions.html +0 -63
- package/docs/types/services_geocoding.GeocodingSearchResult.html +0 -80
- package/docs/types/services_geocoding.LanguageGeocodingOptions.html +0 -70
- package/docs/types/services_geocoding.ReverseGeocodingOptions.html +0 -63
- package/docs/types/services_geolocation.GeolocationInfoOptions.html +0 -65
- package/docs/types/services_geolocation.GeolocationResult.html +0 -128
- package/docs/types/services_staticMaps.AutomaticStaticMapOptions.html +0 -61
- package/docs/types/services_staticMaps.BoundedStaticMapOptions.html +0 -61
- package/docs/types/services_staticMaps.CenteredStaticMapOptions.html +0 -61
- package/docs/types/services_staticMaps.StaticMapBaseOptions.html +0 -157
- package/docs/types/services_staticMaps.StaticMapMarker.html +0 -61
- package/docs/variables/config.config.html +0 -58
- package/docs/variables/language.LanguageGeocoding.html +0 -171
- package/docs/variables/services_coordinates.coordinates.html +0 -110
- package/docs/variables/services_data.data.html +0 -80
- package/docs/variables/services_geocoding.geocoding.html +0 -265
- package/docs/variables/services_geolocation.geolocation.html +0 -79
- package/docs/variables/services_staticMaps.staticMaps.html +0 -128
- package/docsmd/.nojekyll +0 -1
- package/docsmd/README.md +0 -880
- package/docsmd/assets/custom.css +0 -118
- package/docsmd/classes/ClientConfig.md +0 -90
- package/docsmd/classes/MapStyleVariant.md +0 -234
- package/docsmd/classes/ReferenceMapStyle.md +0 -169
- package/docsmd/classes/ServiceError.md +0 -52
- package/images/JS-logo.svg +0 -4
- package/images/TS-logo.svg +0 -6
- package/images/maptiler-client-logo.afdesign +0 -0
- package/images/maptiler-client-logo.svg +0 -75
- package/images/maptiler-logo-256.png +0 -0
- package/images/maptiler-logo.svg +0 -23
- package/images/screenshots/static-bounded-europe-1024.png +0 -0
- package/images/screenshots/static-bounded-europe-2048.png +0 -0
- package/images/screenshots/static-bounded-portugal-1024x2048.png +0 -0
- package/images/screenshots/static-bounded-portugal-2048x2048.png +0 -0
- package/images/screenshots/static-with-path.png +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
(function(u,R){typeof exports=="object"&&typeof module<"u"?R(exports):typeof define=="function"&&define.amd?define(["exports"],R):(u=typeof globalThis<"u"?globalThis:u||self,R(u.maptilerClient={}))})(this,function(u){"use strict";function R(){return typeof self<"u"?fetch.bind(self):typeof global<"u"&&global.fetch?global.fetch:null}class C{constructor(){this._apiKey="",this._fetch=R()}set apiKey(e){this._apiKey=e}get apiKey(){return this._apiKey}set fetch(e){this._fetch=e}get fetch(){return this._fetch}}const y=new C,S={AUTO:"auto",ALBANIAN:"sq",ARABIC:"ar",ARMENIAN:"hy",AZERBAIJANI:"az",BELORUSSIAN:"be",BOSNIAN:"bs",BRETON:"br",BULGARIAN:"bg",CATALAN:"ca",CHINESE:"zh",CROATIAN:"hr",CZECH:"cs",DANISH:"da",DUTCH:"nl",ENGLISH:"en",ESPERANTO:"eo",ESTONIAN:"et",FINNISH:"fi",FRENCH:"fr",FRISIAN:"fy",GEORGIAN:"ka",GERMAN:"de",GREEK:"el",HEBREW:"he",HUNGARIAN:"hu",ICELANDIC:"is",IRISH:"ga",ITALIAN:"it",JAPANESE:"ja",KANNADA:"kn",KAZAKH:"kk",KOREAN:"ko",ROMAN_LATIN:"la",LATVIAN:"lv",LITHUANIAN:"lt",LUXEMBOURGISH:"lb",MACEDONIAN:"mk",MALTESE:"mt",NORWEGIAN:"no",POLISH:"pl",PORTUGUESE:"pt",ROMANIAN:"ro",ROMANSH:"rm",RUSSIAN:"ru",SCOTTISH_GAELIC:"gd",SERBIAN_CYRILLIC:"sr",SLOVAK:"sk",SLOVENE:"sl",SPANISH:"es",SWEDISH:"sv",THAI:"th",TURKISH:"tr",UKRAINIAN:"uk",WELSH:"cy"},x=new Set(Object.values(S));function B(){if(typeof navigator>"u")return Intl.DateTimeFormat().resolvedOptions().locale.split("-")[0];const n=Array.from(new Set(navigator.languages.map(e=>e.split("-")[0]))).filter(e=>x.has(e));return n.length?n[0]:S.ENGLISH}var W=(n,e,t)=>new Promise((i,r)=>{var s=o=>{try{c(t.next(o))}catch(l){r(l)}},a=o=>{try{c(t.throw(o))}catch(l){r(l)}},c=o=>o.done?i(o.value):Promise.resolve(o.value).then(s,a);c((t=t.apply(n,e)).next())});function L(n){return W(this,arguments,function*(e,t={}){if(y.fetch===null)throw new Error("The fetch function was not found. If on NodeJS < 18 please specify the fetch function with config.fetch");if(new URL(e).searchParams.get("key").trim()==="")throw new Error("The MapTiler Cloud API key is missing. Set it in `config.apiKey` or get one for free at https://maptiler.com");return y.fetch(e,t)})}const g={maptilerApiURL:"https://api.maptiler.com/",mapStyle:"streets-v2"};Object.freeze(g);class A extends Error{constructor(e,t=""){super(`Call to enpoint ${e.url} failed with the status code ${e.status}. ${t}`),this.res=e}}var I=(n,e,t)=>new Promise((i,r)=>{var s=o=>{try{c(t.next(o))}catch(l){r(l)}},a=o=>{try{c(t.throw(o))}catch(l){r(l)}},c=o=>o.done?i(o.value):Promise.resolve(o.value).then(s,a);c((t=t.apply(n,e)).next())});const T={400:"Query too long / Invalid parameters",403:"Key is missing, invalid or restricted"};function K(n,e){if(e.language==null)return;const t=Array.from(new Set((Array.isArray(e.language)?e.language:[e.language]).map(i=>i===S.AUTO?B():i))).join(",");n.set("language",t)}function O(n,e){var t;n.set("key",(t=e.apiKey)!=null?t:y.apiKey),e.limit!=null&&n.set("limit",String(e.limit)),e.types!=null&&n.set("types",e.types.join(",")),K(n,e)}function j(n,e){O(n,e),e.bbox!=null&&n.set("bbox",e.bbox.join(",")),e.proximity!=null&&n.set("proximity",e.proximity.join(",")),e.country!=null&&n.set("country",e.country.join(",")),e.fuzzyMatch!=null&&n.set("fuzzyMatch",e.fuzzyMatch?"true":"false"),e.autocomplete!=null&&n.set("autocomplete",e.autocomplete?"true":"false")}function z(n){return I(this,arguments,function*(e,t={}){var i;if(typeof e!="string"||e.trim().length===0)throw new Error("The query must be a non-empty string");const r=new URL(`geocoding/${encodeURIComponent(e)}.json`,g.maptilerApiURL),{searchParams:s}=r;j(s,t);const a=r.toString(),c=yield L(a);if(!c.ok)throw new A(c,(i=T[c.status])!=null?i:"");return yield c.json()})}function _(n){return I(this,arguments,function*(e,t={}){var i;if(!Array.isArray(e)||e.length<2)throw new Error("The position must be an array of form [lng, lat].");const r=new URL(`geocoding/${e[0]},${e[1]}.json`,g.maptilerApiURL);O(r.searchParams,t);const s=r.toString(),a=yield L(s);if(!a.ok)throw new A(a,(i=T[a.status])!=null?i:"");return yield a.json()})}function q(n){return I(this,arguments,function*(e,t={}){var i;const r=new URL(`geocoding/${e}.json`,g.maptilerApiURL);K(r.searchParams,t);const s=r.toString(),a=yield L(s);if(!a.ok)throw new A(a,(i=T[a.status])!=null?i:"");return yield a.json()})}function Y(n){return I(this,arguments,function*(e,t={}){var i;if(!e.length)return[];const r=e.map(f=>encodeURIComponent(f)).join(";"),s=new URL(`geocoding/${r}.json`,g.maptilerApiURL),{searchParams:a}=s;j(a,t);const c=s.toString(),o=yield L(c);if(!o.ok)throw new A(o,(i=T[o.status])!=null?i:"");const l=yield o.json();return e.length===1?[l]:l})}const Z={forward:z,reverse:_,byId:q,batch:Y,language:S};var J=(n,e,t)=>new Promise((i,r)=>{var s=o=>{try{c(t.next(o))}catch(l){r(l)}},a=o=>{try{c(t.throw(o))}catch(l){r(l)}},c=o=>o.done?i(o.value):Promise.resolve(o.value).then(s,a);c((t=t.apply(n,e)).next())});const H={403:"Key is missing, invalid or restricted"};function Q(){return J(this,arguments,function*(n={}){var e;const t=new URL("geolocation/ip.json",g.maptilerApiURL);t.searchParams.set("key",(e=n.apiKey)!=null?e:y.apiKey);const i=t.toString(),r=yield L(i);if(!r.ok)throw new A(r,r.status in H?H[r.status]:"");return yield r.json()})}const X={info:Q};var V=(n,e,t)=>new Promise((i,r)=>{var s=o=>{try{c(t.next(o))}catch(l){r(l)}},a=o=>{try{c(t.throw(o))}catch(l){r(l)}},c=o=>o.done?i(o.value):Promise.resolve(o.value).then(s,a);c((t=t.apply(n,e)).next())});const U={403:"Key is missing, invalid or restricted"};function ee(n){return V(this,arguments,function*(e,t={}){var i;if(typeof e!="string"||e.trim().length===0)throw new Error("The query must be a non-empty string");const r=new URL(`coordinates/search/${e}.json`,g.maptilerApiURL);r.searchParams.set("key",(i=t.apiKey)!=null?i:y.apiKey),"limit"in t&&r.searchParams.set("limit",t.limit.toString()),"transformations"in t&&r.searchParams.set("transformations",t.transformations.toString()),"exports"in t&&r.searchParams.set("exports",t.exports.toString());const s=r.toString(),a=yield L(s);if(!a.ok)throw new A(a,a.status in U?U[a.status]:"");return yield a.json()})}function te(n){return V(this,arguments,function*(e,t={}){var i;const r=(Array.isArray(e[0])?e:[e]).map(o=>`${o[0]},${o[1]}`).join(";"),s=new URL(`coordinates/transform/${r}.json`,g.maptilerApiURL);s.searchParams.set("key",(i=t.apiKey)!=null?i:y.apiKey),"sourceCrs"in t&&s.searchParams.set("s_srs",t.sourceCrs.toString()),"targetCrs"in t&&s.searchParams.set("t_srs",t.targetCrs.toString()),"operations"in t&&s.searchParams.set("ops",(Array.isArray(t.operations)?t.operations:[t.operations]).join("|"));const a=s.toString(),c=yield L(a);if(!c.ok)throw new A(c,c.status in U?U[c.status]:"");return yield c.json()})}const ne={search:ee,transform:te};var ie=(n,e,t)=>new Promise((i,r)=>{var s=o=>{try{c(t.next(o))}catch(l){r(l)}},a=o=>{try{c(t.throw(o))}catch(l){r(l)}},c=o=>o.done?i(o.value):Promise.resolve(o.value).then(s,a);c((t=t.apply(n,e)).next())});const G={403:"Key is missing, invalid or restricted"};function re(n){return ie(this,arguments,function*(e,t={}){var i;if(typeof e!="string"||e.trim().length===0)throw new Error("The data ID must be a non-empty string");const r=new URL(`data/${encodeURIComponent(e)}/features.json`,g.maptilerApiURL);r.searchParams.set("key",(i=t.apiKey)!=null?i:y.apiKey);const s=r.toString(),a=yield L(s);if(!a.ok)throw new A(a,a.status in G?G[a.status]:"");return yield a.json()})}const ae={get:re};function M(n){const e=/^maptiler:\/\/(.*)/;let t;const i=n.trim();let r;return i.startsWith("http://")||i.startsWith("https://")?r=i:(t=e.exec(i))!==null?r=`https://api.maptiler.com/maps/${t[1]}/style.json`:r=`https://api.maptiler.com/maps/${i}/style.json`,r}class k{constructor(e,t,i,r,s,a){this.name=e,this.variantType=t,this.id=i,this.referenceStyle=r,this.description=s,this.imageURL=a}getName(){return this.name}getFullName(){return`${this.referenceStyle.getName()} ${this.name}`}getType(){return this.variantType}getId(){return this.id}getDescription(){return this.description}getReferenceStyle(){return this.referenceStyle}hasVariant(e){return this.referenceStyle.hasVariant(e)}getVariant(e){return this.referenceStyle.getVariant(e)}getVariants(){return this.referenceStyle.getVariants().filter(e=>e!==this)}getImageURL(){return this.imageURL}getExpandedStyleURL(){return M(this.getId())}}class ${constructor(e,t){this.name=e,this.id=t,this.variants={},this.orderedVariants=[]}getName(){return this.name}getId(){return this.id}addVariant(e){this.variants[e.getType()]=e,this.orderedVariants.push(e)}hasVariant(e){return e in this.variants}getVariant(e){return e in this.variants?this.variants[e]:this.orderedVariants[0]}getVariants(){return Object.values(this.variants)}getDefaultVariant(){return this.orderedVariants[0]}}const D=[{referenceStyleID:"STREETS",name:"Streets",description:"",variants:[{id:"streets-v2",name:"Default",variantType:"DEFAULT",description:"",imageURL:""},{id:"streets-v2-dark",name:"Dark",variantType:"DARK",description:"",imageURL:""},{id:"streets-v2-light",name:"Light",variantType:"LIGHT",description:"",imageURL:""},{id:"streets-v2-night",name:"Night",variantType:"NIGHT",description:"",imageURL:""},{id:"streets-v2-pastel",name:"Pastel",variantType:"PASTEL",description:"",imageURL:""}]},{referenceStyleID:"OUTDOOR",name:"Outdoor",description:"",variants:[{id:"outdoor-v2",name:"Default",variantType:"DEFAULT",description:"",imageURL:""},{id:"outdoor-v2-dark",name:"Dark",variantType:"DARK",description:"",imageURL:""}]},{referenceStyleID:"WINTER",name:"Winter",description:"",variants:[{id:"winter-v2",name:"Default",variantType:"DEFAULT",description:"",imageURL:""},{id:"winter-v2-dark",name:"Dark",variantType:"DARK",description:"",imageURL:""}]},{referenceStyleID:"SATELLITE",name:"Satellite",description:"",variants:[{id:"satellite",name:"Default",variantType:"DEFAULT",description:"",imageURL:""}]},{referenceStyleID:"HYBRID",name:"Hybrid",description:"",variants:[{id:"hybrid",name:"Default",variantType:"DEFAULT",description:"",imageURL:""}]},{referenceStyleID:"BASIC",name:"Basic",description:"",variants:[{id:"basic-v2",name:"Default",variantType:"DEFAULT",description:"",imageURL:""},{id:"basic-v2-dark",name:"Dark",variantType:"DARK",description:"",imageURL:""},{id:"basic-v2-light",name:"Light",variantType:"LIGHT",description:"",imageURL:""}]},{referenceStyleID:"BRIGHT",name:"Bright",description:"",variants:[{id:"bright-v2",name:"Default",variantType:"DEFAULT",description:"",imageURL:""},{id:"bright-v2-dark",name:"Dark",variantType:"DARK",description:"",imageURL:""},{id:"bright-v2-light",name:"Light",variantType:"LIGHT",description:"",imageURL:""},{id:"bright-v2-pastel",name:"Pastel",variantType:"PASTEL",description:"",imageURL:""}]},{referenceStyleID:"OPENSTREETMAP",name:"OpenStreetMap",description:"",variants:[{id:"openstreetmap",name:"Default",variantType:"DEFAULT",description:"",imageURL:""}]},{referenceStyleID:"TOPO",name:"Topo",description:"",variants:[{id:"topo-v2",name:"Default",variantType:"DEFAULT",description:"",imageURL:""},{id:"topo-v2-dark",name:"Dark",variantType:"DARK",description:"",imageURL:""},{id:"topo-v2-shiny",name:"Shiny",variantType:"SHINY",description:"",imageURL:""},{id:"topo-v2-pastel",name:"Pastel",variantType:"PASTEL",description:"",imageURL:""},{id:"topo-v2-topographique",name:"Topographique",variantType:"TOPOGRAPHIQUE",description:"",imageURL:""}]},{referenceStyleID:"VOYAGER",name:"Voyager",description:"",variants:[{id:"voyager-v2",name:"Default",variantType:"DEFAULT",description:"",imageURL:""},{id:"voyager-v2-darkmatter",name:"Darkmatter",variantType:"DARK",description:"",imageURL:""},{id:"voyager-v2-positron",name:"Positron",variantType:"LIGHT",description:"",imageURL:""},{id:"voyager-v2-vintage",name:"Vintage",variantType:"VINTAGE",description:"",imageURL:""}]},{referenceStyleID:"TONER",name:"Toner",description:"",variants:[{id:"toner-v2",name:"Default",variantType:"DEFAULT",description:"",imageURL:""},{id:"toner-v2-background",name:"Background",variantType:"BACKGROUND",description:"",imageURL:""},{id:"toner-v2-lite",name:"Lite",variantType:"LITE",description:"",imageURL:""},{id:"toner-v2-lines",name:"Lines",variantType:"LINES",description:"",imageURL:""}]},{referenceStyleID:"DATAVIZ",name:"Dataviz",description:"",variants:[{id:"dataviz",name:"Default",variantType:"DEFAULT",description:"",imageURL:""},{id:"dataviz-dark",name:"Dark",variantType:"DARK",description:"",imageURL:""},{id:"dataviz-light",name:"Light",variantType:"LIGHT",description:"",imageURL:""}]},{referenceStyleID:"BACKDROP",name:"Backdrop",description:"",variants:[{id:"backdrop",name:"Default",variantType:"DEFAULT",description:"",imageURL:""},{id:"backdrop-dark",name:"Dark",variantType:"DARK",description:"",imageURL:""},{id:"backdrop-light",name:"Light",variantType:"LIGHT",description:"",imageURL:""}]},{referenceStyleID:"OCEAN",name:"Ocean",description:"",variants:[{id:"ocean",name:"Default",variantType:"DEFAULT",description:"",imageURL:""}]}];function se(n){return new Proxy(n,{get(e,t,i){return e.hasVariant(t)?e.getVariant(t):t.toString().toUpperCase()===t?n.getDefaultVariant():Reflect.get(e,t,i)}})}function oe(){const n={};for(let e=0;e<D.length;e+=1){const t=D[e],i=se(new $(t.name,t.referenceStyleID));for(let r=0;r<t.variants.length;r+=1){const s=t.variants[r],a=new k(s.name,s.variantType,s.id,i,s.description,s.imageURL);i.addVariant(a)}n[t.referenceStyleID]=i}return n}function E(n){if(!n)return F[D[0].referenceStyleID].getDefaultVariant().getId();if(typeof n=="string"||n instanceof String)return n.trim().toLowerCase();if(n instanceof k)return n.getId();if(n instanceof $)return n.getDefaultVariant().getId()}const F=oe();function ce(n,e,t){let i=e[0],r=e[1],s=t[0]-i,a=t[1]-r;if(s!==0||a!==0){const c=((n[0]-i)*s+(n[1]-r)*a)/(s*s+a*a);c>1?(i=t[0],r=t[1]):c>0&&(i+=s*c,r+=a*c)}return s=n[0]-i,a=n[1]-r,s*s+a*a}function P(n,e,t,i,r){let s=i,a;for(let c=e+1;c<t;c++){const o=ce(n[c],n[e],n[t]);o>s&&(a=c,s=o)}s>i&&(a-e>1&&P(n,e,a,i,r),r.push(n[a]),t-a>1&&P(n,a,t,i,r))}function le(n,e){const t=n.length-1,i=[n[0]];return P(n,0,t,e,i),i.push(n[t]),i}function pe(n,e){if(n.length<=2)return n;const t=e!==void 0?e*e:1;return le(n,t)}function w(n,e=!0){let t=`${n[0]},${n[1]}`;return n.length===3&&e&&(t+=`,${n[2]}`),t}function N(n,e=3e3){let t=n.map(s=>s.join(",")).join("|"),i=5e-6;const r=1e-5;for(;t.length>e;)t=pe(n,i).map(s=>`${s[0]},${s[1]}`).join("|"),i+=r;return t}function me(n,e,t={}){var i,r,s,a,c;const o=E(t.style),l=t.hiDPI?"@2x":"",f=(i=t.format)!=null?i:"png";let d=~~((r=t.width)!=null?r:1024),m=~~((s=t.height)!=null?s:1024);t.hiDPI&&(d=~~(d/2),m=~~(m/2));const p=new URL(`maps/${encodeURIComponent(o)}/static/${n[0]},${n[1]},${e}/${d}x${m}${l}.${f}`,g.maptilerApiURL);if("attribution"in t&&p.searchParams.set("attribution",t.attribution.toString()),"markers"in t){let h="";const v="markerIcon"in t;v&&(h+=`icon:${t.markerIcon}|`),v&&"markerAnchor"in t&&(h+=`anchor:${t.markerAnchor}|`),v&&t.hiDPI&&(h+="scale:2|");const b=Array.isArray(t.markers[0])?t.markers:[t.markers];h+=b.map(ge=>w(ge,!v)).join("|"),p.searchParams.set("markers",h)}if("path"in t){let h="";if(h+=`fill:${(a=t.pathFillColor)!=null?a:"none"}|`,"pathStrokeColor"in t&&(h+=`stroke:${t.pathStrokeColor}|`),"pathWidth"in t){const v=t.pathWidth/(t.hiDPI?2:1);h+=`width:${v.toString()}|`}h+=N(t.path),p.searchParams.set("path",h)}return p.searchParams.set("key",(c=t.apiKey)!=null?c:y.apiKey),p.toString()}function he(n,e={}){var t,i,r,s,a;const c=E(e.style),o=e.hiDPI?"@2x":"",l=(t=e.format)!=null?t:"png";let f=~~((i=e.width)!=null?i:1024),d=~~((r=e.height)!=null?r:1024);e.hiDPI&&(f=~~(f/2),d=~~(d/2));const m=new URL(`maps/${encodeURIComponent(c)}/static/${n[0]},${n[1]},${n[2]},${n[3]}/${f}x${d}${o}.${l}`,g.maptilerApiURL);if("attribution"in e&&m.searchParams.set("attribution",e.attribution.toString()),"padding"in e&&m.searchParams.set("padding",e.padding.toString()),"markers"in e){let p="";const h="markerIcon"in e;h&&(p+=`icon:${e.markerIcon}|`),h&&"markerAnchor"in e&&(p+=`anchor:${e.markerAnchor}|`),h&&e.hiDPI&&(p+="scale:2|");const v=Array.isArray(e.markers[0])?e.markers:[e.markers];p+=v.map(b=>w(b,!h)).join("|"),m.searchParams.set("markers",p)}if("path"in e){let p="";if(p+=`fill:${(s=e.pathFillColor)!=null?s:"none"}|`,"pathStrokeColor"in e&&(p+=`stroke:${e.pathStrokeColor}|`),"pathWidth"in e){const h=e.pathWidth/(e.hiDPI?2:1);p+=`width:${h.toString()}|`}p+=N(e.path),m.searchParams.set("path",p)}return m.searchParams.set("key",(a=e.apiKey)!=null?a:y.apiKey),m.toString()}function ue(n={}){var e,t,i,r,s;if(!("markers"in n)&&!("path"in n))throw new Error("Automatic static maps require markers and/or path to be created.");const a=E(n.style),c=n.hiDPI?"@2x":"",o=(e=n.format)!=null?e:"png";let l=~~((t=n.width)!=null?t:1024),f=~~((i=n.height)!=null?i:1024);n.hiDPI&&(l=~~(l/2),f=~~(f/2));const d=new URL(`maps/${encodeURIComponent(a)}/static/auto/${l}x${f}${c}.${o}`,g.maptilerApiURL);if("attribution"in n&&d.searchParams.set("attribution",n.attribution.toString()),"padding"in n&&d.searchParams.set("padding",n.padding.toString()),"markers"in n){let m="";const p="markerIcon"in n;p&&(m+=`icon:${n.markerIcon}|`),p&&"markerAnchor"in n&&(m+=`anchor:${n.markerAnchor}|`),p&&n.hiDPI&&(m+="scale:2|");const h=Array.isArray(n.markers[0])?n.markers:[n.markers];m+=h.map(v=>w(v,!p)).join("|"),d.searchParams.set("markers",m)}if("path"in n){let m="";if(m+=`fill:${(r=n.pathFillColor)!=null?r:"none"}|`,"pathStrokeColor"in n&&(m+=`stroke:${n.pathStrokeColor}|`),"pathWidth"in n){const p=n.pathWidth/(n.hiDPI?2:1);m+=`width:${p.toString()}|`}m+=N(n.path),d.searchParams.set("path",m)}return d.searchParams.set("key",(s=n.apiKey)!=null?s:y.apiKey),d.toString()}const de={centered:me,bounded:he,automatic:ue};u.ClientConfig=C,u.LanguageGeocoding=S,u.MapStyle=F,u.MapStyleVariant=k,u.ReferenceMapStyle=$,u.ServiceError=A,u.config=y,u.coordinates=ne,u.data=ae,u.expandMapStyle=M,u.geocoding=Z,u.geolocation=X,u.mapStylePresetList=D,u.staticMaps=de,Object.defineProperty(u,"__esModule",{value:!0})});
|
|
1
|
+
(function(p,R){typeof exports=="object"&&typeof module<"u"?R(exports):typeof define=="function"&&define.amd?define(["exports"],R):(p=typeof globalThis<"u"?globalThis:p||self,R(p.maptilerClient={}))})(this,function(p){"use strict";function R(){return typeof self<"u"?fetch.bind(self):typeof global<"u"&&global.fetch?global.fetch:null}class j{constructor(){this._apiKey="",this._fetch=R()}set apiKey(e){this._apiKey=e}get apiKey(){return this._apiKey}set fetch(e){this._fetch=e}get fetch(){return this._fetch}}const u=new j,L={AUTO:"auto",ALBANIAN:"sq",ARABIC:"ar",ARMENIAN:"hy",AZERBAIJANI:"az",BELORUSSIAN:"be",BOSNIAN:"bs",BRETON:"br",BULGARIAN:"bg",CATALAN:"ca",CHINESE:"zh",CROATIAN:"hr",CZECH:"cs",DANISH:"da",DUTCH:"nl",ENGLISH:"en",ESPERANTO:"eo",ESTONIAN:"et",FINNISH:"fi",FRENCH:"fr",FRISIAN:"fy",GEORGIAN:"ka",GERMAN:"de",GREEK:"el",HEBREW:"he",HUNGARIAN:"hu",ICELANDIC:"is",IRISH:"ga",ITALIAN:"it",JAPANESE:"ja",KANNADA:"kn",KAZAKH:"kk",KOREAN:"ko",ROMAN_LATIN:"la",LATVIAN:"lv",LITHUANIAN:"lt",LUXEMBOURGISH:"lb",MACEDONIAN:"mk",MALTESE:"mt",NORWEGIAN:"no",POLISH:"pl",PORTUGUESE:"pt",ROMANIAN:"ro",ROMANSH:"rm",RUSSIAN:"ru",SCOTTISH_GAELIC:"gd",SERBIAN_CYRILLIC:"sr",SLOVAK:"sk",SLOVENE:"sl",SPANISH:"es",SWEDISH:"sv",THAI:"th",TURKISH:"tr",UKRAINIAN:"uk",WELSH:"cy"},nt=new Set(Object.values(L));function it(){if(typeof navigator>"u")return Intl.DateTimeFormat().resolvedOptions().locale.split("-")[0];const t=Array.from(new Set(navigator.languages.map(e=>e.split("-")[0]))).filter(e=>nt.has(e));return t.length?t[0]:L.ENGLISH}async function v(t,e={}){if(u.fetch===null)throw new Error("The fetch function was not found. If on NodeJS < 18 please specify the fetch function with config.fetch");if(new URL(t).searchParams.get("key").trim()==="")throw new Error("The MapTiler Cloud API key is missing. Set it in `config.apiKey` or get one for free at https://maptiler.com");return u.fetch(t,e)}const d={maptilerApiURL:"https://api.maptiler.com/",mapStyle:"streets-v2"};Object.freeze(d);class f extends Error{constructor(e,n=""){super(`Call to enpoint ${e.url} failed with the status code ${e.status}. ${n}`),this.res=e}}const D={400:"Query too long / Invalid parameters",403:"Key is missing, invalid or restricted"};function H(t,e){if(e.language==null)return;const n=Array.from(new Set((Array.isArray(e.language)?e.language:[e.language]).map(i=>i===L.AUTO?it():i))).join(",");t.set("language",n)}function V(t,e){t.set("key",e.apiKey??u.apiKey),e.limit!=null&&t.set("limit",String(e.limit)),e.types!=null&&t.set("types",e.types.join(",")),H(t,e)}function G(t,e){V(t,e),e.bbox!=null&&t.set("bbox",e.bbox.join(",")),e.proximity!=null&&t.set("proximity",e.proximity.join(",")),e.country!=null&&t.set("country",e.country.join(",")),e.fuzzyMatch!=null&&t.set("fuzzyMatch",e.fuzzyMatch?"true":"false"),e.autocomplete!=null&&t.set("autocomplete",e.autocomplete?"true":"false")}async function at(t,e={}){if(typeof t!="string"||t.trim().length===0)throw new Error("The query must be a non-empty string");const n=new URL(`geocoding/${encodeURIComponent(t)}.json`,d.maptilerApiURL),{searchParams:i}=n;G(i,e);const a=n.toString(),r=await v(a);if(!r.ok)throw new f(r,D[r.status]??"");return await r.json()}async function rt(t,e={}){if(!Array.isArray(t)||t.length<2)throw new Error("The position must be an array of form [lng, lat].");const n=new URL(`geocoding/${t[0]},${t[1]}.json`,d.maptilerApiURL);V(n.searchParams,e);const i=n.toString(),a=await v(i);if(!a.ok)throw new f(a,D[a.status]??"");return await a.json()}async function ot(t,e={}){const n=new URL(`geocoding/${t}.json`,d.maptilerApiURL);n.searchParams.set("key",e.apiKey??u.apiKey),H(n.searchParams,e);const i=n.toString(),a=await v(i);if(!a.ok)throw new f(a,D[a.status]??"");return await a.json()}async function st(t,e={}){if(!t.length)return[];const n=t.map(c=>encodeURIComponent(c)).join(";"),i=new URL(`geocoding/${n}.json`,d.maptilerApiURL),{searchParams:a}=i;G(a,e);const r=i.toString(),o=await v(r);if(!o.ok)throw new f(o,D[o.status]??"");const s=await o.json();return t.length===1?[s]:s}const ct={forward:at,reverse:rt,byId:ot,batch:st,language:L},F={403:"Key is missing, invalid or restricted"};async function lt(t={}){const e=new URL("geolocation/ip.json",d.maptilerApiURL);e.searchParams.set("key",t.apiKey??u.apiKey);const n=e.toString(),i=await v(n);if(!i.ok)throw new f(i,i.status in F?F[i.status]:"");return await i.json()}const pt={info:lt},E={403:"Key is missing, invalid or restricted"};async function mt(t,e={}){if(typeof t!="string"||t.trim().length===0)throw new Error("The query must be a non-empty string");const n=new URL(`coordinates/search/${t}.json`,d.maptilerApiURL);n.searchParams.set("key",e.apiKey??u.apiKey),"limit"in e&&n.searchParams.set("limit",e.limit.toString()),"transformations"in e&&n.searchParams.set("transformations",e.transformations.toString()),"exports"in e&&n.searchParams.set("exports",e.exports.toString());const i=n.toString(),a=await v(i);if(!a.ok)throw new f(a,a.status in E?E[a.status]:"");return await a.json()}async function ut(t,e={}){const n=(Array.isArray(t[0])?t:[t]).map(o=>`${o[0]},${o[1]}`).join(";"),i=new URL(`coordinates/transform/${n}.json`,d.maptilerApiURL);i.searchParams.set("key",e.apiKey??u.apiKey),"sourceCrs"in e&&i.searchParams.set("s_srs",e.sourceCrs.toString()),"targetCrs"in e&&i.searchParams.set("t_srs",e.targetCrs.toString()),"operations"in e&&i.searchParams.set("ops",(Array.isArray(e.operations)?e.operations:[e.operations]).join("|"));const a=i.toString(),r=await v(a);if(!r.ok)throw new f(r,r.status in E?E[r.status]:"");return await r.json()}const dt={search:mt,transform:ut},z={403:"Key is missing, invalid or restricted"};async function ht(t,e={}){if(typeof t!="string"||t.trim().length===0)throw new Error("The data ID must be a non-empty string");const n=new URL(`data/${encodeURIComponent(t)}/features.json`,d.maptilerApiURL);n.searchParams.set("key",e.apiKey??u.apiKey);const i=n.toString(),a=await v(i);if(!a.ok)throw new f(a,a.status in z?z[a.status]:"");return await a.json()}const ft={get:ht};function B(t){const e=/^maptiler:\/\/(.*)/;let n;const i=t.trim();let a;return i.startsWith("http://")||i.startsWith("https://")?a=i:(n=e.exec(i))!==null?a=`https://api.maptiler.com/maps/${n[1]}/style.json`:a=`https://api.maptiler.com/maps/${i}/style.json`,a}class P{constructor(e,n,i,a,r,o){this.name=e,this.variantType=n,this.id=i,this.referenceStyle=a,this.description=r,this.imageURL=o}getName(){return this.name}getFullName(){return`${this.referenceStyle.getName()} ${this.name}`}getType(){return this.variantType}getId(){return this.id}getDescription(){return this.description}getReferenceStyle(){return this.referenceStyle}hasVariant(e){return this.referenceStyle.hasVariant(e)}getVariant(e){return this.referenceStyle.getVariant(e)}getVariants(){return this.referenceStyle.getVariants().filter(e=>e!==this)}getImageURL(){return this.imageURL}getExpandedStyleURL(){return B(this.getId())}}class N{constructor(e,n){this.name=e,this.id=n,this.variants={},this.orderedVariants=[]}getName(){return this.name}getId(){return this.id}addVariant(e){this.variants[e.getType()]=e,this.orderedVariants.push(e)}hasVariant(e){return e in this.variants}getVariant(e){return e in this.variants?this.variants[e]:this.orderedVariants[0]}getVariants(){return Object.values(this.variants)}getDefaultVariant(){return this.orderedVariants[0]}}const $=[{referenceStyleID:"STREETS",name:"Streets",description:"",variants:[{id:"streets-v2",name:"Default",variantType:"DEFAULT",description:"",imageURL:""},{id:"streets-v2-dark",name:"Dark",variantType:"DARK",description:"",imageURL:""},{id:"streets-v2-light",name:"Light",variantType:"LIGHT",description:"",imageURL:""},{id:"streets-v2-night",name:"Night",variantType:"NIGHT",description:"",imageURL:""},{id:"streets-v2-pastel",name:"Pastel",variantType:"PASTEL",description:"",imageURL:""}]},{referenceStyleID:"OUTDOOR",name:"Outdoor",description:"",variants:[{id:"outdoor-v2",name:"Default",variantType:"DEFAULT",description:"",imageURL:""},{id:"outdoor-v2-dark",name:"Dark",variantType:"DARK",description:"",imageURL:""}]},{referenceStyleID:"WINTER",name:"Winter",description:"",variants:[{id:"winter-v2",name:"Default",variantType:"DEFAULT",description:"",imageURL:""},{id:"winter-v2-dark",name:"Dark",variantType:"DARK",description:"",imageURL:""}]},{referenceStyleID:"SATELLITE",name:"Satellite",description:"",variants:[{id:"satellite",name:"Default",variantType:"DEFAULT",description:"",imageURL:""}]},{referenceStyleID:"HYBRID",name:"Hybrid",description:"",variants:[{id:"hybrid",name:"Default",variantType:"DEFAULT",description:"",imageURL:""}]},{referenceStyleID:"BASIC",name:"Basic",description:"",variants:[{id:"basic-v2",name:"Default",variantType:"DEFAULT",description:"",imageURL:""},{id:"basic-v2-dark",name:"Dark",variantType:"DARK",description:"",imageURL:""},{id:"basic-v2-light",name:"Light",variantType:"LIGHT",description:"",imageURL:""}]},{referenceStyleID:"BRIGHT",name:"Bright",description:"",variants:[{id:"bright-v2",name:"Default",variantType:"DEFAULT",description:"",imageURL:""},{id:"bright-v2-dark",name:"Dark",variantType:"DARK",description:"",imageURL:""},{id:"bright-v2-light",name:"Light",variantType:"LIGHT",description:"",imageURL:""},{id:"bright-v2-pastel",name:"Pastel",variantType:"PASTEL",description:"",imageURL:""}]},{referenceStyleID:"OPENSTREETMAP",name:"OpenStreetMap",description:"",variants:[{id:"openstreetmap",name:"Default",variantType:"DEFAULT",description:"",imageURL:""}]},{referenceStyleID:"TOPO",name:"Topo",description:"",variants:[{id:"topo-v2",name:"Default",variantType:"DEFAULT",description:"",imageURL:""},{id:"topo-v2-dark",name:"Dark",variantType:"DARK",description:"",imageURL:""},{id:"topo-v2-shiny",name:"Shiny",variantType:"SHINY",description:"",imageURL:""},{id:"topo-v2-pastel",name:"Pastel",variantType:"PASTEL",description:"",imageURL:""},{id:"topo-v2-topographique",name:"Topographique",variantType:"TOPOGRAPHIQUE",description:"",imageURL:""}]},{referenceStyleID:"VOYAGER",name:"Voyager",description:"",variants:[{id:"voyager-v2",name:"Default",variantType:"DEFAULT",description:"",imageURL:""},{id:"voyager-v2-darkmatter",name:"Darkmatter",variantType:"DARK",description:"",imageURL:""},{id:"voyager-v2-positron",name:"Positron",variantType:"LIGHT",description:"",imageURL:""},{id:"voyager-v2-vintage",name:"Vintage",variantType:"VINTAGE",description:"",imageURL:""}]},{referenceStyleID:"TONER",name:"Toner",description:"",variants:[{id:"toner-v2",name:"Default",variantType:"DEFAULT",description:"",imageURL:""},{id:"toner-v2-background",name:"Background",variantType:"BACKGROUND",description:"",imageURL:""},{id:"toner-v2-lite",name:"Lite",variantType:"LITE",description:"",imageURL:""},{id:"toner-v2-lines",name:"Lines",variantType:"LINES",description:"",imageURL:""}]},{referenceStyleID:"DATAVIZ",name:"Dataviz",description:"",variants:[{id:"dataviz",name:"Default",variantType:"DEFAULT",description:"",imageURL:""},{id:"dataviz-dark",name:"Dark",variantType:"DARK",description:"",imageURL:""},{id:"dataviz-light",name:"Light",variantType:"LIGHT",description:"",imageURL:""}]},{referenceStyleID:"BACKDROP",name:"Backdrop",description:"",variants:[{id:"backdrop",name:"Default",variantType:"DEFAULT",description:"",imageURL:""},{id:"backdrop-dark",name:"Dark",variantType:"DARK",description:"",imageURL:""},{id:"backdrop-light",name:"Light",variantType:"LIGHT",description:"",imageURL:""}]},{referenceStyleID:"OCEAN",name:"Ocean",description:"",variants:[{id:"ocean",name:"Default",variantType:"DEFAULT",description:"",imageURL:""}]}];function gt(t){return new Proxy(t,{get(e,n,i){return e.hasVariant(n)?e.getVariant(n):n.toString().toUpperCase()===n?t.getDefaultVariant():Reflect.get(e,n,i)}})}function yt(){const t={};for(let e=0;e<$.length;e+=1){const n=$[e],i=gt(new N(n.name,n.referenceStyleID));for(let a=0;a<n.variants.length;a+=1){const r=n.variants[a],o=new P(r.name,r.variantType,r.id,i,r.description,r.imageURL);i.addVariant(o)}t[n.referenceStyleID]=i}return t}function b(t){if(!t)return W[$[0].referenceStyleID].getDefaultVariant().getId();if(typeof t=="string"||t instanceof String)return t.trim().toLowerCase();if(t instanceof P)return t.getId();if(t instanceof N)return t.getDefaultVariant().getId()}const W=yt();function vt(t,e,n){let i=e[0],a=e[1],r=n[0]-i,o=n[1]-a;if(r!==0||o!==0){const s=((t[0]-i)*r+(t[1]-a)*o)/(r*r+o*o);s>1?(i=n[0],a=n[1]):s>0&&(i+=r*s,a+=o*s)}return r=t[0]-i,o=t[1]-a,r*r+o*o}function K(t,e,n,i,a){let r=i,o;for(let s=e+1;s<n;s++){const c=vt(t[s],t[e],t[n]);c>r&&(o=s,r=c)}r>i&&(o-e>1&&K(t,e,o,i,a),a.push(t[o]),n-o>1&&K(t,o,n,i,a))}function At(t,e){const n=t.length-1,i=[t[0]];return K(t,0,n,e,i),i.push(t[n]),i}function Rt(t,e){if(t.length<=2)return t;const n=e!==void 0?e*e:1;return At(t,n)}function C(t,e=!0){let n=`${t[0]},${t[1]}`;return t.length===3&&e&&(n+=`,${t[2]}`),n}function M(t,e=3e3){let n=t.map(r=>r.join(",")).join("|"),i=5e-6;const a=1e-5;for(;n.length>e;)n=Rt(t,i).map(r=>`${r[0]},${r[1]}`).join("|"),i+=a;return n}function Lt(t,e,n={}){const i=b(n.style),a=n.hiDPI?"@2x":"",r=n.format??"png";let o=~~(n.width??1024),s=~~(n.height??1024);n.hiDPI&&(o=~~(o/2),s=~~(s/2));const c=new URL(`maps/${encodeURIComponent(i)}/static/${t[0]},${t[1]},${e}/${o}x${s}${a}.${r}`,d.maptilerApiURL);if("attribution"in n&&c.searchParams.set("attribution",n.attribution.toString()),"markers"in n){let l="";const m="markerIcon"in n;m&&(l+=`icon:${n.markerIcon}|`),m&&"markerAnchor"in n&&(l+=`anchor:${n.markerAnchor}|`),m&&n.hiDPI&&(l+="scale:2|");const h=Array.isArray(n.markers[0])?n.markers:[n.markers];l+=h.map(y=>C(y,!m)).join("|"),c.searchParams.set("markers",l)}if("path"in n){let l="";if(l+=`fill:${n.pathFillColor??"none"}|`,"pathStrokeColor"in n&&(l+=`stroke:${n.pathStrokeColor}|`),"pathWidth"in n){const m=n.pathWidth/(n.hiDPI?2:1);l+=`width:${m.toString()}|`}l+=M(n.path),c.searchParams.set("path",l)}return c.searchParams.set("key",n.apiKey??u.apiKey),c.toString()}function It(t,e={}){const n=b(e.style),i=e.hiDPI?"@2x":"",a=e.format??"png";let r=~~(e.width??1024),o=~~(e.height??1024);e.hiDPI&&(r=~~(r/2),o=~~(o/2));const s=new URL(`maps/${encodeURIComponent(n)}/static/${t[0]},${t[1]},${t[2]},${t[3]}/${r}x${o}${i}.${a}`,d.maptilerApiURL);if("attribution"in e&&s.searchParams.set("attribution",e.attribution.toString()),"padding"in e&&s.searchParams.set("padding",e.padding.toString()),"markers"in e){let c="";const l="markerIcon"in e;l&&(c+=`icon:${e.markerIcon}|`),l&&"markerAnchor"in e&&(c+=`anchor:${e.markerAnchor}|`),l&&e.hiDPI&&(c+="scale:2|");const m=Array.isArray(e.markers[0])?e.markers:[e.markers];c+=m.map(h=>C(h,!l)).join("|"),s.searchParams.set("markers",c)}if("path"in e){let c="";if(c+=`fill:${e.pathFillColor??"none"}|`,"pathStrokeColor"in e&&(c+=`stroke:${e.pathStrokeColor}|`),"pathWidth"in e){const l=e.pathWidth/(e.hiDPI?2:1);c+=`width:${l.toString()}|`}c+=M(e.path),s.searchParams.set("path",c)}return s.searchParams.set("key",e.apiKey??u.apiKey),s.toString()}function St(t={}){if(!("markers"in t)&&!("path"in t))throw new Error("Automatic static maps require markers and/or path to be created.");const e=b(t.style),n=t.hiDPI?"@2x":"",i=t.format??"png";let a=~~(t.width??1024),r=~~(t.height??1024);t.hiDPI&&(a=~~(a/2),r=~~(r/2));const o=new URL(`maps/${encodeURIComponent(e)}/static/auto/${a}x${r}${n}.${i}`,d.maptilerApiURL);if("attribution"in t&&o.searchParams.set("attribution",t.attribution.toString()),"padding"in t&&o.searchParams.set("padding",t.padding.toString()),"markers"in t){let s="";const c="markerIcon"in t;c&&(s+=`icon:${t.markerIcon}|`),c&&"markerAnchor"in t&&(s+=`anchor:${t.markerAnchor}|`),c&&t.hiDPI&&(s+="scale:2|");const l=Array.isArray(t.markers[0])?t.markers:[t.markers];s+=l.map(m=>C(m,!c)).join("|"),o.searchParams.set("markers",s)}if("path"in t){let s="";if(s+=`fill:${t.pathFillColor??"none"}|`,"pathStrokeColor"in t&&(s+=`stroke:${t.pathStrokeColor}|`),"pathWidth"in t){const c=t.pathWidth/(t.hiDPI?2:1);s+=`width:${c.toString()}|`}s+=M(t.path),o.searchParams.set("path",s)}return o.searchParams.set("key",t.apiKey??u.apiKey),o.toString()}const Tt={centered:Lt,bounded:It,automatic:St};function Ut(t){return t*Math.PI/180}function _(t){return t%1!==0}var I={};function Dt(t,e){if(t<0||t>30)throw Error("Invalid zoom level");return _(t)?x(t,e):(I[e]===void 0&&(I[e]={}),Array.isArray(I[e][t])||(I[e][t]=x(t,e)),I[e][t])}function x(t,e){let n=e*Math.pow(2,t);return[n/360,n/(2*Math.PI),n/2,n]}function q(t,e,n=!1,i=512){let{min:a,max:r,sin:o,log:s,round:c}=Math,[l,m,h,y]=Dt(e,i),S=n?2:1,tt=h,et=a(r(o(Ut(t[1])),-.9999),.9999),T=tt+t[0]*l,U=tt+.5*s((1+et)/(1-et))*-m;return _(e)||(T=c(T),U=c(U)),T>y*S&&(T=y*S),U>y&&(U=y),[T,U]}function Et(t,e=512){let{floor:n}=Math,i=n(t[0]/e),a=n(t[1]/e);return[i,a]}function $t(t,e,n=512){let i=q(t,e,!1,n);return Et(i,n)}function kt(t,e,n=512){let[i,a,r]=e,o=q(t,i,!1,n),s=a*n,c=r*n;return[(o[0]-s)/n,(o[1]-c)/n]}const k=63710088e-1;function g(t){return t*3.28084}function A(t){return t%360*Math.PI/180}function wt(t){return t*180/Math.PI}function Z(t,e,n=512){return Math.cos(t*Math.PI/180)*2*Math.PI*6378137/(n*2**e)*3}function Y(t,e,n){return((1<<n)*e+t)*32+n}function Pt(t){const e="geometry"in t?t.geometry:t;return e.type==="MultiPolygon"?J(e.coordinates):O(e.coordinates)}function J(t){const e="coordinates"in t?t.coordinates:t;let n=0;for(const i of e)n+=O(i);return n}function O(t){const e="coordinates"in t?t.coordinates:t;let n=0;for(const i of e)n+=Nt(i);return n}function Nt(t){let e,n,i,a,r,o,s,c=0;const l=t.length;if(l>2){for(s=0;s<l;s++)s===l-2?(a=l-2,r=l-1,o=0):s===l-1?(a=l-1,r=0,o=1):(a=s,r=s+1,o=s+2),e=t[a],n=t[r],i=t[o],c+=(A(i[0])-A(e[0]))*Math.sin(A(n[1]));c=c*k*k/2}return Math.abs(c)}function bt(t){const e="geometry"in t?t.geometry.coordinates:"coordinates"in t?t.coordinates:t;let n=0,i;for(const a of e)i!==void 0&&(n+=w(i,a)),i=a;return n}function w(t,e){const{pow:n,sin:i,cos:a,sqrt:r,atan2:o}=Math,s=A(e[1]-t[1]),c=A(e[0]-t[0]),l=A(t[1]),m=A(e[1]),h=n(i(s/2),2)+n(i(c/2),2)*a(l)*a(m);return 2*o(r(h),r(1-h))*k}function Kt(t,e,n){const i=new Map,a=[],r=[],o=Z(t[0][1],e,n),s=Ct(t,o);for(const c of s){const l=c,[m,h]=$t(l,e,n),y=Y(m,h,e),S={id:y,x:m,y:h,z:e};i.set(y,S),r.push({coordinate:l,tile:S})}for(const c of i.values())a.push(c);return{coords:r,tiles:a}}function Ct(t,e){const n=[];let i;for(const a of t){if(i!==void 0){const r=w(i,a),o=Math.ceil(r/e);for(let s=0;s<=o-1;s++){const c=[i[0]+(a[0]-i[0])*(s/o),i[1]+(a[1]-i[1])*(s/o)];n.push(c)}}else n.push(a);i=a}return n}function Mt(t,e,n,i,a=X){const{channels:r,image:o}=i;let[s,c]=kt(t,e,n);s=Q(s,n),c=Q(c,n);const l=(c*n+s)*r;return a(o[l],o[l+1],o[l+2],r===4?o[l+3]:0)}function Q(t,e){return Math.max(0,Math.min(e,Math.floor(t*e)))}function X(t,e,n){return-1e4+(t*256*256+e*256+n)*.1}async function Ot(t,e){const n="geometry"in t?t.geometry.coordinates:t.coordinates,{coords:i,tiles:a}=Kt(n,e.zoom??13,e.tileSize??512),r=await jt(a,e.tileRequest);let o=Ht(i,r,e.tileSize??512,e.elevationParser);e.smooth===!0&&(o=Gt(o));let s=Vt(o);return e.metric==="ft"&&(s=Ft(s)),s}async function jt(t,e){const n=new Map,i=[];for(const a of t)i.push(e(a.x,a.y,a.z).then(r=>(n.set(a.id,r),r)).catch(r=>{console.error(r)}));return await Promise.allSettled(i),n}function Ht(t,e,n,i){const a=[];let r=0,o;for(const{tile:s,coordinate:c}of t){const l=e.get(s.id);if(l===void 0)throw new Error(`Missing tile ${s.id} (${s.x}-${s.y}-${s.z})`);const m=Mt(c,[s.z,s.x,s.y],n,l,i);a.push({distance:r,elevation:m,coordinate:c,tile:s}),o!==void 0&&(r+=w(o,c)),o=c}return a}function Vt(t){let e=1/0,n=-1/0,i=0;for(const a of t)a.elevation<e&&(e=a.elevation),a.elevation>n&&(n=a.elevation),i+=a.elevation;return{distance:t[t.length-1].distance,minElevation:e,maxElevation:n,avgElevation:i/t.length,startElevation:t[0].elevation,endElevation:t[t.length-1].elevation,points:t}}function Gt(t){const e=[];let n;for(let i=0;i<t.length;i++){const a=t[i],r=t[i+1]??t[i];if(n===void 0)e.push(a);else{const o={distance:a.distance,elevation:(n.elevation+a.elevation+r.elevation)/3,coordinate:a.coordinate,tile:a.tile};e.push(o)}n=a}return e}function Ft(t){return{distance:g(t.distance),minElevation:g(t.minElevation),maxElevation:g(t.maxElevation),avgElevation:g(t.avgElevation),startElevation:g(t.startElevation),endElevation:g(t.endElevation),points:t.points.map(({distance:e,elevation:n,coordinate:i,tile:a})=>({distance:g(e),elevation:g(n),coordinate:i,tile:a}))}}p.ClientConfig=j,p.LanguageGeocoding=L,p.MapStyle=W,p.MapStyleVariant=P,p.ReferenceMapStyle=N,p.ServiceError=f,p.area=Pt,p.config=u,p.coordinates=dt,p.data=ft,p.defaultElevationParser=X,p.degToRad=A,p.earthRadius=k,p.expandMapStyle=B,p.geocoding=ct,p.geolocation=pt,p.getZoomLevelResolution=Z,p.lineDistance=bt,p.mToFt=g,p.mapStylePresetList=$,p.multiPolygonArea=J,p.pointDistance=w,p.polygonArea=O,p.profileLineString=Ot,p.radToDeg=wt,p.staticMaps=Tt,p.xyzToTileID=Y});
|
package/examples/test-node.js
CHANGED
|
@@ -9,16 +9,16 @@ import {
|
|
|
9
9
|
|
|
10
10
|
// For this examople to work, you must bring your own node-compatible fetch,
|
|
11
11
|
// unles you are using a version of Nodejs that already contains fetch (>=18)
|
|
12
|
-
import fetch from 'node-fetch';
|
|
12
|
+
// import fetch from 'node-fetch';
|
|
13
13
|
|
|
14
|
-
config.fetch = fetch;
|
|
15
|
-
config.apiKey = '
|
|
14
|
+
// config.fetch = fetch;
|
|
15
|
+
config.apiKey = 'YOUR_MAPTILER_CLOUD_API_KEY';
|
|
16
16
|
|
|
17
17
|
async function testGeocoding() {
|
|
18
|
-
const result1 = await geocoding.forward('bordeaux', {language: [LanguageGeocoding.AUTO, LanguageGeocoding.ENGLISH]});
|
|
19
|
-
console.log(result1);
|
|
18
|
+
// const result1 = await geocoding.forward('bordeaux', {language: [LanguageGeocoding.AUTO, LanguageGeocoding.ENGLISH]});
|
|
19
|
+
// console.log(result1);
|
|
20
20
|
|
|
21
|
-
const result2 = await geocoding.reverse(
|
|
21
|
+
const result2 = await geocoding.reverse([6.249638, 46.402056], {language: ['es', 'en']});
|
|
22
22
|
console.log(result2);
|
|
23
23
|
}
|
|
24
24
|
|
|
@@ -46,7 +46,7 @@ async function testData() {
|
|
|
46
46
|
|
|
47
47
|
(async () => {
|
|
48
48
|
await testGeocoding();
|
|
49
|
-
await testGeolocation();
|
|
50
|
-
await testCoordinates();
|
|
51
|
-
await testData();
|
|
49
|
+
// await testGeolocation();
|
|
50
|
+
// await testCoordinates();
|
|
51
|
+
// await testData();
|
|
52
52
|
})()
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@maptiler/client",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.7.0",
|
|
4
4
|
"description": "Javascript & Typescript wrapper to MapTiler Cloud API",
|
|
5
5
|
"module": "dist/maptiler-client.mjs",
|
|
6
6
|
"types": "dist/maptiler-client.d.ts",
|
|
@@ -9,7 +9,8 @@
|
|
|
9
9
|
"homepage": "https://github.com/maptiler/maptiler-client-js",
|
|
10
10
|
"exports": {
|
|
11
11
|
"import": "./dist/maptiler-client.mjs",
|
|
12
|
-
"require": "./dist/maptiler-client.cjs"
|
|
12
|
+
"require": "./dist/maptiler-client.cjs",
|
|
13
|
+
"types": "./dist/maptiler-client.d.ts"
|
|
13
14
|
},
|
|
14
15
|
"publishConfig": {
|
|
15
16
|
"access": "public",
|
|
@@ -39,8 +40,10 @@
|
|
|
39
40
|
"docmd": "rm -rf docsmd/*; typedoc --readme none --plugin typedoc-plugin-markdown --out docsmd src/index.ts",
|
|
40
41
|
"dochtml": "rm -rf docs/*; typedoc; cp -r images docs/",
|
|
41
42
|
"doc": "npm run docmd; npm run dochtml",
|
|
42
|
-
"prepare": "npm run format; npm run lint; npm run
|
|
43
|
-
"test": "
|
|
43
|
+
"prepare": "npm run format; npm run lint; npm run test; npm run build",
|
|
44
|
+
"test:prod": "vitest test --run",
|
|
45
|
+
"test:dev": "vitest test --watch",
|
|
46
|
+
"test": ""
|
|
44
47
|
},
|
|
45
48
|
"repository": {
|
|
46
49
|
"type": "git",
|
|
@@ -48,25 +51,29 @@
|
|
|
48
51
|
},
|
|
49
52
|
"license": "BSD-3-Clause",
|
|
50
53
|
"devDependencies": {
|
|
51
|
-
"@rollup/plugin-commonjs": "^
|
|
52
|
-
"@rollup/plugin-json": "^
|
|
53
|
-
"@rollup/plugin-node-resolve": "^
|
|
54
|
-
"@typescript-eslint/eslint-plugin": "^
|
|
55
|
-
"@typescript-eslint/parser": "^
|
|
56
|
-
"eslint": "^8.
|
|
57
|
-
"prettier": "^
|
|
58
|
-
"rollup": "^
|
|
59
|
-
"rollup-plugin-dts": "^
|
|
60
|
-
"rollup-plugin-esbuild": "^
|
|
54
|
+
"@rollup/plugin-commonjs": "^25.0.7",
|
|
55
|
+
"@rollup/plugin-json": "^6.0.1",
|
|
56
|
+
"@rollup/plugin-node-resolve": "^15.2.3",
|
|
57
|
+
"@typescript-eslint/eslint-plugin": "^6.9.0",
|
|
58
|
+
"@typescript-eslint/parser": "^6.9.0",
|
|
59
|
+
"eslint": "^8.52.0",
|
|
60
|
+
"prettier": "^3.0.3",
|
|
61
|
+
"rollup": "^4.1.4",
|
|
62
|
+
"rollup-plugin-dts": "^6.1.0",
|
|
63
|
+
"rollup-plugin-esbuild": "^6.1.0",
|
|
61
64
|
"rollup-plugin-node-globals": "^1.4.0",
|
|
62
65
|
"rollup-plugin-string": "^3.0.0",
|
|
63
66
|
"rollup-plugin-swc": "^0.2.1",
|
|
64
67
|
"serve": "^14.1.1",
|
|
65
|
-
"
|
|
66
|
-
"typedoc
|
|
67
|
-
"
|
|
68
|
+
"sharp": "^0.32.6",
|
|
69
|
+
"typedoc": "^0.25.2",
|
|
70
|
+
"typedoc-plugin-markdown": "^3.16.0",
|
|
71
|
+
"typescript": "^5.2.2",
|
|
72
|
+
"vitest": "^0.34.6"
|
|
68
73
|
},
|
|
69
74
|
"dependencies": {
|
|
70
|
-
"@
|
|
75
|
+
"@rollup/pluginutils": "^5.0.5",
|
|
76
|
+
"@types/geojson": "^7946.0.10",
|
|
77
|
+
"web-merc-projection": "^1.3.2"
|
|
71
78
|
}
|
|
72
79
|
}
|
package/readme.md
CHANGED
|
@@ -43,7 +43,7 @@ npm install --save @maptiler/client
|
|
|
43
43
|
```
|
|
44
44
|
|
|
45
45
|
# API documentation
|
|
46
|
-
In addition to the details and examples provided in this readme, check out the [complete API documentation](https://maptiler.
|
|
46
|
+
In addition to the details and examples provided in this readme, check out the [complete API documentation](https://labs.maptiler.com/maptiler-client-js).
|
|
47
47
|
|
|
48
48
|
# Quick start
|
|
49
49
|
```ts
|
package/rollup.config.js
CHANGED
|
@@ -25,7 +25,7 @@ const bundles = [
|
|
|
25
25
|
watch: {
|
|
26
26
|
include: "src/**"
|
|
27
27
|
},
|
|
28
|
-
external: []
|
|
28
|
+
external: ["web-merc-projection"]
|
|
29
29
|
},
|
|
30
30
|
|
|
31
31
|
// CJS module, not minified + sourcemap
|
|
@@ -48,7 +48,7 @@ const bundles = [
|
|
|
48
48
|
watch: {
|
|
49
49
|
include: "src/**"
|
|
50
50
|
},
|
|
51
|
-
external: []
|
|
51
|
+
external: ["web-merc-projection"]
|
|
52
52
|
},
|
|
53
53
|
|
|
54
54
|
// UMD module, not minified
|
|
@@ -106,7 +106,7 @@ if (process.env.NODE_ENV === "production") {
|
|
|
106
106
|
}
|
|
107
107
|
],
|
|
108
108
|
input: "src/index.ts",
|
|
109
|
-
external: [],
|
|
109
|
+
external: ["web-merc-projection"],
|
|
110
110
|
},
|
|
111
111
|
{
|
|
112
112
|
plugins: [
|
package/src/callFetch.ts
CHANGED
|
@@ -3,14 +3,14 @@ import { config } from "./config";
|
|
|
3
3
|
export async function callFetch(resource, options = {}) {
|
|
4
4
|
if (config.fetch === null) {
|
|
5
5
|
throw new Error(
|
|
6
|
-
"The fetch function was not found. If on NodeJS < 18 please specify the fetch function with config.fetch"
|
|
6
|
+
"The fetch function was not found. If on NodeJS < 18 please specify the fetch function with config.fetch",
|
|
7
7
|
);
|
|
8
8
|
}
|
|
9
9
|
|
|
10
10
|
// Control if URL contains the api key
|
|
11
11
|
if (new URL(resource).searchParams.get("key").trim() === "") {
|
|
12
12
|
throw new Error(
|
|
13
|
-
"The MapTiler Cloud API key is missing. Set it in `config.apiKey` or get one for free at https://maptiler.com"
|
|
13
|
+
"The MapTiler Cloud API key is missing. Set it in `config.apiKey` or get one for free at https://maptiler.com",
|
|
14
14
|
);
|
|
15
15
|
}
|
|
16
16
|
|
package/src/config.ts
CHANGED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { llToTilePx } from "web-merc-projection";
|
|
2
|
+
|
|
3
|
+
import type { TileImage } from "./";
|
|
4
|
+
|
|
5
|
+
export type ElevationParser = (
|
|
6
|
+
r: number,
|
|
7
|
+
g: number,
|
|
8
|
+
b: number,
|
|
9
|
+
a: number,
|
|
10
|
+
) => number;
|
|
11
|
+
|
|
12
|
+
/** Given an RGB or RBGA image and lon-lat coordinate, determine the elevation */
|
|
13
|
+
export default function getElevation(
|
|
14
|
+
coord: [lon: number, lat: number],
|
|
15
|
+
tile: [zoom: number, x: number, y: number],
|
|
16
|
+
tileSize: number,
|
|
17
|
+
tileImage: TileImage,
|
|
18
|
+
elevationParser: ElevationParser = defaultElevationParser,
|
|
19
|
+
): number {
|
|
20
|
+
const { channels, image } = tileImage;
|
|
21
|
+
let [x, y] = llToTilePx(coord, tile, tileSize);
|
|
22
|
+
x = clampPixel(x, tileSize);
|
|
23
|
+
y = clampPixel(y, tileSize);
|
|
24
|
+
const index = (y * tileSize + x) * channels;
|
|
25
|
+
|
|
26
|
+
return elevationParser(
|
|
27
|
+
image[index],
|
|
28
|
+
image[index + 1],
|
|
29
|
+
image[index + 2],
|
|
30
|
+
channels === 4 ? image[index + 3] : 0,
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Clamp the pixels to the 0-tileSize bounds */
|
|
35
|
+
function clampPixel(n: number, tileSize: number): number {
|
|
36
|
+
return Math.max(0, Math.min(tileSize, Math.floor(n * tileSize)));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Default elevation parser used by Mapbox and Maplibre. Result is in meters */
|
|
40
|
+
export function defaultElevationParser(
|
|
41
|
+
r: number,
|
|
42
|
+
g: number,
|
|
43
|
+
b: number,
|
|
44
|
+
): number {
|
|
45
|
+
return -10000 + (r * 256 * 256 + g * 256 + b) * 0.1;
|
|
46
|
+
}
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
import tileCover from "./tileCover";
|
|
2
|
+
import getElevation from "./getElevation";
|
|
3
|
+
import { pointDistance, mToFt } from "../geometry";
|
|
4
|
+
|
|
5
|
+
import type { TileCoverCoordinates, TileID } from "./tileCover";
|
|
6
|
+
import type { ElevationParser } from "./getElevation";
|
|
7
|
+
import type { Feature, LineString } from "geojson";
|
|
8
|
+
|
|
9
|
+
export * from "./getElevation";
|
|
10
|
+
export * from "./tileCover";
|
|
11
|
+
|
|
12
|
+
export interface TileImage {
|
|
13
|
+
channels: 1 | 2 | 3 | 4;
|
|
14
|
+
image: Uint8ClampedArray;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export type TileRequest = (
|
|
18
|
+
x: number,
|
|
19
|
+
y: number,
|
|
20
|
+
zoom: number,
|
|
21
|
+
) => Promise<TileImage>;
|
|
22
|
+
|
|
23
|
+
export interface Options {
|
|
24
|
+
/** type of metric to use. Meters or feet. Default: meters */
|
|
25
|
+
metric?: "m" | "ft";
|
|
26
|
+
/** Zoom that is queried from the server. Default: 13 */
|
|
27
|
+
zoom?: number;
|
|
28
|
+
/** Tile size of the images returned. Default 512 */
|
|
29
|
+
tileSize?: number;
|
|
30
|
+
/** Tile Request method */
|
|
31
|
+
tileRequest: TileRequest;
|
|
32
|
+
/** Elevation parser. Default: elevation = -10000 + ((R * 256 * 256 + G * 256 + B) * 0.1) */
|
|
33
|
+
elevationParser?: ElevationParser;
|
|
34
|
+
/** smooth out the elevation to make the visual aesthetic nicer */
|
|
35
|
+
smooth?: boolean;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface ElevPoint {
|
|
39
|
+
/** Distance along path from the starting point in the metric defind by options */
|
|
40
|
+
distance: number;
|
|
41
|
+
/** Elevation of the point */
|
|
42
|
+
elevation: number;
|
|
43
|
+
/** Coordinates of the point in lat-lon */
|
|
44
|
+
coordinate: [lon: number, lat: number];
|
|
45
|
+
/** Tile that the point is in */
|
|
46
|
+
tile: TileID;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface Output {
|
|
50
|
+
/** Total length of the path in the metric defined by options */
|
|
51
|
+
distance: number;
|
|
52
|
+
/** Minimum elevation of the path */
|
|
53
|
+
minElevation: number;
|
|
54
|
+
/** Maximum elevation of the path */
|
|
55
|
+
maxElevation: number;
|
|
56
|
+
/** Average elevation of the path */
|
|
57
|
+
avgElevation: number;
|
|
58
|
+
/** Elevation at the start of the path */
|
|
59
|
+
startElevation: number;
|
|
60
|
+
/** Elevation at the end of the path */
|
|
61
|
+
endElevation: number;
|
|
62
|
+
/** Array of points along the path */
|
|
63
|
+
points: ElevPoint[];
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Given a GeoJSON LineString or Feature<Linestring>, return the elevation data for the path.
|
|
68
|
+
* This algorithm will automatically break the path into denser segments relative to the zoom level if necessary.
|
|
69
|
+
*/
|
|
70
|
+
export async function profileLineString(
|
|
71
|
+
path: Feature<LineString> | LineString,
|
|
72
|
+
options: Options,
|
|
73
|
+
): Promise<Output> {
|
|
74
|
+
// get the tile cover
|
|
75
|
+
const coordinates =
|
|
76
|
+
"geometry" in path ? path.geometry.coordinates : path.coordinates;
|
|
77
|
+
const { coords, tiles } = tileCover(
|
|
78
|
+
coordinates,
|
|
79
|
+
options.zoom ?? 13,
|
|
80
|
+
options.tileSize ?? 512,
|
|
81
|
+
);
|
|
82
|
+
// get tiles
|
|
83
|
+
const tileCache = await getTiles(tiles, options.tileRequest);
|
|
84
|
+
// get the elevation data
|
|
85
|
+
let points = getElevations(
|
|
86
|
+
coords,
|
|
87
|
+
tileCache,
|
|
88
|
+
options.tileSize ?? 512,
|
|
89
|
+
options.elevationParser,
|
|
90
|
+
);
|
|
91
|
+
// smooth the elevation data if needed
|
|
92
|
+
if (options.smooth === true) points = smoothElevation(points);
|
|
93
|
+
// calculate the output
|
|
94
|
+
let output = buildOutput(points);
|
|
95
|
+
// convert to miles if needed
|
|
96
|
+
if (options.metric === "ft") output = toFeet(output);
|
|
97
|
+
|
|
98
|
+
return output;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Request all the tiles we need */
|
|
102
|
+
async function getTiles(
|
|
103
|
+
tiles: TileID[],
|
|
104
|
+
tileRequest: TileRequest,
|
|
105
|
+
): Promise<Map<number, TileImage>> {
|
|
106
|
+
const tileCache = new Map<number, TileImage>();
|
|
107
|
+
|
|
108
|
+
// request all the tiles we need
|
|
109
|
+
const requests: Array<Promise<TileImage | undefined>> = [];
|
|
110
|
+
for (const tile of tiles) {
|
|
111
|
+
requests.push(
|
|
112
|
+
tileRequest(tile.x, tile.y, tile.z)
|
|
113
|
+
.then((res: TileImage): TileImage => {
|
|
114
|
+
tileCache.set(tile.id, res);
|
|
115
|
+
return res;
|
|
116
|
+
})
|
|
117
|
+
.catch((err: unknown) => {
|
|
118
|
+
console.error(err);
|
|
119
|
+
return undefined;
|
|
120
|
+
}),
|
|
121
|
+
);
|
|
122
|
+
}
|
|
123
|
+
// wait for all the requests to finish
|
|
124
|
+
await Promise.allSettled(requests);
|
|
125
|
+
|
|
126
|
+
return tileCache;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Get the elevation data for each coordinate */
|
|
130
|
+
function getElevations(
|
|
131
|
+
coords: TileCoverCoordinates[],
|
|
132
|
+
tileCache: Map<number, TileImage>,
|
|
133
|
+
tileSize: number,
|
|
134
|
+
elevationParser?: ElevationParser,
|
|
135
|
+
): ElevPoint[] {
|
|
136
|
+
const points: ElevPoint[] = [];
|
|
137
|
+
|
|
138
|
+
// get the elevation data for each coordinate
|
|
139
|
+
let curDistance = 0;
|
|
140
|
+
let prevCoord: [lon: number, lat: number] | undefined;
|
|
141
|
+
for (const { tile, coordinate } of coords) {
|
|
142
|
+
const cTile = tileCache.get(tile.id);
|
|
143
|
+
if (cTile === undefined)
|
|
144
|
+
throw new Error(
|
|
145
|
+
`Missing tile ${tile.id} (${tile.x}-${tile.y}-${tile.z})`,
|
|
146
|
+
);
|
|
147
|
+
const elevation = getElevation(
|
|
148
|
+
coordinate,
|
|
149
|
+
[tile.z, tile.x, tile.y],
|
|
150
|
+
tileSize,
|
|
151
|
+
cTile,
|
|
152
|
+
elevationParser,
|
|
153
|
+
);
|
|
154
|
+
points.push({
|
|
155
|
+
distance: curDistance,
|
|
156
|
+
elevation,
|
|
157
|
+
coordinate,
|
|
158
|
+
tile,
|
|
159
|
+
});
|
|
160
|
+
// calculate the distance between the points
|
|
161
|
+
if (prevCoord !== undefined) {
|
|
162
|
+
curDistance += pointDistance(prevCoord, coordinate);
|
|
163
|
+
}
|
|
164
|
+
prevCoord = coordinate;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
return points;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Improve the output to include metrics about the max/min/avg elevation */
|
|
171
|
+
function buildOutput(points: ElevPoint[]): Output {
|
|
172
|
+
// setup variables
|
|
173
|
+
let minElevation = Infinity;
|
|
174
|
+
let maxElevation = -Infinity;
|
|
175
|
+
let totalElevation = 0;
|
|
176
|
+
// calcuate min, max, and average
|
|
177
|
+
for (const point of points) {
|
|
178
|
+
if (point.elevation < minElevation) minElevation = point.elevation;
|
|
179
|
+
if (point.elevation > maxElevation) maxElevation = point.elevation;
|
|
180
|
+
totalElevation += point.elevation;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
return {
|
|
184
|
+
distance: points[points.length - 1].distance,
|
|
185
|
+
minElevation,
|
|
186
|
+
maxElevation,
|
|
187
|
+
avgElevation: totalElevation / points.length,
|
|
188
|
+
startElevation: points[0].elevation,
|
|
189
|
+
endElevation: points[points.length - 1].elevation,
|
|
190
|
+
points,
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Smooth function to make the elevation appear more aesthetically
|
|
196
|
+
* pleaseing without changing the values greatly
|
|
197
|
+
*/
|
|
198
|
+
function smoothElevation(points: ElevPoint[]): ElevPoint[] {
|
|
199
|
+
const newPoints: ElevPoint[] = [];
|
|
200
|
+
let prevPoint: ElevPoint | undefined;
|
|
201
|
+
for (let i = 0; i < points.length; i++) {
|
|
202
|
+
const point = points[i];
|
|
203
|
+
const nextPoint = points[i + 1] ?? points[i];
|
|
204
|
+
if (prevPoint === undefined) {
|
|
205
|
+
newPoints.push(point);
|
|
206
|
+
} else {
|
|
207
|
+
const newPoint: ElevPoint = {
|
|
208
|
+
distance: point.distance,
|
|
209
|
+
elevation:
|
|
210
|
+
(prevPoint.elevation + point.elevation + nextPoint.elevation) / 3,
|
|
211
|
+
coordinate: point.coordinate,
|
|
212
|
+
tile: point.tile,
|
|
213
|
+
};
|
|
214
|
+
newPoints.push(newPoint);
|
|
215
|
+
}
|
|
216
|
+
prevPoint = point;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
return newPoints;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Convert all output properties from km to miles */
|
|
223
|
+
function toFeet(input: Output): Output {
|
|
224
|
+
const output: Output = {
|
|
225
|
+
distance: mToFt(input.distance),
|
|
226
|
+
minElevation: mToFt(input.minElevation),
|
|
227
|
+
maxElevation: mToFt(input.maxElevation),
|
|
228
|
+
avgElevation: mToFt(input.avgElevation),
|
|
229
|
+
startElevation: mToFt(input.startElevation),
|
|
230
|
+
endElevation: mToFt(input.endElevation),
|
|
231
|
+
points: input.points.map(({ distance, elevation, coordinate, tile }) => ({
|
|
232
|
+
distance: mToFt(distance),
|
|
233
|
+
elevation: mToFt(elevation),
|
|
234
|
+
coordinate,
|
|
235
|
+
tile,
|
|
236
|
+
})),
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
return output;
|
|
240
|
+
}
|