diff --git a/README.md b/README.md index 9237816..a724809 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,20 @@ The website can also run out of a local SQLite database which is convenient for local development. The production server runs on PostgreSQL and the web app is primarily designed for that. +### PostGIS Extension for PostgreSQL + +For the "Who's Nearby" feature to work you will need a PostgreSQL +database with the PostGIS geospatial extension installed. Usually +it might be a matter of `dnf install postgis` and activating the +extension on your nonshy database as your superuser (postgres): + +```psql +create extension postgis; +``` + +If you get errors like "Type geography not found" from Postgres when +running distance based searches, this is the likely culprit. + ## Building the App This app is written in Go: [go.dev](https://go.dev). You can probably @@ -136,4 +150,4 @@ Suggested crontab: ## License -GPLv3. \ No newline at end of file +GPLv3. diff --git a/pkg/controller/account/dashboard.go b/pkg/controller/account/dashboard.go index 52bd528..e0e1e20 100644 --- a/pkg/controller/account/dashboard.go +++ b/pkg/controller/account/dashboard.go @@ -4,6 +4,7 @@ import ( "net/http" "code.nonshy.com/nonshy/website/pkg/config" + "code.nonshy.com/nonshy/website/pkg/log" "code.nonshy.com/nonshy/website/pkg/models" "code.nonshy.com/nonshy/website/pkg/session" "code.nonshy.com/nonshy/website/pkg/templates" @@ -75,6 +76,12 @@ func Dashboard() http.HandlerFunc { _, hasPublic = photoTypes[models.PhotoPublic] ) + // Geolocation/Who's Nearby: if the current user uses GeoIP, update + // their coordinates now. + if err := models.RefreshGeoIP(currentUser.ID, r); err != nil { + log.Error("RefreshGeoIP: %s", err) + } + var vars = map[string]interface{}{ "Notifications": notifs, "NotifMap": notifMap, diff --git a/pkg/controller/account/search.go b/pkg/controller/account/search.go index 3529cef..71a57fe 100644 --- a/pkg/controller/account/search.go +++ b/pkg/controller/account/search.go @@ -20,6 +20,7 @@ func Search() http.HandlerFunc { "created_at desc", "username", "lower(name)", + "distance", } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -103,6 +104,10 @@ func Search() http.HandlerFunc { // Photo counts mapped to users "PhotoCountMap": models.MapPhotoCounts(users), + + // Current user's location setting. + "MyLocation": models.GetUserLocation(currentUser.ID), + "DistanceMap": models.MapDistances(currentUser, users), } if err := tmpl.Execute(w, r, vars); err != nil { diff --git a/pkg/controller/account/settings.go b/pkg/controller/account/settings.go index eecd9dc..8f9c11e 100644 --- a/pkg/controller/account/settings.go +++ b/pkg/controller/account/settings.go @@ -4,10 +4,12 @@ import ( "fmt" "net/http" nm "net/mail" + "strconv" "strings" "time" "code.nonshy.com/nonshy/website/pkg/config" + "code.nonshy.com/nonshy/website/pkg/geoip" "code.nonshy.com/nonshy/website/pkg/log" "code.nonshy.com/nonshy/website/pkg/mail" "code.nonshy.com/nonshy/website/pkg/models" @@ -122,6 +124,36 @@ func Settings() http.HandlerFunc { } session.Flash(w, r, "Website preferences updated!") + case "location": + hashtag = "#location" + var ( + source = r.PostFormValue("source") + latStr = r.PostFormValue("latitude") + lonStr = r.PostFormValue("longitude") + ) + + // Get and update the user's location. + location := models.GetUserLocation(user.ID) + location.Source = source + + if lat, err := strconv.ParseFloat(latStr, 64); err == nil { + location.Latitude = lat + } else { + location.Latitude = 0 + } + + if lon, err := strconv.ParseFloat(lonStr, 64); err == nil { + location.Longitude = lon + } else { + location.Longitude = 0 + } + + // Save it. + if err := location.Save(); err != nil { + session.FlashError(w, r, "Couldn't save your location preference: %s", err) + } else { + session.Flash(w, r, "Location settings updated!") + } case "settings": hashtag = "#account" var ( @@ -210,6 +242,14 @@ func Settings() http.HandlerFunc { return } + // For the Location tab: get GeoIP insights. + insights, err := geoip.GetRequestInsights(r) + if err != nil { + log.Error("GetRequestInsights: %s", err) + } + vars["GeoIPInsights"] = insights + vars["UserLocation"] = models.GetUserLocation(user.ID) + if err := tmpl.Execute(w, r, vars); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return diff --git a/pkg/geoip/geoip.go b/pkg/geoip/geoip.go index 1ef4f9d..4593962 100644 --- a/pkg/geoip/geoip.go +++ b/pkg/geoip/geoip.go @@ -3,6 +3,7 @@ package geoip import ( "errors" + "fmt" "net" "net/http" "strings" @@ -12,6 +13,70 @@ import ( "github.com/oschwald/geoip2-golang" ) +// Insights returns structured GeoIP insights useful for the Location tab of the settings page. +type Insights struct { + CountryCode string + CountryName string + Subdivisions []string + City string + PostalCode string + Latitude float64 + Longitude float64 +} + +// IsZero checks if the insights are unpopulated. +func (i Insights) IsZero() bool { + return i.CountryCode == "" +} + +// String pretty prints the insights for front-end display. +func (i Insights) String() string { + var parts = []string{ + i.CountryName, + strings.Join(i.Subdivisions, ", "), + i.City, + } + if i.PostalCode != "" { + parts = append(parts, "Postal Code "+i.PostalCode) + } + parts = append(parts, fmt.Sprintf("Lat: %f; Long: %f", i.Latitude, i.Longitude)) + return strings.Join(parts, "; ") +} + +// GetRequestInsights returns structured insights based on the current HTTP request. +func GetRequestInsights(r *http.Request) (Insights, error) { + var ( + addr = utility.IPAddress(r) + ip = net.ParseIP(addr) + ) + return GetInsights(ip) +} + +// GetInsights returns structured insights based on an IP address. +func GetInsights(ip net.IP) (Insights, error) { + city, err := GetCity(ip) + if err != nil { + return Insights{}, err + } + + var result = Insights{ + City: city.City.Names["en"], + CountryCode: city.Country.IsoCode, + CountryName: city.Country.Names["en"], + Subdivisions: []string{}, + PostalCode: city.Postal.Code, + Latitude: city.Location.Latitude, + Longitude: city.Location.Longitude, + } + for _, sub := range city.Subdivisions { + if name, ok := sub.Names["en"]; ok { + result.Subdivisions = append(result.Subdivisions, name) + } + } + + return result, nil +} + // GetRequestCity returns the GeoIP City result for the current HTTP request. func GetRequestCity(r *http.Request) (*geoip2.City, error) { var ( diff --git a/pkg/models/deletion/delete_user.go b/pkg/models/deletion/delete_user.go index 702ded9..c67c8f5 100644 --- a/pkg/models/deletion/delete_user.go +++ b/pkg/models/deletion/delete_user.go @@ -29,6 +29,7 @@ func DeleteUser(user *models.User) error { {"Subscriptions", DeleteSubscriptions}, {"Photos", DeleteUserPhotos}, {"Certification Photo", DeleteCertification}, + {"Who's Nearby Locations", DeleteUserLocation}, {"Comment Photos", DeleteUserCommentPhotos}, {"Messages", DeleteUserMessages}, {"Friends", DeleteFriends}, @@ -139,6 +140,16 @@ func DeleteCertification(userID uint64) error { return nil } +// DeleteUserLocation scrubs data for deleting a user. +func DeleteUserLocation(userID uint64) error { + log.Error("DeleteUser: DeleteUserLocation(%d)", userID) + result := models.DB.Where( + "user_id = ?", + userID, + ).Delete(&models.UserLocation{}) + return result.Error +} + // DeleteUserMessages scrubs data for deleting a user. func DeleteUserMessages(userID uint64) error { log.Error("DeleteUser: DeleteUserMessages(%d)", userID) diff --git a/pkg/models/models.go b/pkg/models/models.go index 318168e..90eea4a 100644 --- a/pkg/models/models.go +++ b/pkg/models/models.go @@ -28,4 +28,5 @@ func AutoMigrate() { DB.AutoMigrate(&PollVote{}) DB.AutoMigrate(&AdminGroup{}) DB.AutoMigrate(&AdminScope{}) + DB.AutoMigrate(&UserLocation{}) } diff --git a/pkg/models/user.go b/pkg/models/user.go index 226ec5a..387cb1e 100644 --- a/pkg/models/user.go +++ b/pkg/models/user.go @@ -203,11 +203,40 @@ func SearchUsers(user *User, search *UserSearch, pager *Pagination) ([]*User, er var ( users = []*User{} query *gorm.DB + joins string // GPS location join. wheres = []string{} placeholders = []interface{}{} blockedUserIDs = BlockedUserIDs(user.ID) + myLocation = GetUserLocation(user.ID) ) + // Sort by distance? Requires PostgreSQL. + if pager.Sort == "distance" { + if !config.Current.Database.IsPostgres { + return users, errors.New("ordering by distance requires PostgreSQL with the PostGIS extension") + } + + // If the current user doesn't have their location on file, they can't do this. + if myLocation.Source == LocationSourceNone || (myLocation.Latitude == 0 && myLocation.Longitude == 0) { + return users, errors.New("can not order by distance because your location is not known") + } + + // Only query for users who have locations. + joins = "JOIN user_locations ON (user_locations.user_id = users.id)" + wheres = append(wheres, + "user_locations.latitude IS NOT NULL", + "user_locations.longitude IS NOT NULL", + "user_locations.latitude <> 0", + "user_locations.longitude <> 0", + ) + + pager.Sort = fmt.Sprintf(`ST_Distance( + ST_MakePoint(user_locations.longitude, user_locations.latitude)::geography, + ST_MakePoint(%f, %f)::geography)`, + myLocation.Longitude, myLocation.Latitude, + ) + } + if len(blockedUserIDs) > 0 { wheres = append(wheres, "id NOT IN ?") placeholders = append(placeholders, blockedUserIDs) @@ -271,7 +300,11 @@ func SearchUsers(user *User, search *UserSearch, pager *Pagination) ([]*User, er placeholders = append(placeholders, date) } - query = (&User{}).Preload().Where( + query = (&User{}).Preload() + if joins != "" { + query = query.Joins(joins) + } + query = query.Where( strings.Join(wheres, " AND "), placeholders..., ).Order(pager.Sort) diff --git a/pkg/models/user_location.go b/pkg/models/user_location.go new file mode 100644 index 0000000..91e3980 --- /dev/null +++ b/pkg/models/user_location.go @@ -0,0 +1,135 @@ +package models + +import ( + "fmt" + "math" + "net/http" + + "code.nonshy.com/nonshy/website/pkg/geoip" + "code.nonshy.com/nonshy/website/pkg/log" +) + +// UserLocation table holds a user's location preference and coordinates. +type UserLocation struct { + UserID uint64 `gorm:"primaryKey"` + Source string + Latitude float64 `gorm:"index"` + Longitude float64 `gorm:"index"` +} + +// Source options for UserLocation. +const ( + LocationSourceNone = "" + LocationSourceGeoIP = "geoip" + LocationSourceGPS = "gps" + LocationSourcePin = "pin" +) + +// GetUserLocation gets the UserLocation object for a user ID, or a new object. +func GetUserLocation(userId uint64) *UserLocation { + var ul = &UserLocation{} + result := DB.First(&ul, userId) + if result.Error != nil { + return &UserLocation{ + UserID: userId, + } + } + return ul +} + +// Save the UserLocation. +func (ul *UserLocation) Save() error { + if ul.Source == LocationSourceNone { + ul.Latitude = 0 + ul.Longitude = 0 + } + return DB.Save(ul).Error +} + +// RefreshGeoIP will auto-update a user's location by GeoIP if that's their setting. +func RefreshGeoIP(userID uint64, r *http.Request) error { + loc := GetUserLocation(userID) + if loc.Source == LocationSourceGeoIP { + if insights, err := geoip.GetRequestInsights(r); err == nil { + loc.Latitude = insights.Latitude + loc.Longitude = insights.Longitude + return loc.Save() + } else { + return fmt.Errorf("didn't get insights: %s", err) + } + } + return nil +} + +// MapDistances computes human readable distances between you and the set of users. +func MapDistances(currentUser *User, others []*User) DistanceMap { + // Get all the distances we can. + var ( + result = DistanceMap{} + myDist = GetUserLocation(currentUser.ID) + // dist = map[uint64]*UserLocation{} + userIDs = []uint64{} + ) + for _, user := range others { + userIDs = append(userIDs, user.ID) + } + + // Query for their UserLocation objects, if exists. + var ul = []*UserLocation{} + res := DB.Where("user_id IN ?", userIDs).Find(&ul) + if res.Error != nil { + log.Error("MapDistances: %s", res.Error) + return result + } + + // Map them out. + for _, row := range ul { + km, mi := HaversineDistance( + myDist.Latitude, myDist.Longitude, + row.Latitude, row.Longitude, + ) + result[row.UserID] = fmt.Sprintf("%.1fkm / %.1fmi", km, mi) + } + + return result +} + +// DistanceMap maps user IDs to distance strings. +type DistanceMap map[uint64]string + +// Get a value from the DistanceMap for easy front-end access. +func (dm DistanceMap) Get(key uint64) string { + if value, ok := dm[key]; ok { + return value + } + return "unknown distance" +} + +// HaversineDistance returns the distance (in kilometers, miles) between +// two points of latitude and longitude pairs. +func HaversineDistance(lat1, lon1, lat2, lon2 float64) (float64, float64) { + lat1 *= piRad + lon1 *= piRad + lat2 *= piRad + lon2 *= piRad + var r = earthRadius + + // Calculate. + h := hsin(lat2-lat1) + math.Cos(lat1)*math.Cos(lat2)*hsin(lon2-lon1) + + meters := 2 * r * math.Asin(math.Sqrt(h)) + kilometers := meters / 1000 + miles := kilometers * 0.621371 + return kilometers, miles +} + +// adapted from: https://gist.github.com/cdipaolo/d3f8db3848278b49db68 +// haversin(θ) function +func hsin(theta float64) float64 { + return math.Pow(math.Sin(theta/2), 2) +} + +const ( + piRad = math.Pi / 180 + earthRadius = 6378100.0 // Earth radius in meters +) diff --git a/web/static/js/openlayers-7.5.1/en/latest/ol/dist/ol.js b/web/static/js/openlayers-7.5.1/en/latest/ol/dist/ol.js new file mode 100644 index 0000000..a4381cd --- /dev/null +++ b/web/static/js/openlayers-7.5.1/en/latest/ol/dist/ol.js @@ -0,0 +1,4 @@ +var ol=function(){"use strict";const t={1:"The view center is not defined",2:"The view resolution is not defined",3:"The view rotation is not defined",4:"`image` and `src` cannot be provided at the same time",5:"`imgSize` must be set when `image` is provided",7:"`format` must be set when `url` is set",8:"Unknown `serverType` configured",9:"`url` must be configured or set using `#setUrl()`",10:"The default `geometryFunction` can only handle `Point` geometries",11:"`options.featureTypes` must be an Array",12:"`options.geometryName` must also be provided when `options.bbox` is set",13:"Invalid corner",14:"Invalid color",15:"Tried to get a value for a key that does not exist in the cache",16:"Tried to set a value for a key that is used already",17:"`resolutions` must be sorted in descending order",18:"Either `origin` or `origins` must be configured, never both",19:"Number of `tileSizes` and `resolutions` must be equal",20:"Number of `origins` and `resolutions` must be equal",22:"Either `tileSize` or `tileSizes` must be configured, never both",24:"Invalid extent or geometry provided as `geometry`",25:"Cannot fit empty extent provided as `geometry`",26:"Features must have an id set",27:"Features must have an id set",28:'`renderMode` must be `"hybrid"` or `"vector"`',30:"The passed `feature` was already added to the source",31:"Tried to enqueue an `element` that was already added to the queue",32:"Transformation matrix cannot be inverted",33:"Invalid units",34:"Invalid geometry layout",36:"Unknown SRS type",37:"Unknown geometry type found",38:"`styleMapValue` has an unknown type",39:"Unknown geometry type",40:"Expected `feature` to have a geometry",41:"Expected an `ol/style/Style` or an array of `ol/style/Style.js`",42:"Question unknown, the answer is 42",43:"Expected `layers` to be an array or a `Collection`",47:"Expected `controls` to be an array or an `ol/Collection`",48:"Expected `interactions` to be an array or an `ol/Collection`",49:"Expected `overlays` to be an array or an `ol/Collection`",50:"`options.featureTypes` should be an Array",51:"Either `url` or `tileJSON` options must be provided",52:"Unknown `serverType` configured",53:"Unknown `tierSizeCalculation` configured",55:"The {-y} placeholder requires a tile grid with extent",56:"mapBrowserEvent must originate from a pointer event",57:"At least 2 conditions are required",59:"Invalid command found in the PBF",60:"Missing or invalid `size`",61:"Cannot determine IIIF Image API version from provided image information JSON",62:"A `WebGLArrayBuffer` must either be of type `ELEMENT_ARRAY_BUFFER` or `ARRAY_BUFFER`",64:"Layer opacity must be a number",66:"`forEachFeatureAtCoordinate` cannot be used on a WebGL layer if the hit detection logic has not been enabled. This is done by providing adequate shaders using the `hitVertexShader` and `hitFragmentShader` properties of `WebGLPointsLayerRenderer`",67:"A layer can only be added to the map once. Use either `layer.setMap()` or `map.addLayer()`, not both",68:"A VectorTile source can only be rendered if it has a projection compatible with the view projection",69:"`width` or `height` cannot be provided together with `scale`"};class e extends Error{constructor(e){const i=t[e];super(i),this.code=e,this.name="AssertionError",this.message=i}}var i=e;function n(t){t.stopPropagation()}var r=class{constructor(t){this.propagationStopped,this.defaultPrevented,this.type=t,this.target=null}preventDefault(){this.defaultPrevented=!0}stopPropagation(){this.propagationStopped=!0}},s="propertychange";var o=class{constructor(){this.disposed=!1}dispose(){this.disposed||(this.disposed=!0,this.disposeInternal())}disposeInternal(){}};function a(t,e,i){let n,r;i=i||l;let s=0,o=t.length,a=!1;for(;s>1),r=+i(t[n],e),r<0?s=n+1:(o=n,a=!r);return a?s:~s}function l(t,e){return t>e?1:te?-1:0}function c(t,e,i){if(t[0]<=e)return 0;const n=t.length;if(e<=t[n-1])return n-1;if("function"==typeof i){for(let r=1;r0?r-1:r}return n-1}if(i>0){for(let i=1;i0||i&&0===s)}))}function p(){return!0}function m(){return!1}function _(){}function y(t){let e,i,n,r=!1;return function(){const s=Array.prototype.slice.call(arguments);return r&&this===n&&g(s,i)||(r=!0,n=this,i=s,e=t.apply(this,arguments)),e}}function x(t){return function(){let e;try{e=t()}catch(t){return Promise.reject(t)}return e instanceof Promise?e:Promise.resolve(e)}()}function v(t){for(const e in t)delete t[e]}function S(t){let e;for(e in t)return!1;return!e}var w=class extends o{constructor(t){super(),this.eventTarget_=t,this.pendingRemovals_=null,this.dispatching_=null,this.listeners_=null}addEventListener(t,e){if(!t||!e)return;const i=this.listeners_||(this.listeners_={}),n=i[t]||(i[t]=[]);n.includes(e)||n.push(e)}dispatchEvent(t){const e="string"==typeof t,i=e?t:t.type,n=this.listeners_&&this.listeners_[i];if(!n)return;const s=e?new r(t):t;s.target||(s.target=this.eventTarget_||this);const o=this.dispatching_||(this.dispatching_={}),a=this.pendingRemovals_||(this.pendingRemovals_={});let l;i in o||(o[i]=0,a[i]=0),++o[i];for(let t=0,e=n.length;t0)}removeEventListener(t,e){const i=this.listeners_&&this.listeners_[t];if(i){const n=i.indexOf(e);-1!==n&&(this.pendingRemovals_&&t in this.pendingRemovals_?(i[n]=_,++this.pendingRemovals_[t]):(i.splice(n,1),0===i.length&&delete this.listeners_[t]))}}},E="change",T="error",C="contextmenu",R="click",b="dblclick",P="dragenter",I="dragover",F="drop",L="keydown",M="keypress",A="load",O="touchmove",N="wheel";function D(t,e,i,n,r){if(n&&n!==t&&(i=i.bind(n)),r){const n=i;i=function(){t.removeEventListener(e,i),n.apply(this,arguments)}}const s={target:t,type:e,listener:i};return t.addEventListener(e,i),s}function k(t,e,i,n){return D(t,e,i,n,!0)}function G(t){t&&t.target&&(t.target.removeEventListener(t.type,t.listener),v(t))}class j extends w{constructor(){super(),this.on=this.onInternal,this.once=this.onceInternal,this.un=this.unInternal,this.revision_=0}changed(){++this.revision_,this.dispatchEvent(E)}getRevision(){return this.revision_}onInternal(t,e){if(Array.isArray(t)){const i=t.length,n=new Array(i);for(let r=0;r0;)this.pop()}extend(t){for(let e=0,i=t.length;ethis.getLength())throw new Error("Index out of bounds: "+t);this.unique_&&this.assertUnique_(e),this.array_.splice(t,0,e),this.updateLength_(),this.dispatchEvent(new q(Y,e,t))}pop(){return this.removeAt(this.getLength()-1)}push(t){this.unique_&&this.assertUnique_(t);const e=this.getLength();return this.insertAt(e,t),this.getLength()}remove(t){const e=this.array_;for(let i=0,n=e.length;i=this.getLength())return;const e=this.array_[t];return this.array_.splice(t,1),this.updateLength_(),this.dispatchEvent(new q(K,e,t)),e}setAt(t,e){if(t>=this.getLength())return void this.insertAt(t,e);if(t<0)throw new Error("Index out of bounds: "+t);this.unique_&&this.assertUnique_(e,t);const i=this.array_[t];this.array_[t]=e,this.dispatchEvent(new q(K,i,t)),this.dispatchEvent(new q(Y,e,t))}updateLength_(){this.set(H,this.array_.length)}assertUnique_(t,e){for(let n=0,r=this.array_.length;nt)throw new Error("Tile load sequence violation");this.state=t,this.changed()}load(){z()}getAlpha(t,e){if(!this.transition_)return 1;let i=this.transitionStarts_[t];if(i){if(-1===i)return 1}else i=e,this.transitionStarts_[t]=i;const n=e-i+1e3/60;return n>=this.transition_?1:nt(n/this.transition_)}inTransition(t){return!!this.transition_&&-1!==this.transitionStarts_[t]}endTransition(t){this.transition_&&(this.transitionStarts_[t]=-1)}};const lt="undefined"!=typeof navigator&&void 0!==navigator.userAgent?navigator.userAgent.toLowerCase():"",ht=lt.includes("firefox"),ct=lt.includes("safari")&&!lt.includes("chrom"),ut=ct&&(lt.includes("version/15.4")||/cpu (os|iphone os) 15_4 like mac os x/.test(lt)),dt=lt.includes("webkit")&&!lt.includes("edge"),gt=lt.includes("macintosh"),ft="undefined"!=typeof devicePixelRatio?devicePixelRatio:1,pt="undefined"!=typeof WorkerGlobalScope&&"undefined"!=typeof OffscreenCanvas&&self instanceof WorkerGlobalScope,mt="undefined"!=typeof Image&&Image.prototype.decode,_t=function(){let t=!1;try{const e=Object.defineProperty({},"passive",{get:function(){t=!0}});window.addEventListener("_",null,e),window.removeEventListener("_",null,e)}catch(t){}return t}();function yt(t,e,i,n){let r;return r=i&&i.length?i.shift():pt?new OffscreenCanvas(t||300,e||300):document.createElement("canvas"),t&&(r.width=t),e&&(r.height=e),r.getContext("2d",n)}function xt(t){const e=t.canvas;e.width=1,e.height=1,t.clearRect(0,0,1,1)}function vt(t){let e=t.offsetWidth;const i=getComputedStyle(t);return e+=parseInt(i.marginLeft,10)+parseInt(i.marginRight,10),e}function St(t){let e=t.offsetHeight;const i=getComputedStyle(t);return e+=parseInt(i.marginTop,10)+parseInt(i.marginBottom,10),e}function wt(t,e){const i=e.parentNode;i&&i.replaceChild(t,e)}function Et(t){return t&&t.parentNode?t.parentNode.removeChild(t):null}function Tt(t){for(;t.lastChild;)t.removeChild(t.lastChild)}function Ct(t,e){const i=t.childNodes;for(let n=0;;++n){const r=i[n],s=e[n];if(!r&&!s)break;r!==s&&(r?s?t.insertBefore(s,r):(t.removeChild(r),--n):t.appendChild(s))}}function Rt(t){return t instanceof Image||t instanceof HTMLCanvasElement||t instanceof HTMLVideoElement?t:null}function bt(t){return t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Float32Array||t instanceof DataView?t:null}let Pt=null;function It(t){Pt||(Pt=yt(t.width,t.height,void 0,{willReadFrequently:!0}));const e=Pt.canvas,i=t.width;e.width!==i&&(e.width=i);const n=t.height;return e.height!==n&&(e.height=n),Pt.clearRect(0,0,i,n),Pt.drawImage(t,0,0),Pt.getImageData(0,0,i,n).data}const Ft=[256,256];var Lt=class extends at{constructor(t){const e=J;super(t.tileCoord,e,{transition:t.transition,interpolate:t.interpolate}),this.loader_=t.loader,this.data_=null,this.error_=null,this.size_=t.size||null}getSize(){if(this.size_)return this.size_;const t=Rt(this.data_);return t?[t.width,t.height]:Ft}getData(){return this.data_}getError(){return this.error_}load(){if(this.state!==J&&this.state!==et)return;this.state=Q,this.changed();const t=this;this.loader_().then((function(e){t.data_=e,t.state=tt,t.changed()})).catch((function(e){t.error_=e,t.state=et,t.changed()}))}};function Mt(t,e){if(!t)throw new i(e)}class At extends Z{constructor(t){if(super(),this.on,this.once,this.un,this.id_=void 0,this.geometryName_="geometry",this.style_=null,this.styleFunction_=void 0,this.geometryChangeKey_=null,this.addChangeListener(this.geometryName_,this.handleGeometryChanged_),t)if("function"==typeof t.getSimplifiedGeometry){const e=t;this.setGeometry(e)}else{const e=t;this.setProperties(e)}}clone(){const t=new At(this.hasProperties()?this.getProperties():null);t.setGeometryName(this.getGeometryName());const e=this.getGeometry();e&&t.setGeometry(e.clone());const i=this.getStyle();return i&&t.setStyle(i),t}getGeometry(){return this.get(this.geometryName_)}getId(){return this.id_}getGeometryName(){return this.geometryName_}getStyle(){return this.style_}getStyleFunction(){return this.styleFunction_}handleGeometryChange_(){this.changed()}handleGeometryChanged_(){this.geometryChangeKey_&&(G(this.geometryChangeKey_),this.geometryChangeKey_=null);const t=this.getGeometry();t&&(this.geometryChangeKey_=D(t,E,this.handleGeometryChange_,this)),this.changed()}setGeometry(t){this.set(this.geometryName_,t)}setStyle(t){this.style_=t,this.styleFunction_=t?Ot(t):void 0,this.changed()}setId(t){this.id_=t,this.changed()}setGeometryName(t){this.removeChangeListener(this.geometryName_,this.handleGeometryChanged_),this.geometryName_=t,this.addChangeListener(this.geometryName_,this.handleGeometryChanged_),this.handleGeometryChanged_()}}function Ot(t){if("function"==typeof t)return t;let e;if(Array.isArray(t))e=t;else{Mt("function"==typeof t.getZIndex,41);e=[t]}return function(){return e}}var Nt=At;const Dt=new Array(6);function kt(){return[1,0,0,1,0,0]}function Gt(t){return Bt(t,1,0,0,1,0,0)}function jt(t,e){const i=t[0],n=t[1],r=t[2],s=t[3],o=t[4],a=t[5],l=e[0],h=e[1],c=e[2],u=e[3],d=e[4],g=e[5];return t[0]=i*l+r*h,t[1]=n*l+s*h,t[2]=i*c+r*u,t[3]=n*c+s*u,t[4]=i*d+r*g+o,t[5]=n*d+s*g+a,t}function Bt(t,e,i,n,r,s,o){return t[0]=e,t[1]=i,t[2]=n,t[3]=r,t[4]=s,t[5]=o,t}function Ut(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t}function zt(t,e){const i=e[0],n=e[1];return e[0]=t[0]*i+t[2]*n+t[4],e[1]=t[1]*i+t[3]*n+t[5],e}function Xt(t,e){const i=Math.cos(e),n=Math.sin(e);return jt(t,Bt(Dt,i,n,-n,i,0,0))}function Vt(t,e,i){return jt(t,Bt(Dt,e,0,0,i,0,0))}function Wt(t,e,i){return Bt(t,e,0,0,i,0,0)}function Zt(t,e,i){return jt(t,Bt(Dt,1,0,0,1,e,i))}function Yt(t,e,i,n,r,s,o,a){const l=Math.sin(s),h=Math.cos(s);return t[0]=n*h,t[1]=r*l,t[2]=-n*l,t[3]=r*h,t[4]=o*n*h-a*n*l+e,t[5]=o*r*l+a*r*h+i,t}function Kt(t,e){const i=Ht(e);Mt(0!==i,32);const n=e[0],r=e[1],s=e[2],o=e[3],a=e[4],l=e[5];return t[0]=o/i,t[1]=-r/i,t[2]=-s/i,t[3]=n/i,t[4]=(s*l-o*a)/i,t[5]=-(n*l-r*a)/i,t}function Ht(t){return t[0]*t[3]-t[1]*t[2]}let qt;function $t(t){const e="matrix("+t.join(", ")+")";if(pt)return e;const i=qt||(qt=document.createElement("div"));return i.style.transform=e,i.style.transform}var Jt={UNKNOWN:0,INTERSECTING:1,ABOVE:2,RIGHT:4,BELOW:8,LEFT:16};function Qt(t){const e=ae();for(let i=0,n=t.length;ir&&(l|=Jt.RIGHT),as&&(l|=Jt.ABOVE),l===Jt.UNKNOWN&&(l=Jt.INTERSECTING),l}function ae(){return[1/0,1/0,-1/0,-1/0]}function le(t,e,i,n,r){return r?(r[0]=t,r[1]=e,r[2]=i,r[3]=n,r):[t,e,i,n]}function he(t){return le(1/0,1/0,-1/0,-1/0,t)}function ce(t,e){const i=t[0],n=t[1];return le(i,n,i,n,e)}function ue(t,e,i,n,r){return _e(he(r),t,e,i,n)}function de(t,e){return t[0]==e[0]&&t[2]==e[2]&&t[1]==e[1]&&t[3]==e[3]}function ge(t,e,i){return Math.abs(t[0]-e[0])t[2]&&(t[2]=e[2]),e[1]t[3]&&(t[3]=e[3]),t}function pe(t,e){e[0]t[2]&&(t[2]=e[0]),e[1]t[3]&&(t[3]=e[1])}function me(t,e){for(let i=0,n=e.length;ie[0]?n[0]=t[0]:n[0]=e[0],t[1]>e[1]?n[1]=t[1]:n[1]=e[1],t[2]=e[0]&&t[1]<=e[3]&&t[3]>=e[1]}function Oe(t){return t[2]=o&&p<=l),n||!(s&Jt.RIGHT)||r&Jt.RIGHT||(m=g-(d-l)*f,n=m>=a&&m<=h),n||!(s&Jt.BELOW)||r&Jt.BELOW||(p=d-(g-a)/f,n=p>=o&&p<=l),n||!(s&Jt.LEFT)||r&Jt.LEFT||(m=g-(d-o)*f,n=m>=a&&m<=h)}return n}function Ge(t,e,i,n){if(Oe(t))return he(i);let r=[];if(n>1){const e=t[2]-t[0],i=t[3]-t[1];for(let s=0;s=i[2])){const e=Me(i),r=Math.floor((n[0]-i[0])/e)*e;t[0]-=r,t[2]-=r}return t}function Be(t,e){if(e.canWrapX()){const i=e.getExtent();if(!isFinite(t[0])||!isFinite(t[2]))return[[i[0],t[1],i[2],t[3]]];je(t,e);const n=Me(i);if(Me(t)>n)return[[i[0],t[1],i[2],t[3]]];if(t[0]i[2])return[[t[0],t[1],i[2],t[3]],[i[0],t[1],t[2]-n,t[3]]]}return[t]}const Ue={9001:"m",9002:"ft",9003:"us-ft",9101:"radians",9102:"degrees"};function ze(t){return Ue[t]}const Xe={radians:6370997/(2*Math.PI),degrees:2*Math.PI*6370997/360,ft:.3048,m:1,"us-ft":1200/3937};var Ve=class{constructor(t){this.code_=t.code,this.units_=t.units,this.extent_=void 0!==t.extent?t.extent:null,this.worldExtent_=void 0!==t.worldExtent?t.worldExtent:null,this.axisOrientation_=void 0!==t.axisOrientation?t.axisOrientation:"enu",this.global_=void 0!==t.global&&t.global,this.canWrapX_=!(!this.global_||!this.extent_),this.getPointResolutionFunc_=t.getPointResolution,this.defaultTileGrid_=null,this.metersPerUnit_=t.metersPerUnit}canWrapX(){return this.canWrapX_}getCode(){return this.code_}getExtent(){return this.extent_}getUnits(){return this.units_}getMetersPerUnit(){return this.metersPerUnit_||Xe[this.units_]}getWorldExtent(){return this.worldExtent_}getAxisOrientation(){return this.axisOrientation_}isGlobal(){return this.global_}setGlobal(t){this.global_=t,this.canWrapX_=!(!t||!this.extent_)}getDefaultTileGrid(){return this.defaultTileGrid_}setDefaultTileGrid(t){this.defaultTileGrid_=t}setExtent(t){this.extent_=t,this.canWrapX_=!(!this.global_||!t)}setWorldExtent(t){this.worldExtent_=t}setGetPointResolution(t){this.getPointResolutionFunc_=t}getPointResolutionFunc(){return this.getPointResolutionFunc_}};const We=6378137,Ze=Math.PI*We,Ye=[-Ze,-Ze,Ze,Ze],Ke=[-180,-85,180,85],He=We*Math.log(Math.tan(Math.PI/2));class qe extends Ve{constructor(t){super({code:t,units:"m",extent:Ye,global:!0,worldExtent:Ke,getPointResolution:function(t,e){return t/Math.cosh(e[1]/We)}})}}const $e=[new qe("EPSG:3857"),new qe("EPSG:102100"),new qe("EPSG:102113"),new qe("EPSG:900913"),new qe("http://www.opengis.net/def/crs/EPSG/0/3857"),new qe("http://www.opengis.net/gml/srs/epsg.xml#3857")];function Je(t,e,i){const n=t.length;i=i>1?i:2,void 0===e&&(e=i>2?t.slice():new Array(n));for(let r=0;rHe?i=He:i<-He&&(i=-He),e[r+1]=i}return e}function Qe(t,e,i){const n=t.length;i=i>1?i:2,void 0===e&&(e=i>2?t.slice():new Array(n));for(let r=0;r1?(i=r,n=s):l>0&&(i+=o*l,n+=a*l)}return pi(t,e,i,n)}function pi(t,e,i,n){const r=i-t,s=n-e;return r*r+s*s}function mi(t){const e=t.length;for(let i=0;ir&&(r=e,n=s)}if(0===r)return null;const s=t[n];t[n]=t[i],t[i]=s;for(let n=i+1;n=0;n--){i[n]=t[n][e]/t[n][n];for(let r=n-1;r>=0;r--)t[r][e]-=t[r][n]*i[n]}return i}function _i(t){return 180*t/Math.PI}function yi(t){return t*Math.PI/180}function xi(t,e){const i=t%e;return i*e<0?i+e:i}function vi(t,e,i){return t+i*(e-t)}function Si(t,e){const i=Math.pow(10,e);return Math.round(t*i)/i}function wi(t,e){return Math.round(Si(t,e))}function Ei(t,e){return Math.floor(Si(t,e))}function Ti(t,e){return Math.ceil(Si(t,e))}function Ci(t,e,i){const n=void 0!==i?t.toFixed(i):""+t;let r=n.indexOf(".");return r=-1===r?n.length:r,r>e?n:new Array(1+e-r).join("0")+n}function Ri(t,e){const i=(""+t).split("."),n=(""+e).split(".");for(let t=0;tr)return 1;if(r>e)return-1}return 0}function bi(t,e){return t[0]+=+e[0],t[1]+=+e[1],t}function Pi(t,e){const i=e.getRadius(),n=e.getCenter(),r=n[0],s=n[1];let o=t[0]-r;const a=t[1]-s;0===o&&0===a&&(o=1);const l=Math.sqrt(o*o+a*a);return[r+i*o/l,s+i*a/l]}function Ii(t,e){const i=t[0],n=t[1],r=e[0],s=e[1],o=r[0],a=r[1],l=s[0],h=s[1],c=l-o,u=h-a,d=0===c&&0===u?0:(c*(i-o)+u*(n-a))/(c*c+u*u||0);let g,f;return d<=0?(g=o,f=a):d>=1?(g=l,f=h):(g=o+d*c,f=a+d*u),[g,f]}function Fi(t,e,i){const n=xi(e+180,360)-180,r=Math.abs(3600*n),s=i||0;let o=Math.floor(r/3600),a=Math.floor((r-3600*o)/60),l=Si(r-3600*o-60*a,s);l>=60&&(l=0,a+=1),a>=60&&(a=0,o+=1);let h=o+"°";return 0===a&&0===l||(h+=" "+Ci(a,2)+"′"),0!==l&&(h+=" "+Ci(l,2,s)+"″"),0!==n&&(h+=" "+t.charAt(n<0?1:0)),h}function Li(t,e,i){return t?e.replace("{x}",t[0].toFixed(i)).replace("{y}",t[1].toFixed(i)):""}function Mi(t,e){let i=!0;for(let n=t.length-1;n>=0;--n)if(t[n]!=e[n]){i=!1;break}return i}function Ai(t,e){const i=Math.cos(e),n=Math.sin(e),r=t[0]*i-t[1]*n,s=t[1]*i+t[0]*n;return t[0]=r,t[1]=s,t}function Oi(t,e){return t[0]*=e,t[1]*=e,t}function Ni(t,e){const i=t[0]-e[0],n=t[1]-e[1];return i*i+n*n}function Di(t,e){return Math.sqrt(Ni(t,e))}function ki(t,e){return Ni(t,Ii(t,e))}function Gi(t,e){return Li(t,"{x}, {y}",e)}function ji(t,e){if(e.canWrapX()){const i=Me(e.getExtent()),n=Bi(t,e,i);n&&(t[0]-=n*i)}return t}function Bi(t,e,i){const n=e.getExtent();let r=0;return e.canWrapX()&&(t[0]n[2])&&(i=i||Me(n),r=Math.floor((t[0]-n[0])/i)),r}const Ui=6371008.8;function zi(t,e,i){i=i||Ui;const n=yi(t[1]),r=yi(e[1]),s=(r-n)/2,o=yi(e[0]-t[0])/2,a=Math.sin(s)*Math.sin(s)+Math.sin(o)*Math.sin(o)*Math.cos(n)*Math.cos(r);return 2*i*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))}function Xi(t,e){let i=0;for(let n=0,r=t.length;nZi.warn||console.warn(...t)}function Hi(...t){Yi>Zi.error||console.error(...t)}let qi=!0;function $i(t){qi=!(void 0===t||t)}function Ji(t,e){if(void 0!==e)for(let i=0,n=t.length;i=o?e[s+t]:r[t]}return i}}function hn(t,e,i,n){const r=nn(t),s=nn(e);ui(r,s,ln(i)),ui(s,r,ln(n))}function cn(t,e){if(t===e)return!0;const i=t.getUnits()===e.getUnits();if(t.getCode()===e.getCode())return i;return un(t,e)===Ji&&i}function un(t,e){let i=di(t.getCode(),e.getCode());return i||(i=Qi),i}function dn(t,e){return un(nn(t),nn(e))}function gn(t,e,i){return dn(e,i)(t,void 0,t.length)}function fn(t,e,i,n){return Ge(t,dn(e,i),void 0,n)}let pn=null;function mn(t){pn=nn(t)}function _n(){return pn}function yn(t,e){return pn?gn(t,e,pn):t}function xn(t,e){return pn?gn(t,pn,e):(qi&&!Mi(t,[0,0])&&t[0]>=-180&&t[0]<=180&&t[1]>=-90&&t[1]<=90&&(qi=!1,Ki("Call useGeographic() from ol/proj once to work with [longitude, latitude] coordinates.")),t)}function vn(t,e){return pn?fn(t,e,pn):t}function Sn(t,e){return pn?fn(t,pn,e):t}function wn(t,e){if(!pn)return t;const i=nn(e).getUnits(),n=pn.getUnits();return i&&n?t*Xe[i]/Xe[n]:t}function En(t,e){if(!pn)return t;const i=nn(e).getUnits(),n=pn.getUnits();return i&&n?t*Xe[n]/Xe[i]:t}function Tn(t,e,i){return function(n){let r,s;if(t.canWrapX()){const e=t.getExtent(),o=Me(e);s=Bi(n=n.slice(0),t,o),s&&(n[0]=n[0]-s*o),n[0]=gi(n[0],e[0],e[2]),n[1]=gi(n[1],e[1],e[3]),r=i(n)}else r=i(n);return s&&e.canWrapX()&&(r[0]+=s*Me(e.getExtent())),r}}function Cn(){sn($e),sn(ri),on(ri,$e,Je,Qe)}function Rn(t,e,i,n,r,s){s=s||[];let o=0;for(let a=e;a1)u=i;else{if(d>0){for(let r=0;rr&&(r=a),s=i,o=n}return r}function kn(t,e,i,n,r){for(let s=0,o=i.length;s0;){const i=h.pop(),s=h.pop();let o=0;const a=t[s],u=t[s+1],d=t[i],g=t[i+1];for(let e=s+n;eo&&(c=e,o=i)}o>r&&(l[(c-e)/n]=1,s+nr&&(s[o++]=h,s[o++]=c,a=h,l=c);return h==a&&c==l||(s[o++]=h,s[o++]=c),o}function Hn(t,e){return e*Math.round(t/e)}function qn(t,e,i,n,r,s,o){if(e==i)return o;let a,l,h=Hn(t[e],r),c=Hn(t[e+1],r);e+=n,s[o++]=h,s[o++]=c;do{if(a=Hn(t[e],r),l=Hn(t[e+1],r),(e+=n)==i)return s[o++]=a,s[o++]=l,o}while(a==h&&l==c);for(;e0&&f>d)&&(g<0&&p0&&p>g)?(a=i,l=u):(s[o++]=a,s[o++]=l,h=a,c=l,a=i,l=u)}return s[o++]=a,s[o++]=l,o}function $n(t,e,i,n,r,s,o,a){for(let l=0,h=i.length;ls&&(i-a)*(s-l)-(r-a)*(n-l)>0&&o++:n<=s&&(i-a)*(s-l)-(r-a)*(n-l)<0&&o--,a=i,l=n}return 0!==o}function ur(t,e,i,n,r,s){if(0===i.length)return!1;if(!cr(t,e,i[0],n,r,s))return!1;for(let e=1,o=i.length;ey&&(c=(u+d)/2,ur(t,e,i,n,c,p)&&(_=c,y=r)),u=d}return isNaN(_)&&(_=r[s]),o?(o.push(_,p,y),o):[_,p,y]}function fr(t,e,i,n,r){let s=[];for(let o=0,a=i.length;o=r[0]&&s[2]<=r[2]||(s[1]>=r[1]&&s[3]<=r[3]||pr(t,e,i,n,(function(t,e){return ke(r,t,e)})))))}function _r(t,e,i,n,r){for(let s=0,o=i.length;s0}function Er(t,e,i,n,r){r=void 0!==r&&r;for(let s=0,o=i.length;s0&&this.points_[i+2]>t;)i-=3;const n=this.points_[e+2]-this.points_[i+2];if(n<1e3/60)return!1;const r=this.points_[e]-this.points_[i],s=this.points_[e+1]-this.points_[i+1];return this.angle_=Math.atan2(s,r),this.initialVelocity_=Math.sqrt(r*r+s*s)/n,this.initialVelocity_>this.minVelocity_}getDistance(){return(this.minVelocity_-this.initialVelocity_)/this.decay_}getAngle(){return this.angle_}};const rs=/^#([a-f0-9]{3}|[a-f0-9]{4}(?:[a-f0-9]{2}){0,2})$/i,ss=/^([a-z]*)$|^hsla?\(.*\)$/i;function os(t){return"string"==typeof t?t:us(t)}function as(t){const e=document.createElement("div");if(e.style.color=t,""!==e.style.color){document.body.appendChild(e);const t=getComputedStyle(e).color;return document.body.removeChild(e),t}return""}const ls=function(){const t={};let e=0;return function(i){let n;if(t.hasOwnProperty(i))n=t[i];else{if(e>=1024){let i=0;for(const n in t)0==(3&i++)&&(delete t[n],--e)}n=function(t){let e,i,n,r,s;ss.exec(t)&&(t=as(t));if(rs.exec(t)){const o=t.length-1;let a;a=o<=4?1:2;const l=4===o||8===o;e=parseInt(t.substr(1+0*a,a),16),i=parseInt(t.substr(1+1*a,a),16),n=parseInt(t.substr(1+2*a,a),16),r=l?parseInt(t.substr(1+3*a,a),16):255,1==a&&(e=(e<<4)+e,i=(i<<4)+i,n=(n<<4)+n,l&&(r=(r<<4)+r)),s=[e,i,n,r/255]}else t.startsWith("rgba(")?(s=t.slice(5,-1).split(",").map(Number),cs(s)):t.startsWith("rgb(")?(s=t.slice(4,-1).split(",").map(Number),s.push(1),cs(s)):Mt(!1,14);return s}(i),t[i]=n,++e}return n}}();function hs(t){return Array.isArray(t)?t:ls(t)}function cs(t){return t[0]=gi(t[0]+.5|0,0,255),t[1]=gi(t[1]+.5|0,0,255),t[2]=gi(t[2]+.5|0,0,255),t[3]=gi(t[3],0,1),t}function us(t){let e=t[0];e!=(0|e)&&(e=e+.5|0);let i=t[1];i!=(0|i)&&(i=i+.5|0);let n=t[2];n!=(0|n)&&(n=n+.5|0);return"rgba("+e+","+i+","+n+","+(void 0===t[3]?1:Math.round(100*t[3])/100)+")"}function ds(t){return ss.test(t)&&(t=as(t)),rs.test(t)||t.startsWith("rgba(")||t.startsWith("rgb(")}class gs{constructor(){this.cache_={},this.cacheSize_=0,this.maxCacheSize_=32}clear(){this.cache_={},this.cacheSize_=0}canExpireCache(){return this.cacheSize_>this.maxCacheSize_}expire(){if(this.canExpireCache()){let t=0;for(const e in this.cache_){const i=this.cache_[e];0!=(3&t++)||i.hasListener()||(delete this.cache_[e],--this.cacheSize_)}}}get(t,e,i){const n=fs(t,e,i);return n in this.cache_?this.cache_[n]:null}set(t,e,i,n){const r=fs(t,e,i);this.cache_[r]=n,++this.cacheSize_}setSize(t){this.maxCacheSize_=t,this.expire()}}function fs(t,e,i){return e+":"+t+":"+(i?os(i):"null")}var ps=gs;const ms=new gs;var _s="opacity",ys="visible",xs="extent",vs="zIndex",Ss="maxResolution",ws="minResolution",Es="maxZoom",Ts="minZoom",Cs="source",Rs="map";var bs=class extends Z{constructor(t){super(),this.on,this.once,this.un,this.background_=t.background;const e=Object.assign({},t);"object"==typeof t.properties&&(delete e.properties,Object.assign(e,t.properties)),e[_s]=void 0!==t.opacity?t.opacity:1,Mt("number"==typeof e[_s],64),e[ys]=void 0===t.visible||t.visible,e[vs]=t.zIndex,e[Ss]=void 0!==t.maxResolution?t.maxResolution:1/0,e[ws]=void 0!==t.minResolution?t.minResolution:0,e[Ts]=void 0!==t.minZoom?t.minZoom:-1/0,e[Es]=void 0!==t.maxZoom?t.maxZoom:1/0,this.className_=void 0!==e.className?e.className:"ol-layer",delete e.className,this.setProperties(e),this.state_=null}getBackground(){return this.background_}getClassName(){return this.className_}getLayerState(t){const e=this.state_||{layer:this,managed:void 0===t||t},i=this.getZIndex();return e.opacity=gi(Math.round(100*this.getOpacity())/100,0,1),e.visible=this.getVisible(),e.extent=this.getExtent(),e.zIndex=void 0!==i||e.managed?i:1/0,e.maxResolution=this.getMaxResolution(),e.minResolution=Math.max(this.getMinResolution(),0),e.minZoom=this.getMinZoom(),e.maxZoom=this.getMaxZoom(),this.state_=e,e}getLayersArray(t){return z()}getLayerStatesArray(t){return z()}getExtent(){return this.get(xs)}getMaxResolution(){return this.get(Ss)}getMinResolution(){return this.get(ws)}getMinZoom(){return this.get(Ts)}getMaxZoom(){return this.get(Es)}getOpacity(){return this.get(_s)}getSourceState(){return z()}getVisible(){return this.get(ys)}getZIndex(){return this.get(vs)}setBackground(t){this.background_=t,this.changed()}setExtent(t){this.set(xs,t)}setMaxResolution(t){this.set(Ss,t)}setMinResolution(t){this.set(ws,t)}setMaxZoom(t){this.set(Es,t)}setMinZoom(t){this.set(Ts,t)}setOpacity(t){Mt("number"==typeof t,64),this.set(_s,t)}setVisible(t){this.set(ys,t)}setZIndex(t){this.set(vs,t)}disposeInternal(){this.state_&&(this.state_.layer=null,this.state_=null),super.disposeInternal()}},Ps="prerender",Is="postrender",Fs="precompose",Ls="postcompose",Ms="rendercomplete",As=0,Os=1,Ns={CENTER:"center",RESOLUTION:"resolution",ROTATION:"rotation"};const Ds=42,ks=256;function Gs(t,e,i){return function(n,r,s,o,a){if(!n)return;if(!r&&!e)return n;const l=e?0:s[0]*r,h=e?0:s[1]*r,c=a?a[0]:0,u=a?a[1]:0;let d=t[0]+l/2+c,g=t[2]-l/2+c,f=t[1]+h/2+u,p=t[3]-h/2+u;d>g&&(d=(g+d)/2,g=d),f>p&&(f=(p+f)/2,p=f);let m=gi(n[0],d,g),_=gi(n[1],f,p);if(o&&i&&r){const t=30*r;m+=-t*Math.log(1+Math.max(0,d-n[0])/t)+t*Math.log(1+Math.max(0,n[0]-g)/t),_+=-t*Math.log(1+Math.max(0,f-n[1])/t)+t*Math.log(1+Math.max(0,n[1]-p)/t)}return[m,_]}}function js(t){return t}function Bs(t,e,i,n){const r=Me(e)/i[0],s=Pe(e)/i[1];return n?Math.min(t,Math.max(r,s)):Math.min(t,Math.min(r,s))}function Us(t,e,i){let n=Math.min(t,e);return n*=Math.log(1+50*Math.max(0,t/e-1))/50+1,i&&(n=Math.max(n,i),n/=Math.log(1+50*Math.max(0,i/t-1))/50+1),gi(n,i/2,2*e)}function zs(t,e,i,n){return e=void 0===e||e,function(r,s,o,a){if(void 0!==r){const l=t[0],h=t[t.length-1],u=i?Bs(l,i,o,n):l;if(a)return e?Us(r,u,h):gi(r,h,u);const d=Math.min(u,r),g=Math.floor(c(t,d,s));return t[g]>u&&g1&&"function"==typeof arguments[i-1]&&(e=arguments[i-1],--i);let n=0;for(;n0}getInteracting(){return this.hints_[Os]>0}cancelAnimations(){let t;this.setHint(As,-this.hints_[As]);for(let e=0,i=this.animations_.length;e=0;--i){const n=this.animations_[i];let r=!0;for(let i=0,s=n.length;i0?o/s.duration:1;a>=1?(s.complete=!0,a=1):r=!1;const l=s.easing(a);if(s.sourceCenter){const t=s.sourceCenter[0],e=s.sourceCenter[1],i=s.targetCenter[0],n=s.targetCenter[1];this.nextCenter_=s.targetCenter;const r=t+l*(i-t),o=e+l*(n-e);this.targetCenter_=[r,o]}if(s.sourceResolution&&s.targetResolution){const t=1===l?s.targetResolution:s.sourceResolution+l*(s.targetResolution-s.sourceResolution);if(s.anchor){const e=this.getViewportSize_(this.getRotation()),i=this.constraints_.resolution(t,0,e,!0);this.targetCenter_=this.calculateCenterZoom(i,s.anchor)}this.nextResolution_=s.targetResolution,this.targetResolution_=t,this.applyTargetState_(!0)}if(void 0!==s.sourceRotation&&void 0!==s.targetRotation){const t=1===l?xi(s.targetRotation+Math.PI,2*Math.PI)-Math.PI:s.sourceRotation+l*(s.targetRotation-s.sourceRotation);if(s.anchor){const e=this.constraints_.rotation(t,!0);this.targetCenter_=this.calculateCenterRotate(e,s.anchor)}this.nextRotation_=s.targetRotation,this.targetRotation_=t}if(this.applyTargetState_(!0),e=!0,!s.complete)break}if(r){this.animations_[i]=null,this.setHint(As,-1),this.nextCenter_=null,this.nextResolution_=NaN,this.nextRotation_=NaN;const t=n[0].callback;t&&Hs(t,!0)}}this.animations_=this.animations_.filter(Boolean),e&&void 0===this.updateAnimationKey_&&(this.updateAnimationKey_=requestAnimationFrame(this.updateAnimations_.bind(this)))}calculateCenterRotate(t,e){let i;const n=this.getCenterInternal();return void 0!==n&&(i=[n[0]-e[0],n[1]-e[1]],Ai(i,t-this.getRotation()),bi(i,e)),i}calculateCenterZoom(t,e){let i;const n=this.getCenterInternal(),r=this.getResolution();if(void 0!==n&&void 0!==r){i=[e[0]-t*(e[0]-n[0])/r,e[1]-t*(e[1]-n[1])/r]}return i}getViewportSize_(t){const e=this.viewportSize_;if(t){const i=e[0],n=e[1];return[Math.abs(i*Math.cos(t))+Math.abs(n*Math.sin(t)),Math.abs(i*Math.sin(t))+Math.abs(n*Math.cos(t))]}return e}setViewportSize(t){this.viewportSize_=Array.isArray(t)?t.slice():[100,100],this.getAnimating()||this.resolveConstraints(0)}getCenter(){const t=this.getCenterInternal();return t?yn(t,this.getProjection()):t}getCenterInternal(){return this.get(Ns.CENTER)}getConstraints(){return this.constraints_}getConstrainResolution(){return this.get("constrainResolution")}getHints(t){return void 0!==t?(t[0]=this.hints_[0],t[1]=this.hints_[1],t):this.hints_.slice()}calculateExtent(t){return vn(this.calculateExtentInternal(t),this.getProjection())}calculateExtentInternal(t){t=t||this.getViewportSizeMinusPadding_();const e=this.getCenterInternal();Mt(e,1);const i=this.getResolution();Mt(void 0!==i,2);const n=this.getRotation();return Mt(void 0!==n,3),Re(e,i,n,t)}getMaxResolution(){return this.maxResolution_}getMinResolution(){return this.minResolution_}getMaxZoom(){return this.getZoomForResolution(this.minResolution_)}setMaxZoom(t){this.applyOptions_(this.getUpdatedOptions_({maxZoom:t}))}getMinZoom(){return this.getZoomForResolution(this.maxResolution_)}setMinZoom(t){this.applyOptions_(this.getUpdatedOptions_({minZoom:t}))}setConstrainResolution(t){this.applyOptions_(this.getUpdatedOptions_({constrainResolution:t}))}getProjection(){return this.projection_}getResolution(){return this.get(Ns.RESOLUTION)}getResolutions(){return this.resolutions_}getResolutionForExtent(t,e){return this.getResolutionForExtentInternal(Sn(t,this.getProjection()),e)}getResolutionForExtentInternal(t,e){e=e||this.getViewportSizeMinusPadding_();const i=Me(t)/e[0],n=Pe(t)/e[1];return Math.max(i,n)}getResolutionForValueFunction(t){t=t||2;const e=this.getConstrainedResolution(this.maxResolution_),i=this.minResolution_,n=Math.log(e/i)/Math.log(t);return function(i){return e/Math.pow(t,i*n)}}getRotation(){return this.get(Ns.ROTATION)}getValueForResolutionFunction(t){const e=Math.log(t||2),i=this.getConstrainedResolution(this.maxResolution_),n=this.minResolution_,r=Math.log(i/n)/e;return function(t){return Math.log(i/t)/e/r}}getViewportSizeMinusPadding_(t){let e=this.getViewportSize_(t);const i=this.padding_;return i&&(e=[e[0]-i[1]-i[3],e[1]-i[0]-i[2]]),e}getState(){const t=this.getProjection(),e=this.getResolution(),i=this.getRotation();let n=this.getCenterInternal();const r=this.padding_;if(r){const t=this.getViewportSizeMinusPadding_();n=to(n,this.getViewportSize_(),[t[0]/2+r[3],t[1]/2+r[0]],e,i)}return{center:n.slice(0),projection:void 0!==t?t:null,resolution:e,nextCenter:this.nextCenter_,nextResolution:this.nextResolution_,nextRotation:this.nextRotation_,rotation:i,zoom:this.getZoom()}}getViewStateAndExtent(){return{viewState:this.getState(),extent:this.calculateExtent()}}getZoom(){let t;const e=this.getResolution();return void 0!==e&&(t=this.getZoomForResolution(e)),t}getZoomForResolution(t){let e,i,n=this.minZoom_||0;if(this.resolutions_){const r=c(this.resolutions_,t,1);n=r,e=this.resolutions_[r],i=r==this.resolutions_.length-1?2:e/this.resolutions_[r+1]}else e=this.maxResolution_,i=this.zoomFactor_;return n+Math.log(e/t)/Math.log(i)}getResolutionForZoom(t){if(this.resolutions_){if(this.resolutions_.length<=1)return 0;const e=gi(Math.floor(t),0,this.resolutions_.length-2),i=this.resolutions_[e]/this.resolutions_[e+1];return this.resolutions_[e]/Math.pow(i,gi(t-e,0,1))}return this.maxResolution_/Math.pow(this.zoomFactor_,t-this.minZoom_)}fit(t,e){let i;if(Mt(Array.isArray(t)||"function"==typeof t.getSimplifiedGeometry,24),Array.isArray(t)){Mt(!Oe(t),25);i=Lr(Sn(t,this.getProjection()))}else if("Circle"===t.getType()){const e=Sn(t.getExtent(),this.getProjection());i=Lr(e),i.rotate(this.getRotation(),Te(e))}else{const e=_n();i=e?t.clone().transform(e,this.getProjection()):t}this.fitInternal(i,e)}rotatedExtentForGeometry(t){const e=this.getRotation(),i=Math.cos(e),n=Math.sin(-e),r=t.getFlatCoordinates(),s=t.getStride();let o=1/0,a=1/0,l=-1/0,h=-1/0;for(let t=0,e=r.length;t=t.maxResolution)return!1;const n=e.zoom;return n>t.minZoom&&n<=t.maxZoom}var no=class extends bs{constructor(t){const e=Object.assign({},t);delete e.source,super(e),this.on,this.once,this.un,this.mapPrecomposeKey_=null,this.mapRenderKey_=null,this.sourceChangeKey_=null,this.renderer_=null,this.sourceReady_=!1,this.rendered=!1,t.render&&(this.render=t.render),t.map&&this.setMap(t.map),this.addChangeListener(Cs,this.handleSourcePropertyChange_);const i=t.source?t.source:null;this.setSource(i)}getLayersArray(t){return(t=t||[]).push(this),t}getLayerStatesArray(t){return(t=t||[]).push(this.getLayerState()),t}getSource(){return this.get(Cs)||null}getRenderSource(){return this.getSource()}getSourceState(){const t=this.getSource();return t?t.getState():"undefined"}handleSourceChange_(){this.changed(),this.sourceReady_||"ready"!==this.getSource().getState()||(this.sourceReady_=!0,this.dispatchEvent("sourceready"))}handleSourcePropertyChange_(){this.sourceChangeKey_&&(G(this.sourceChangeKey_),this.sourceChangeKey_=null),this.sourceReady_=!1;const t=this.getSource();t&&(this.sourceChangeKey_=D(t,E,this.handleSourceChange_,this),"ready"===t.getState()&&(this.sourceReady_=!0,setTimeout((()=>{this.dispatchEvent("sourceready")}),0))),this.changed()}getFeatures(t){return this.renderer_?this.renderer_.getFeatures(t):Promise.resolve([])}getData(t){return this.renderer_&&this.rendered?this.renderer_.getData(t):null}isVisible(t){let e;const i=this.getMapInternal();let n;!t&&i&&(t=i.getView()),e=t instanceof eo?{viewState:t.getState(),extent:t.calculateExtent()}:t,!e.layerStatesArray&&i&&(e.layerStatesArray=i.getLayerGroup().getLayerStatesArray()),n=e.layerStatesArray?e.layerStatesArray.find((t=>t.layer===this)):this.getLayerState();const r=this.getExtent();return io(n,e.viewState)&&(!r||Ae(r,e.extent))}getAttributions(t){if(!this.isVisible(t))return[];let e;const i=this.getSource();if(i&&(e=i.getAttributions()),!e)return[];let n=e(t instanceof eo?t.getViewStateAndExtent():t);return Array.isArray(n)||(n=[n]),n}render(t,e){const i=this.getRenderer();return i.prepareFrame(t)?(this.rendered=!0,i.renderFrame(t,e)):null}unrender(){this.rendered=!1}setMapInternal(t){t||this.unrender(),this.set(Rs,t)}getMapInternal(){return this.get(Rs)}setMap(t){this.mapPrecomposeKey_&&(G(this.mapPrecomposeKey_),this.mapPrecomposeKey_=null),t||this.changed(),this.mapRenderKey_&&(G(this.mapRenderKey_),this.mapRenderKey_=null),t&&(this.mapPrecomposeKey_=D(t,Fs,(function(t){const e=t.frameState.layerStatesArray,i=this.getLayerState(!1);Mt(!e.some((function(t){return t.layer===i.layer})),67),e.push(i)}),this),this.mapRenderKey_=D(this,E,t.render,t),this.changed())}setSource(t){this.set(Cs,t)}getRenderer(){return this.renderer_||(this.renderer_=this.createRenderer()),this.renderer_}hasRenderer(){return!!this.renderer_}createRenderer(){return null}disposeInternal(){this.renderer_&&(this.renderer_.dispose(),delete this.renderer_),this.setSource(null),super.disposeInternal()}};function ro(t,e){ms.expire()}var so=class extends o{constructor(t){super(),this.map_=t}dispatchRenderEvent(t,e){z()}calculateMatrices2D(t){const e=t.viewState,i=t.coordinateToPixelTransform,n=t.pixelToCoordinateTransform;Yt(i,t.size[0]/2,t.size[1]/2,1/e.resolution,-1/e.resolution,-e.rotation,-e.center[0],-e.center[1]),Kt(n,i)}forEachFeatureAtCoordinate(t,e,i,n,r,s,o,a){let l;const h=e.viewState;function c(t,e,i,n){return r.call(s,e,t?i:null,n)}const u=h.projection,d=ji(t.slice(),u),g=[[0,0]];if(u.canWrapX()&&n){const t=Me(u.getExtent());g.push([-t,0],[t,0])}const f=e.layerStatesArray,p=f.length,m=[],_=[];for(let n=0;n=0;--r){const s=f[r],u=s.layer;if(u.hasRenderer()&&io(s,h)&&o.call(a,u)){const r=u.getRenderer(),o=u.getSource();if(r&&o){const a=o.getWrapX()?d:t,h=c.bind(null,s.managed);_[0]=a[0]+g[n][0],_[1]=a[1]+g[n][1],l=r.forEachFeatureAtCoordinate(_,e,i,h,m)}if(l)return l}}if(0===m.length)return;const y=1/m.length;return m.forEach(((t,e)=>t.distanceSq+=e*y)),m.sort(((t,e)=>t.distanceSq-e.distanceSq)),m.some((t=>l=t.callback(t.feature,t.layer,t.geometry))),l}hasFeatureAtCoordinate(t,e,i,n,r,s){return void 0!==this.forEachFeatureAtCoordinate(t,e,i,n,p,this,r,s)}getMap(){return this.map_}renderFrame(t){z()}flushDeclutterItems(t){}scheduleExpireIconCache(t){ms.canExpireCache()&&t.postRenderFunctions.push(ro)}};var oo=class extends r{constructor(t,e,i,n){super(t),this.inversePixelTransform=e,this.frameState=i,this.context=n}};const ao="ol-hidden",lo="ol-selectable",ho="ol-unselectable",co="ol-unsupported",uo="ol-control",go="ol-collapsed",fo=new RegExp(["^\\s*(?=(?:(?:[-a-z]+\\s*){0,2}(italic|oblique))?)","(?=(?:(?:[-a-z]+\\s*){0,2}(small-caps))?)","(?=(?:(?:[-a-z]+\\s*){0,2}(bold(?:er)?|lighter|[1-9]00 ))?)","(?:(?:normal|\\1|\\2|\\3)\\s*){0,3}((?:xx?-)?","(?:small|large)|medium|smaller|larger|[\\.\\d]+(?:\\%|in|[cem]m|ex|p[ctx]))","(?:\\s*\\/\\s*(normal|[\\.\\d]+(?:\\%|in|[cem]m|ex|p[ctx])?))","?\\s*([-,\\\"\\'\\sa-z]+?)\\s*$"].join(""),"i"),po=["style","variant","weight","size","lineHeight","family"],mo=function(t){const e=t.match(fo);if(!e)return null;const i={lineHeight:"normal",size:"1.2em",style:"normal",weight:"normal",variant:"normal"};for(let t=0,n=po.length;tMath.max(e,Oo(t,i))),0);return i[e]=n,n}function Do(t,e){const i=[],n=[],r=[];let s=0,o=0,a=0,l=0;for(let h=0,c=e.length;h<=c;h+=2){const u=e[h];if("\n"===u||h===c){s=Math.max(s,o),r.push(o),o=0,a+=l;continue}const d=e[h+1]||t.font,g=Oo(d,u);i.push(g),o+=g;const f=Mo(d);n.push(f),l=Math.max(l,f)}return{width:s,height:a,widths:i,heights:n,lineWidths:r}}function ko(t,e,i,n,r,s,o,a,l,h,c){t.save(),1!==i&&(t.globalAlpha*=i),e&&t.setTransform.apply(t,e),n.contextInstructions?(t.translate(l,h),t.scale(c[0],c[1]),function(t,e){const i=t.contextInstructions;for(let t=0,n=i.length;t=0;--i)e[i].renderDeclutter(t);t.declutterTree=null,e.length=0}};class jo extends r{constructor(t,e){super(t),this.layer=e}}const Bo="layers";class Uo extends bs{constructor(t){t=t||{};const e=Object.assign({},t);delete e.layers;let i=t.layers;super(e),this.on,this.once,this.un,this.layersListenerKeys_=[],this.listenerKeys_={},this.addChangeListener(Bo,this.handleLayersChanged_),i?Array.isArray(i)?i=new $(i.slice(),{unique:!0}):Mt("function"==typeof i.getArray,43):i=new $(void 0,{unique:!0}),this.setLayers(i)}handleLayerChange_(){this.changed()}handleLayersChanged_(){this.layersListenerKeys_.forEach(G),this.layersListenerKeys_.length=0;const t=this.getLayers();this.layersListenerKeys_.push(D(t,Y,this.handleLayersAdd_,this),D(t,K,this.handleLayersRemove_,this));for(const t in this.listenerKeys_)this.listenerKeys_[t].forEach(G);v(this.listenerKeys_);const e=t.getArray();for(let t=0,i=e.length;t{this.clickTimeoutId_=void 0;const e=new Vo(Wo.SINGLECLICK,this.map_,t);this.dispatchEvent(e)}),250)}updateActivePointers_(t){const e=t,i=e.pointerId;if(e.type==Wo.POINTERUP||e.type==Wo.POINTERCANCEL){delete this.trackedTouches_[i];for(const t in this.trackedTouches_)if(this.trackedTouches_[t].target!==e.target){delete this.trackedTouches_[t];break}}else e.type!=Wo.POINTERDOWN&&e.type!=Wo.POINTERMOVE||(this.trackedTouches_[i]=e);this.activePointers_=Object.values(this.trackedTouches_)}handlePointerUp_(t){this.updateActivePointers_(t);const e=new Vo(Wo.POINTERUP,this.map_,t,void 0,void 0,this.activePointers_);this.dispatchEvent(e),this.emulateClicks_&&!e.defaultPrevented&&!this.dragging_&&this.isMouseActionButton_(t)&&this.emulateClick_(this.down_),0===this.activePointers_.length&&(this.dragListenerKeys_.forEach(G),this.dragListenerKeys_.length=0,this.dragging_=!1,this.down_=null)}isMouseActionButton_(t){return 0===t.button}handlePointerDown_(t){this.emulateClicks_=0===this.activePointers_.length,this.updateActivePointers_(t);const e=new Vo(Wo.POINTERDOWN,this.map_,t,void 0,void 0,this.activePointers_);if(this.dispatchEvent(e),this.down_=new PointerEvent(t.type,t),Object.defineProperty(this.down_,"target",{writable:!1,value:t.target}),0===this.dragListenerKeys_.length){const t=this.map_.getOwnerDocument();this.dragListenerKeys_.push(D(t,Wo.POINTERMOVE,this.handlePointerMove_,this),D(t,Wo.POINTERUP,this.handlePointerUp_,this),D(this.element_,Wo.POINTERCANCEL,this.handlePointerUp_,this)),this.element_.getRootNode&&this.element_.getRootNode()!==t&&this.dragListenerKeys_.push(D(this.element_.getRootNode(),Wo.POINTERUP,this.handlePointerUp_,this))}}handlePointerMove_(t){if(this.isMoving_(t)){this.updateActivePointers_(t),this.dragging_=!0;const e=new Vo(Wo.POINTERDRAG,this.map_,t,this.dragging_,void 0,this.activePointers_);this.dispatchEvent(e)}}relayMoveEvent_(t){this.originalPointerMoveEvent_=t;const e=!(!this.down_||!this.isMoving_(t));this.dispatchEvent(new Vo(Wo.POINTERMOVE,this.map_,t,e))}handleTouchMove_(t){const e=this.originalPointerMoveEvent_;e&&!e.defaultPrevented||"boolean"==typeof t.cancelable&&!0!==t.cancelable||t.preventDefault()}isMoving_(t){return this.dragging_||Math.abs(t.clientX-this.down_.clientX)>this.moveTolerance_||Math.abs(t.clientY-this.down_.clientY)>this.moveTolerance_}disposeInternal(){this.relayedListenerKey_&&(G(this.relayedListenerKey_),this.relayedListenerKey_=null),this.element_.removeEventListener(O,this.boundHandleTouchMove_),this.pointerdownListenerKey_&&(G(this.pointerdownListenerKey_),this.pointerdownListenerKey_=null),this.dragListenerKeys_.forEach(G),this.dragListenerKeys_.length=0,this.element_=null,super.disposeInternal()}},$o="postrender",Jo="movestart",Qo="moveend",ta="loadstart",ea="loadend",ia="layergroup",na="size",ra="target",sa="view";const oa=1/0;var aa=class{constructor(t,e){this.priorityFunction_=t,this.keyFunction_=e,this.elements_=[],this.priorities_=[],this.queuedElements_={}}clear(){this.elements_.length=0,this.priorities_.length=0,v(this.queuedElements_)}dequeue(){const t=this.elements_,e=this.priorities_,i=t[0];1==t.length?(t.length=0,e.length=0):(t[0]=t.pop(),e[0]=e.pop(),this.siftUp_(0));const n=this.keyFunction_(i);return delete this.queuedElements_[n],i}enqueue(t){Mt(!(this.keyFunction_(t)in this.queuedElements_),31);const e=this.priorityFunction_(t);return e!=oa&&(this.elements_.push(t),this.priorities_.push(e),this.queuedElements_[this.keyFunction_(t)]=!0,this.siftDown_(0,this.elements_.length-1),!0)}getCount(){return this.elements_.length}getLeftChildIndex_(t){return 2*t+1}getRightChildIndex_(t){return 2*t+2}getParentIndex_(t){return t-1>>1}heapify_(){let t;for(t=(this.elements_.length>>1)-1;t>=0;t--)this.siftUp_(t)}isEmpty(){return 0===this.elements_.length}isKeyQueued(t){return t in this.queuedElements_}isQueued(t){return this.isKeyQueued(this.keyFunction_(t))}siftUp_(t){const e=this.elements_,i=this.priorities_,n=e.length,r=e[t],s=i[t],o=t;for(;t>1;){const r=this.getLeftChildIndex_(t),s=this.getRightChildIndex_(t),o=st;){const t=this.getParentIndex_(e);if(!(n[t]>s))break;i[e]=i[t],n[e]=n[t],e=t}i[e]=r,n[e]=s}reprioritize(){const t=this.priorityFunction_,e=this.elements_,i=this.priorities_;let n=0;const r=e.length;let s,o,a;for(o=0;o0;)n=this.dequeue()[0],r=n.getKey(),i=n.getState(),i!==J||r in this.tilesLoadingKeys_||(this.tilesLoadingKeys_[r]=!0,++this.tilesLoading_,++s,n.load())}};function ha(t,e,i,n,r){if(!t||!(i in t.wantedTiles))return oa;if(!t.wantedTiles[i][e.getKey()])return oa;const s=t.viewState.center,o=n[0]-s[0],a=n[1]-s[1];return 65536*Math.log(r)+Math.sqrt(o*o+a*a)/r}var ca=class extends Z{constructor(t){super();const e=t.element;!e||t.target||e.style.pointerEvents||(e.style.pointerEvents="auto"),this.element=e||null,this.target_=null,this.map_=null,this.listenerKeys=[],t.render&&(this.render=t.render),t.target&&this.setTarget(t.target)}disposeInternal(){Et(this.element),super.disposeInternal()}getMap(){return this.map_}setMap(t){this.map_&&Et(this.element);for(let t=0,e=this.listenerKeys.length;te.getAttributions(t))))),i=!this.getMap().getAllLayers().some((t=>t.getSource()&&!1===t.getSource().getAttributionsCollapsible()));return this.overrideCollapsible_||this.setCollapsible(i),e}updateElement_(t){if(!t)return void(this.renderedVisible_&&(this.element.style.display="none",this.renderedVisible_=!1));const e=this.collectSourceAttributions_(t),i=e.length>0;if(this.renderedVisible_!=i&&(this.element.style.display=i?"":"none",this.renderedVisible_=i),!g(e,this.renderedAttributions_)){Tt(this.ulElement_);for(let t=0,i=e.length;t0&&e%(2*Math.PI)!=0?t.animate({rotation:0,duration:this.duration_,easing:rt}):t.setRotation(0))}render(t){const e=t.frameState;if(!e)return;const i=e.viewState.rotation;if(i!=this.rotation_){const t="rotate("+i+"rad)";if(this.autoHide_){const t=this.element.classList.contains(ao);t||0!==i?t&&0!==i&&this.element.classList.remove(ao):this.element.classList.add(ao)}this.label_.style.transform=t}this.rotation_=i}};var ga=class extends ca{constructor(t){t=t||{},super({element:document.createElement("div"),target:t.target});const e=void 0!==t.className?t.className:"ol-zoom",i=void 0!==t.delta?t.delta:1,n=void 0!==t.zoomInClassName?t.zoomInClassName:e+"-in",r=void 0!==t.zoomOutClassName?t.zoomOutClassName:e+"-out",s=void 0!==t.zoomInLabel?t.zoomInLabel:"+",o=void 0!==t.zoomOutLabel?t.zoomOutLabel:"–",a=void 0!==t.zoomInTipLabel?t.zoomInTipLabel:"Zoom in",l=void 0!==t.zoomOutTipLabel?t.zoomOutTipLabel:"Zoom out",h=document.createElement("button");h.className=n,h.setAttribute("type","button"),h.title=a,h.appendChild("string"==typeof s?document.createTextNode(s):s),h.addEventListener(R,this.handleClick_.bind(this,i),!1);const c=document.createElement("button");c.className=r,c.setAttribute("type","button"),c.title=l,c.appendChild("string"==typeof o?document.createTextNode(o):o),c.addEventListener(R,this.handleClick_.bind(this,-i),!1);const u=e+" "+ho+" "+uo,d=this.element;d.className=u,d.appendChild(h),d.appendChild(c),this.duration_=void 0!==t.duration?t.duration:250}handleClick_(t,e){e.preventDefault(),this.zoomByDelta_(t)}zoomByDelta_(t){const e=this.getMap().getView();if(!e)return;const i=e.getZoom();if(void 0!==i){const n=e.getConstrainedZoom(i+t);this.duration_>0?(e.getAnimating()&&e.cancelAnimations(),e.animate({zoom:n,duration:this.duration_,easing:rt})):e.setZoom(n)}}};function fa(t){t=t||{};const e=new $;(void 0===t.zoom||t.zoom)&&e.push(new ga(t.zoomOptions));(void 0===t.rotate||t.rotate)&&e.push(new da(t.rotateOptions));return(void 0===t.attribution||t.attribution)&&e.push(new ua(t.attributionOptions)),e}var pa="active";function ma(t,e,i){const n=t.getCenterInternal();if(n){const r=[n[0]+e[0],n[1]+e[1]];t.animateInternal({duration:void 0!==i?i:250,easing:ot,center:t.getConstrainedCenter(r)})}}function _a(t,e,i,n){const r=t.getZoom();if(void 0===r)return;const s=t.getConstrainedZoom(r+e),o=t.getResolutionForZoom(s);t.getAnimating()&&t.cancelAnimations(),t.animate({resolution:o,anchor:i,duration:void 0!==n?n:250,easing:rt})}var ya=class extends Z{constructor(t){super(),this.on,this.once,this.un,t&&t.handleEvent&&(this.handleEvent=t.handleEvent),this.map_=null,this.setActive(!0)}getActive(){return this.get(pa)}getMap(){return this.map_}handleEvent(t){return!0}setActive(t){this.set(pa,t)}setMap(t){this.map_=t}};var xa=class extends ya{constructor(t){super(),t=t||{},this.delta_=t.delta?t.delta:1,this.duration_=void 0!==t.duration?t.duration:250}handleEvent(t){let e=!1;if(t.type==Wo.DBLCLICK){const i=t.originalEvent,n=t.map,r=t.coordinate,s=i.shiftKey?-this.delta_:this.delta_;_a(n.getView(),s,r,this.duration_),i.preventDefault(),e=!0}return!e}};function va(t){const e=t.length;let i=0,n=0;for(let r=0;r0}}else if(t.type==Wo.POINTERDOWN){const i=this.handleDownEvent(t);this.handlingDownUpSequence=i,e=this.stopDown(i)}else t.type==Wo.POINTERMOVE&&this.handleMoveEvent(t);return!e}handleMoveEvent(t){}handleUpEvent(t){return!1}stopDown(t){return t}updateTrackedPointers_(t){t.activePointers&&(this.targetPointers=t.activePointers)}};function wa(t){const e=arguments;return function(t){let i=!0;for(let n=0,r=e.length;n0&&this.condition_(t)){const e=t.map.getView();return this.lastCentroid=null,e.getAnimating()&&e.cancelAnimations(),this.kinetic_&&this.kinetic_.begin(),this.noKinetic_=this.targetPointers.length>1,!0}return!1}};var Ga=class extends Sa{constructor(t){t=t||{},super({stopDown:m}),this.condition_=t.condition?t.condition:Ta,this.lastAngle_=void 0,this.duration_=void 0!==t.duration?t.duration:250}handleDragEvent(t){if(!Na(t))return;const e=t.map,i=e.getView();if(i.getConstraints().rotation===Ws)return;const n=e.getSize(),r=t.pixel,s=Math.atan2(n[1]/2-r[1],r[0]-n[0]/2);if(void 0!==this.lastAngle_){const t=s-this.lastAngle_;i.adjustRotationInternal(-t)}this.lastAngle_=s}handleUpEvent(t){if(!Na(t))return!0;return t.map.getView().endInteraction(this.duration_),!1}handleDownEvent(t){if(!Na(t))return!1;if(Pa(t)&&this.condition_(t)){return t.map.getView().beginInteraction(),this.lastAngle_=void 0,!0}return!1}};var ja=class extends o{constructor(t){super(),this.geometry_=null,this.element_=document.createElement("div"),this.element_.style.position="absolute",this.element_.style.pointerEvents="auto",this.element_.className="ol-box "+t,this.map_=null,this.startPixel_=null,this.endPixel_=null}disposeInternal(){this.setMap(null)}render_(){const t=this.startPixel_,e=this.endPixel_,i="px",n=this.element_.style;n.left=Math.min(t[0],e[0])+i,n.top=Math.min(t[1],e[1])+i,n.width=Math.abs(e[0]-t[0])+i,n.height=Math.abs(e[1]-t[1])+i}setMap(t){if(this.map_){this.map_.getOverlayContainer().removeChild(this.element_);const t=this.element_.style;t.left="inherit",t.top="inherit",t.width="inherit",t.height="inherit"}this.map_=t,this.map_&&this.map_.getOverlayContainer().appendChild(this.element_)}setPixels(t,e){this.startPixel_=t,this.endPixel_=e,this.createOrUpdateGeometry(),this.render_()}createOrUpdateGeometry(){const t=this.startPixel_,e=this.endPixel_,i=[t,[t[0],e[1]],e,[e[0],t[1]]].map(this.map_.getCoordinateFromPixelInternal,this.map_);i[4]=i[0].slice(),this.geometry_?this.geometry_.setCoordinates([i]):this.geometry_=new Ir([i])}getGeometry(){return this.geometry_}};const Ba="boxstart",Ua="boxdrag",za="boxend",Xa="boxcancel";class Va extends r{constructor(t,e,i){super(t),this.coordinate=e,this.mapBrowserEvent=i}}var Wa=class extends Sa{constructor(t){super(),this.on,this.once,this.un,t=t||{},this.box_=new ja(t.className||"ol-dragbox"),this.minArea_=void 0!==t.minArea?t.minArea:64,t.onBoxEnd&&(this.onBoxEnd=t.onBoxEnd),this.startPixel_=null,this.condition_=t.condition?t.condition:Pa,this.boxEndCondition_=t.boxEndCondition?t.boxEndCondition:this.defaultBoxEndCondition}defaultBoxEndCondition(t,e,i){const n=i[0]-e[0],r=i[1]-e[1];return n*n+r*r>=this.minArea_}getGeometry(){return this.box_.getGeometry()}handleDragEvent(t){this.box_.setPixels(this.startPixel_,t.pixel),this.dispatchEvent(new Va(Ua,t.coordinate,t))}handleUpEvent(t){this.box_.setMap(null);const e=this.boxEndCondition_(t,this.startPixel_,t.pixel);return e&&this.onBoxEnd(t),this.dispatchEvent(new Va(e?za:Xa,t.coordinate,t)),!1}handleDownEvent(t){return!!this.condition_(t)&&(this.startPixel_=t.pixel,this.box_.setMap(t.map),this.box_.setPixels(this.startPixel_,this.startPixel_),this.dispatchEvent(new Va(Ba,t.coordinate,t)),!0)}onBoxEnd(t){}};var Za=class extends Wa{constructor(t){super({condition:(t=t||{}).condition?t.condition:Aa,className:t.className||"ol-dragzoom",minArea:t.minArea}),this.duration_=void 0!==t.duration?t.duration:200,this.out_=void 0!==t.out&&t.out}onBoxEnd(t){const e=this.getMap().getView();let i=this.getGeometry();if(this.out_){const t=e.rotatedExtentForGeometry(i),n=e.getResolutionForExtentInternal(t),r=e.getResolution()/n;i=i.clone(),i.scale(r*r)}e.fitInternal(i,{duration:this.duration_,easing:rt})}},Ya="ArrowLeft",Ka="ArrowUp",Ha="ArrowRight",qa="ArrowDown";var $a=class extends ya{constructor(t){super(),t=t||{},this.defaultCondition_=function(t){return La(t)&&Oa(t)},this.condition_=void 0!==t.condition?t.condition:this.defaultCondition_,this.duration_=void 0!==t.duration?t.duration:100,this.pixelDelta_=void 0!==t.pixelDelta?t.pixelDelta:128}handleEvent(t){let e=!1;if(t.type==L){const i=t.originalEvent,n=i.key;if(this.condition_(t)&&(n==qa||n==Ya||n==Ha||n==Ka)){const r=t.map.getView(),s=r.getResolution()*this.pixelDelta_;let o=0,a=0;n==qa?a=-s:n==Ya?o=-s:n==Ha?o=s:a=s;const l=[o,a];Ai(l,r.getRotation()),ma(r,l,this.duration_),i.preventDefault(),e=!0}}return!e}};var Ja=class extends ya{constructor(t){super(),t=t||{},this.condition_=t.condition?t.condition:function(t){return!Ma(t)&&Oa(t)},this.delta_=t.delta?t.delta:1,this.duration_=void 0!==t.duration?t.duration:100}handleEvent(t){let e=!1;if(t.type==L||t.type==M){const i=t.originalEvent,n=i.key;if(this.condition_(t)&&("+"===n||"-"===n)){const r=t.map,s="+"===n?this.delta_:-this.delta_;_a(r.getView(),s,void 0,this.duration_),i.preventDefault(),e=!0}}return!e}};var Qa=class extends ya{constructor(t){super(t=t||{}),this.totalDelta_=0,this.lastDelta_=0,this.maxDelta_=void 0!==t.maxDelta?t.maxDelta:1,this.duration_=void 0!==t.duration?t.duration:250,this.timeout_=void 0!==t.timeout?t.timeout:80,this.useAnchor_=void 0===t.useAnchor||t.useAnchor,this.constrainResolution_=void 0!==t.constrainResolution&&t.constrainResolution;const e=t.condition?t.condition:ba;this.condition_=t.onFocusOnly?wa(Ra,e):e,this.lastAnchor_=null,this.startTime_=void 0,this.timeoutId_,this.mode_=void 0,this.trackpadEventGap_=400,this.trackpadTimeoutId_,this.deltaPerZoom_=300}endInteraction_(){this.trackpadTimeoutId_=void 0;const t=this.getMap();if(!t)return;t.getView().endInteraction(void 0,this.lastDelta_?this.lastDelta_>0?1:-1:0,this.lastAnchor_)}handleEvent(t){if(!this.condition_(t))return!0;if(t.type!==N)return!0;const e=t.map,i=t.originalEvent;let n;if(i.preventDefault(),this.useAnchor_&&(this.lastAnchor_=t.coordinate),t.type==N&&(n=i.deltaY,ht&&i.deltaMode===WheelEvent.DOM_DELTA_PIXEL&&(n/=ft),i.deltaMode===WheelEvent.DOM_DELTA_LINE&&(n*=40)),0===n)return!1;this.lastDelta_=n;const r=Date.now();void 0===this.startTime_&&(this.startTime_=r),(!this.mode_||r-this.startTime_>this.trackpadEventGap_)&&(this.mode_=Math.abs(n)<4?"trackpad":"wheel");const s=e.getView();if("trackpad"===this.mode_&&!s.getConstrainResolution()&&!this.constrainResolution_)return this.trackpadTimeoutId_?clearTimeout(this.trackpadTimeoutId_):(s.getAnimating()&&s.cancelAnimations(),s.beginInteraction()),this.trackpadTimeoutId_=setTimeout(this.endInteraction_.bind(this),this.timeout_),s.adjustZoom(-n/this.deltaPerZoom_,this.lastAnchor_),this.startTime_=r,!1;this.totalDelta_+=n;const o=Math.max(this.timeout_-(r-this.startTime_),0);return clearTimeout(this.timeoutId_),this.timeoutId_=setTimeout(this.handleWheelZoom_.bind(this,e),o),!1}handleWheelZoom_(t){const e=t.getView();e.getAnimating()&&e.cancelAnimations();let i=-gi(this.totalDelta_,-this.maxDelta_*this.deltaPerZoom_,this.maxDelta_*this.deltaPerZoom_)/this.deltaPerZoom_;(e.getConstrainResolution()||this.constrainResolution_)&&(i=i?i>0?1:-1:0),_a(e,i,this.lastAnchor_,this.duration_),this.mode_=void 0,this.totalDelta_=0,this.lastAnchor_=null,this.startTime_=void 0,this.timeoutId_=void 0}setMouseAnchor(t){this.useAnchor_=t,t||(this.lastAnchor_=null)}};var tl=class extends Sa{constructor(t){const e=t=t||{};e.stopDown||(e.stopDown=m),super(e),this.anchor_=null,this.lastAngle_=void 0,this.rotating_=!1,this.rotationDelta_=0,this.threshold_=void 0!==t.threshold?t.threshold:.3,this.duration_=void 0!==t.duration?t.duration:250}handleDragEvent(t){let e=0;const i=this.targetPointers[0],n=this.targetPointers[1],r=Math.atan2(n.clientY-i.clientY,n.clientX-i.clientX);if(void 0!==this.lastAngle_){const t=r-this.lastAngle_;this.rotationDelta_+=t,!this.rotating_&&Math.abs(this.rotationDelta_)>this.threshold_&&(this.rotating_=!0),e=t}this.lastAngle_=r;const s=t.map,o=s.getView();o.getConstraints().rotation!==Ws&&(this.anchor_=s.getCoordinateFromPixelInternal(s.getEventPixel(va(this.targetPointers))),this.rotating_&&(s.render(),o.adjustRotationInternal(e,this.anchor_)))}handleUpEvent(t){if(this.targetPointers.length<2){return t.map.getView().endInteraction(this.duration_),!1}return!0}handleDownEvent(t){if(this.targetPointers.length>=2){const e=t.map;return this.anchor_=null,this.lastAngle_=void 0,this.rotating_=!1,this.rotationDelta_=0,this.handlingDownUpSequence||e.getView().beginInteraction(),!0}return!1}};var el=class extends Sa{constructor(t){const e=t=t||{};e.stopDown||(e.stopDown=m),super(e),this.anchor_=null,this.duration_=void 0!==t.duration?t.duration:400,this.lastDistance_=void 0,this.lastScaleDelta_=1}handleDragEvent(t){let e=1;const i=this.targetPointers[0],n=this.targetPointers[1],r=i.clientX-n.clientX,s=i.clientY-n.clientY,o=Math.sqrt(r*r+s*s);void 0!==this.lastDistance_&&(e=this.lastDistance_/o),this.lastDistance_=o;const a=t.map,l=a.getView();1!=e&&(this.lastScaleDelta_=e),this.anchor_=a.getCoordinateFromPixelInternal(a.getEventPixel(va(this.targetPointers))),a.render(),l.adjustResolutionInternal(e,this.anchor_)}handleUpEvent(t){if(this.targetPointers.length<2){const e=t.map.getView(),i=this.lastScaleDelta_>1?1:-1;return e.endInteraction(this.duration_,i),!1}return!0}handleDownEvent(t){if(this.targetPointers.length>=2){const e=t.map;return this.anchor_=null,this.lastDistance_=void 0,this.lastScaleDelta_=1,this.handlingDownUpSequence||e.getView().beginInteraction(),!0}return!1}};function il(t){t=t||{};const e=new $,i=new ns(-.005,.05,100);(void 0===t.altShiftDragRotate||t.altShiftDragRotate)&&e.push(new Ga);(void 0===t.doubleClickZoom||t.doubleClickZoom)&&e.push(new xa({delta:t.zoomDelta,duration:t.zoomDuration}));(void 0===t.dragPan||t.dragPan)&&e.push(new ka({onFocusOnly:t.onFocusOnly,kinetic:i}));(void 0===t.pinchRotate||t.pinchRotate)&&e.push(new tl);(void 0===t.pinchZoom||t.pinchZoom)&&e.push(new el({duration:t.zoomDuration}));(void 0===t.keyboard||t.keyboard)&&(e.push(new $a),e.push(new Ja({delta:t.zoomDelta,duration:t.zoomDuration})));(void 0===t.mouseWheelZoom||t.mouseWheelZoom)&&e.push(new Qa({onFocusOnly:t.onFocusOnly,duration:t.zoomDuration}));return(void 0===t.shiftDragZoom||t.shiftDragZoom)&&e.push(new Za({duration:t.zoomDuration})),e}function nl(t,e,i){return void 0===i&&(i=[0,0]),i[0]=t[0]+2*e,i[1]=t[1]+2*e,i}function rl(t){return t[0]>0&&t[1]>0}function sl(t,e,i){return void 0===i&&(i=[0,0]),i[0]=t[0]*e+.5|0,i[1]=t[1]*e+.5|0,i}function ol(t,e){return Array.isArray(t)?t:(void 0===e?e=[t,t]:(e[0]=t,e[1]=t),e)}function al(t){t instanceof no?t.setMapInternal(null):t instanceof zo&&t.getLayers().forEach(al)}function ll(t,e){if(t instanceof no)t.setMapInternal(e);else if(t instanceof zo){const i=t.getLayers().getArray();for(let t=0,n=i.length;tthis.updateSize())),this.controls=e.controls||fa(),this.interactions=e.interactions||il({onFocusOnly:!0}),this.overlays_=e.overlays,this.overlayIdIndex_={},this.renderer_=null,this.postRenderFunctions_=[],this.tileQueue_=new la(this.getTilePriority.bind(this),this.handleTileChange_.bind(this)),this.addChangeListener(ia,this.handleLayerGroupChanged_),this.addChangeListener(sa,this.handleViewChanged_),this.addChangeListener(na,this.handleSizeChanged_),this.addChangeListener(ra,this.handleTargetChanged_),this.setProperties(e.values);const i=this;!t.view||t.view instanceof eo||t.view.then((function(t){i.setView(new eo(t))})),this.controls.addEventListener(Y,(t=>{t.element.setMap(this)})),this.controls.addEventListener(K,(t=>{t.element.setMap(null)})),this.interactions.addEventListener(Y,(t=>{t.element.setMap(this)})),this.interactions.addEventListener(K,(t=>{t.element.setMap(null)})),this.overlays_.addEventListener(Y,(t=>{this.addOverlayInternal_(t.element)})),this.overlays_.addEventListener(K,(t=>{const e=t.element.getId();void 0!==e&&delete this.overlayIdIndex_[e.toString()],t.element.setMap(null)})),this.controls.forEach((t=>{t.setMap(this)})),this.interactions.forEach((t=>{t.setMap(this)})),this.overlays_.forEach(this.addOverlayInternal_.bind(this))}addControl(t){this.getControls().push(t)}addInteraction(t){this.getInteractions().push(t)}addLayer(t){this.getLayerGroup().getLayers().push(t)}handleLayerAdd_(t){ll(t.layer,this)}addOverlay(t){this.getOverlays().push(t)}addOverlayInternal_(t){const e=t.getId();void 0!==e&&(this.overlayIdIndex_[e.toString()]=t),t.setMap(this)}disposeInternal(){this.controls.clear(),this.interactions.clear(),this.overlays_.clear(),this.resizeObserver_.disconnect(),this.setTarget(null),super.disposeInternal()}forEachFeatureAtPixel(t,e,i){if(!this.frameState_||!this.renderer_)return;const n=this.getCoordinateFromPixelInternal(t),r=void 0!==(i=void 0!==i?i:{}).hitTolerance?i.hitTolerance:0,s=void 0!==i.layerFilter?i.layerFilter:p,o=!1!==i.checkWrapped;return this.renderer_.forEachFeatureAtCoordinate(n,this.frameState_,r,o,e,null,s,null)}getFeaturesAtPixel(t,e){const i=[];return this.forEachFeatureAtPixel(t,(function(t){i.push(t)}),e),i}getAllLayers(){const t=[];return function e(i){i.forEach((function(i){i instanceof zo?e(i.getLayers()):t.push(i)}))}(this.getLayers()),t}hasFeatureAtPixel(t,e){if(!this.frameState_||!this.renderer_)return!1;const i=this.getCoordinateFromPixelInternal(t),n=void 0!==(e=void 0!==e?e:{}).layerFilter?e.layerFilter:p,r=void 0!==e.hitTolerance?e.hitTolerance:0,s=!1!==e.checkWrapped;return this.renderer_.hasFeatureAtCoordinate(i,this.frameState_,r,s,n,null)}getEventCoordinate(t){return this.getCoordinateFromPixel(this.getEventPixel(t))}getEventCoordinateInternal(t){return this.getCoordinateFromPixelInternal(this.getEventPixel(t))}getEventPixel(t){const e=this.viewport_.getBoundingClientRect(),i=this.getSize(),n=e.width/i[0],r=e.height/i[1],s="changedTouches"in t?t.changedTouches[0]:t;return[(s.clientX-e.left)/n,(s.clientY-e.top)/r]}getTarget(){return this.get(ra)}getTargetElement(){return this.targetElement_}getCoordinateFromPixel(t){return yn(this.getCoordinateFromPixelInternal(t),this.getView().getProjection())}getCoordinateFromPixelInternal(t){const e=this.frameState_;return e?zt(e.pixelToCoordinateTransform,t.slice()):null}getControls(){return this.controls}getOverlays(){return this.overlays_}getOverlayById(t){const e=this.overlayIdIndex_[t.toString()];return void 0!==e?e:null}getInteractions(){return this.interactions}getLayerGroup(){return this.get(ia)}setLayers(t){const e=this.getLayerGroup();if(t instanceof $)return void e.setLayers(t);const i=e.getLayers();i.clear(),i.extend(t)}getLayers(){return this.getLayerGroup().getLayers()}getLoadingOrNotReady(){const t=this.getLayerGroup().getLayerStatesArray();for(let e=0,i=t.length;e=0;i--){const n=e[i];if(n.getMap()!==this||!n.getActive()||!this.getTargetElement())continue;if(!n.handleEvent(t)||t.propagationStopped)break}}}handlePostRender(){const t=this.frameState_,e=this.tileQueue_;if(!e.isEmpty()){let i=this.maxTilesLoading_,n=i;if(t){const e=t.viewHints;if(e[As]||e[Os]){const e=Date.now()-t.time>8;i=e?0:8,n=e?0:2}}e.getTilesLoading(){this.postRenderTimeoutHandle_=void 0,this.handlePostRender()}),0))}setLayerGroup(t){const e=this.getLayerGroup();e&&this.handleLayerRemove_(new jo("removelayer",e)),this.set(ia,t)}setSize(t){this.set(na,t)}setTarget(t){this.set(ra,t)}setView(t){if(!t||t instanceof eo)return void this.set(sa,t);this.set(sa,new eo);const e=this;t.then((function(t){e.setView(new eo(t))}))}updateSize(){const t=this.getTargetElement();let e;if(t){const i=getComputedStyle(t),n=t.offsetWidth-parseFloat(i.borderLeftWidth)-parseFloat(i.paddingLeft)-parseFloat(i.paddingRight)-parseFloat(i.borderRightWidth),r=t.offsetHeight-parseFloat(i.borderTopWidth)-parseFloat(i.paddingTop)-parseFloat(i.paddingBottom)-parseFloat(i.borderBottomWidth);isNaN(n)||isNaN(r)||(e=[n,r],!rl(e)&&(t.offsetWidth||t.offsetHeight||t.getClientRects().length)&&Ki("No map visible because the map container's width or height are 0."))}const i=this.getSize();!e||i&&g(e,i)||(this.setSize(e),this.updateViewportSize_())}updateViewportSize_(){const t=this.getView();if(t){let e;const i=getComputedStyle(this.viewport_);i.width&&i.height&&(e=[parseInt(i.width,10),parseInt(i.height,10)]),t.setViewportSize(e)}}};const cl="element",ul="map",dl="offset",gl="position",fl="positioning";var pl=class extends Z{constructor(t){super(),this.on,this.once,this.un,this.options=t,this.id=t.id,this.insertFirst=void 0===t.insertFirst||t.insertFirst,this.stopEvent=void 0===t.stopEvent||t.stopEvent,this.element=document.createElement("div"),this.element.className=void 0!==t.className?t.className:"ol-overlay-container "+lo,this.element.style.position="absolute",this.element.style.pointerEvents="auto",this.autoPan=!0===t.autoPan?{}:t.autoPan||void 0,this.rendered={transform_:"",visible:!0},this.mapPostrenderListenerKey=null,this.addChangeListener(cl,this.handleElementChanged),this.addChangeListener(ul,this.handleMapChanged),this.addChangeListener(dl,this.handleOffsetChanged),this.addChangeListener(gl,this.handlePositionChanged),this.addChangeListener(fl,this.handlePositioningChanged),void 0!==t.element&&this.setElement(t.element),this.setOffset(void 0!==t.offset?t.offset:[0,0]),this.setPositioning(t.positioning||"top-left"),void 0!==t.position&&this.setPosition(t.position)}getElement(){return this.get(cl)}getId(){return this.id}getMap(){return this.get(ul)||null}getOffset(){return this.get(dl)}getPosition(){return this.get(gl)}getPositioning(){return this.get(fl)}handleElementChanged(){Tt(this.element);const t=this.getElement();t&&this.element.appendChild(t)}handleMapChanged(){this.mapPostrenderListenerKey&&(Et(this.element),G(this.mapPostrenderListenerKey),this.mapPostrenderListenerKey=null);const t=this.getMap();if(t){this.mapPostrenderListenerKey=D(t,$o,this.render,this),this.updatePixelPosition();const e=this.stopEvent?t.getOverlayContainerStopEvent():t.getOverlayContainer();this.insertFirst?e.insertBefore(this.element,e.childNodes[0]||null):e.appendChild(this.element),this.performAutoPan()}}render(){this.updatePixelPosition()}handleOffsetChanged(){this.updatePixelPosition()}handlePositionChanged(){this.updatePixelPosition(),this.performAutoPan()}handlePositioningChanged(){this.updatePixelPosition()}setElement(t){this.set(cl,t)}setMap(t){this.set(ul,t)}setOffset(t){this.set(dl,t)}setPosition(t){this.set(gl,t)}performAutoPan(){this.autoPan&&this.panIntoView(this.autoPan)}panIntoView(t){const e=this.getMap();if(!e||!e.getTargetElement()||!this.get(gl))return;const i=this.getRect(e.getTargetElement(),e.getSize()),n=this.getElement(),r=this.getRect(n,[vt(n),St(n)]),s=void 0===(t=t||{}).margin?20:t.margin;if(!re(i,r)){const n=r[0]-i[0],o=i[2]-r[2],a=r[1]-i[1],l=i[3]-r[3],h=[0,0];if(n<0?h[0]=n-s:o<0&&(h[0]=Math.abs(o)+s),a<0?h[1]=a-s:l<0&&(h[1]=Math.abs(l)+s),0!==h[0]||0!==h[1]){const i=e.getView().getCenterInternal(),n=e.getPixelFromCoordinateInternal(i);if(!n)return;const r=[n[0]+h[0],n[1]+h[1]],s=t.animation||{};e.getView().animateInternal({center:e.getCoordinateFromPixelInternal(r),duration:s.duration,easing:s.easing})}}}getRect(t,e){const i=t.getBoundingClientRect(),n=i.left+window.pageXOffset,r=i.top+window.pageYOffset;return[n,r,n+e[0],r+e[1]]}setPositioning(t){this.set(fl,t)}setVisible(t){this.rendered.visible!==t&&(this.element.style.display=t?"":"none",this.rendered.visible=t)}updatePixelPosition(){const t=this.getMap(),e=this.getPosition();if(!t||!t.isRendered()||!e)return void this.setVisible(!1);const i=t.getPixelFromCoordinate(e),n=t.getSize();this.updateRenderedPosition(i,n)}updateRenderedPosition(t,e){const i=this.element.style,n=this.getOffset(),r=this.getPositioning();this.setVisible(!0);let s="0%",o="0%";"bottom-right"==r||"center-right"==r||"top-right"==r?s="-100%":"bottom-center"!=r&&"center-center"!=r&&"top-center"!=r||(s="-50%"),"bottom-left"==r||"bottom-center"==r||"bottom-right"==r?o="-100%":"center-left"!=r&&"center-center"!=r&&"center-right"!=r||(o="-50%");const a=`translate(${s}, ${o}) translate(${Math.round(t[0]+n[0])+"px"}, ${Math.round(t[1]+n[1])+"px"})`;this.rendered.transform_!=a&&(this.rendered.transform_=a,i.transform=a)}getOptions(){return this.options}};var ml=class{constructor(t){this.highWaterMark=void 0!==t?t:2048,this.count_=0,this.entries_={},this.oldest_=null,this.newest_=null}canExpireCache(){return this.highWaterMark>0&&this.getCount()>this.highWaterMark}expireCache(t){for(;this.canExpireCache();)this.pop()}clear(){this.count_=0,this.entries_={},this.oldest_=null,this.newest_=null}containsKey(t){return this.entries_.hasOwnProperty(t)}forEach(t){let e=this.oldest_;for(;e;)t(e.value_,e.key_,this),e=e.newer}get(t,e){const i=this.entries_[t];return Mt(void 0!==i,15),i===this.newest_||(i===this.oldest_?(this.oldest_=this.oldest_.newer,this.oldest_.older=null):(i.newer.older=i.older,i.older.newer=i.newer),i.newer=null,i.older=this.newest_,this.newest_.newer=i,this.newest_=i),i.value_}remove(t){const e=this.entries_[t];return Mt(void 0!==e,15),e===this.newest_?(this.newest_=e.older,this.newest_&&(this.newest_.newer=null)):e===this.oldest_?(this.oldest_=e.newer,this.oldest_&&(this.oldest_.older=null)):(e.newer.older=e.older,e.older.newer=e.newer),delete this.entries_[t],--this.count_,e.value_}getCount(){return this.count_}getKeys(){const t=new Array(this.count_);let e,i=0;for(e=this.newest_;e;e=e.older)t[i++]=e.key_;return t}getValues(){const t=new Array(this.count_);let e,i=0;for(e=this.newest_;e;e=e.older)t[i++]=e.value_;return t}peekLast(){return this.oldest_.value_}peekLastKey(){return this.oldest_.key_}peekFirstKey(){return this.newest_.key_}peek(t){if(this.containsKey(t))return this.entries_[t].value_}pop(){const t=this.oldest_;return delete this.entries_[t.key_],t.newer&&(t.newer.older=null),this.oldest_=t.newer,this.oldest_||(this.newest_=null),--this.count_,t.value_}replace(t,e){this.get(t),this.entries_[t].value_=e}set(t,e){Mt(!(t in this.entries_),16);const i={key_:t,newer:null,older:this.newest_,value_:e};this.newest_?this.newest_.newer=i:this.oldest_=i,this.newest_=i,this.entries_[t]=i,++this.count_}setSize(t){this.highWaterMark=t}};function _l(t,e,i,n){return void 0!==n?(n[0]=t,n[1]=e,n[2]=i,n):[t,e,i]}function yl(t,e,i){return t+"/"+e+"/"+i}function xl(t){return yl(t[0],t[1],t[2])}function vl(t){const[e,i,n]=t.substring(t.lastIndexOf("/")+1,t.length).split(",").map(Number);return yl(e,i,n)}function Sl(t){return t.split("/").map(Number)}function wl(t){return(t[1]<i||i>e.getMaxZoom())return!1;const s=e.getFullTileRange(i);return!s||s.containsXY(n,r)}var Tl=class extends ml{clear(){for(;this.getCount()>0;)this.pop().release();super.clear()}expireCache(t){for(;this.canExpireCache();){if(this.peekLast().getKey()in t)break;this.pop().release()}}pruneExceptNewestZ(){if(0===this.getCount())return;const t=Sl(this.peekFirstKey())[0];this.forEach((e=>{e.tileCoord[0]!==t&&(this.remove(xl(e.tileCoord)),e.release())}))}};class Cl{constructor(t,e,i,n){this.minX=t,this.maxX=e,this.minY=i,this.maxY=n}contains(t){return this.containsXY(t[1],t[2])}containsTileRange(t){return this.minX<=t.minX&&t.maxX<=this.maxX&&this.minY<=t.minY&&t.maxY<=this.maxY}containsXY(t,e){return this.minX<=t&&t<=this.maxX&&this.minY<=e&&e<=this.maxY}equals(t){return this.minX==t.minX&&this.minY==t.minY&&this.maxX==t.maxX&&this.maxY==t.maxY}extend(t){t.minXthis.maxX&&(this.maxX=t.maxX),t.minYthis.maxY&&(this.maxY=t.maxY)}getHeight(){return this.maxY-this.minY+1}getSize(){return[this.getWidth(),this.getHeight()]}getWidth(){return this.maxX-this.minX+1}intersects(t){return this.minX<=t.maxX&&this.maxX>=t.minX&&this.minY<=t.maxY&&this.maxY>=t.minY}}function Rl(t,e,i,n,r){return void 0!==r?(r.minX=t,r.maxX=e,r.minY=i,r.maxY=n,r):new Cl(t,e,i,n)}var bl=Cl;const Pl=[];var Il=class extends at{constructor(t,e,i,n){super(t,e,{transition:0}),this.context_={},this.executorGroups={},this.declutterExecutorGroups={},this.loadingSourceTiles=0,this.hitDetectionImageData={},this.replayState_={},this.sourceTiles=[],this.errorTileKeys={},this.wantedResolution,this.getSourceTiles=n.bind(void 0,this),this.wrappedTileCoord=i}getContext(t){const e=V(t);return e in this.context_||(this.context_[e]=yt(1,1,Pl)),this.context_[e]}hasContext(t){return V(t)in this.context_}getImage(t){return this.hasContext(t)?this.getContext(t).canvas:null}getReplayState(t){const e=V(t);return e in this.replayState_||(this.replayState_[e]={dirty:!1,renderedRenderOrder:null,renderedResolution:NaN,renderedRevision:-1,renderedTileResolution:NaN,renderedTileRevision:-1,renderedTileZ:-1}),this.replayState_[e]}load(){this.getSourceTiles()}release(){for(const t in this.context_){const e=this.context_[t];xt(e),Pl.push(e.canvas),delete this.context_[t]}super.release()}};var Fl=class extends at{constructor(t,e,i,n,r,s){super(t,e,s),this.extent=null,this.format_=n,this.features_=null,this.loader_,this.projection=null,this.resolution,this.tileLoadFunction_=r,this.url_=i,this.key=i}getFormat(){return this.format_}getFeatures(){return this.features_}load(){this.state==J&&(this.setState(Q),this.tileLoadFunction_(this,this.url_),this.loader_&&this.loader_(this.extent,this.resolution,this.projection))}onLoad(t,e){this.setFeatures(t)}onError(){this.setState(et)}setFeatures(t){this.features_=t,this.setState(tt)}setLoader(t){this.loader_=t}};function Ll(t){return Array.isArray(t)?us(t):t}let Ml,Al=!1;function Ol(t,e,i,n,r,s,o){const a=new XMLHttpRequest;a.open("GET","function"==typeof t?t(i,n,r):t,!0),"arraybuffer"==e.getType()&&(a.responseType="arraybuffer"),a.withCredentials=Al,a.onload=function(t){if(!a.status||a.status>=200&&a.status<300){const t=e.getType();let n;"json"==t||"text"==t?n=a.responseText:"xml"==t?(n=a.responseXML,n||(n=(new DOMParser).parseFromString(a.responseText,"application/xml"))):"arraybuffer"==t&&(n=a.response),n?s(e.readFeatures(n,{extent:i,featureProjection:r}),e.readProjection(n)):o()}else o()},a.onerror=o,a.send()}function Nl(t,e){return function(i,n,r,s,o){const a=this;Ol(t,e,i,n,r,(function(t,e){a.addFeatures(t),void 0!==s&&s(t)}),o||_)}}function Dl(t,e){return[[-1/0,-1/0,1/0,1/0]]}function kl(t,e,i,n){const r=document.createElement("script"),s="olc_"+V(e);function o(){delete window[s],r.parentNode.removeChild(r)}r.async=!0,r.src=t+(t.includes("?")?"&":"?")+(n||"callback")+"="+s;const a=setTimeout((function(){o(),i&&i()}),1e4);window[s]=function(t){clearTimeout(a),o(),e(t)},document.head.appendChild(r)}class Gl extends Error{constructor(t){super("Unexpected response status: "+t.status),this.name="ResponseError",this.response=t}}class jl extends Error{constructor(t){super("Failed to issue request"),this.name="ClientError",this.client=t}}function Bl(t){return new Promise((function(e,i){const n=new XMLHttpRequest;n.addEventListener("load",(function(t){const n=t.target;if(!n.status||n.status>=200&&n.status<300){let t;try{t=JSON.parse(n.responseText)}catch(t){const e="Error parsing response text as JSON: "+t.message;return void i(new Error(e))}e(t)}else i(new Gl(n))})),n.addEventListener("error",(function(t){i(new jl(t.target))})),n.open("GET",t),n.setRequestHeader("Accept","application/json"),n.send()}))}function Ul(t,e){return e.includes("://")?e:new URL(e,t).href}var zl=class{drawCustom(t,e,i,n){}drawGeometry(t){}setStyle(t){}drawCircle(t,e){}drawFeature(t,e){}drawGeometryCollection(t,e){}drawLineString(t,e){}drawMultiLineString(t,e){}drawMultiPoint(t,e){}drawMultiPolygon(t,e){}drawPoint(t,e){}drawPolygon(t,e){}drawText(t,e){}setFillStrokeStyle(t,e){}setImageStyle(t,e){}setTextStyle(t,e){}};var Xl=class extends zl{constructor(t,e,i,n,r,s,o){super(),this.context_=t,this.pixelRatio_=e,this.extent_=i,this.transform_=n,this.transformRotation_=n?Si(Math.atan2(n[1],n[0]),10):0,this.viewRotation_=r,this.squaredTolerance_=s,this.userTransform_=o,this.contextFillState_=null,this.contextStrokeState_=null,this.contextTextState_=null,this.fillState_=null,this.strokeState_=null,this.image_=null,this.imageAnchorX_=0,this.imageAnchorY_=0,this.imageHeight_=0,this.imageOpacity_=0,this.imageOriginX_=0,this.imageOriginY_=0,this.imageRotateWithView_=!1,this.imageRotation_=0,this.imageScale_=[0,0],this.imageWidth_=0,this.text_="",this.textOffsetX_=0,this.textOffsetY_=0,this.textRotateWithView_=!1,this.textRotation_=0,this.textScale_=[0,0],this.textFillState_=null,this.textStrokeState_=null,this.textState_=null,this.pixelCoordinates_=[],this.tmpLocalTransform_=[1,0,0,1,0,0]}drawImages_(t,e,i,n){if(!this.image_)return;const r=Rn(t,e,i,n,this.transform_,this.pixelCoordinates_),s=this.context_,o=this.tmpLocalTransform_,a=s.globalAlpha;1!=this.imageOpacity_&&(s.globalAlpha=a*this.imageOpacity_);let l=this.imageRotation_;0===this.transformRotation_&&(l-=this.viewRotation_),this.imageRotateWithView_&&(l+=this.viewRotation_);for(let t=0,e=r.length;tt*this.pixelRatio_)),lineDashOffset:(r||0)*this.pixelRatio_,lineJoin:void 0!==s?s:So,lineWidth:(void 0!==o?o:1)*this.pixelRatio_,miterLimit:void 0!==a?a:wo,strokeStyle:Ll(t||Eo)}}else this.strokeState_=null}setImageStyle(t){let e;if(!t||!(e=t.getSize()))return void(this.image_=null);const i=t.getPixelRatio(this.pixelRatio_),n=t.getAnchor(),r=t.getOrigin();this.image_=t.getImage(this.pixelRatio_),this.imageAnchorX_=n[0]*i,this.imageAnchorY_=n[1]*i,this.imageHeight_=e[1]*i,this.imageOpacity_=t.getOpacity(),this.imageOriginX_=r[0],this.imageOriginY_=r[1],this.imageRotateWithView_=t.getRotateWithView(),this.imageRotation_=t.getRotation();const s=t.getScaleArray();this.imageScale_=[s[0]*this.pixelRatio_/i,s[1]*this.pixelRatio_/i],this.imageWidth_=e[0]*i}setTextStyle(t){if(t){const e=t.getFill();if(e){const t=e.getColor();this.textFillState_={fillStyle:Ll(t||yo)}}else this.textFillState_=null;const i=t.getStroke();if(i){const t=i.getColor(),e=i.getLineCap(),n=i.getLineDash(),r=i.getLineDashOffset(),s=i.getLineJoin(),o=i.getWidth(),a=i.getMiterLimit();this.textStrokeState_={lineCap:void 0!==e?e:xo,lineDash:n||vo,lineDashOffset:r||0,lineJoin:void 0!==s?s:So,lineWidth:void 0!==o?o:1,miterLimit:void 0!==a?a:wo,strokeStyle:Ll(t||Eo)}}else this.textStrokeState_=null;const n=t.getFont(),r=t.getOffsetX(),s=t.getOffsetY(),o=t.getRotateWithView(),a=t.getRotation(),l=t.getScaleArray(),h=t.getText(),c=t.getTextAlign(),u=t.getTextBaseline();this.textState_={font:void 0!==n?n:_o,textAlign:void 0!==c?c:To,textBaseline:void 0!==u?u:Co},this.text_=void 0!==h?Array.isArray(h)?h.reduce(((t,e,i)=>t+(i%2?" ":e)),""):h:"",this.textOffsetX_=void 0!==r?this.pixelRatio_*r:0,this.textOffsetY_=void 0!==s?this.pixelRatio_*s:0,this.textRotateWithView_=void 0!==o&&o,this.textRotation_=void 0!==a?a:0,this.textScale_=[this.pixelRatio_*l[0],this.pixelRatio_*l[1]]}else this.text_=""}};const Vl=.5,Wl={Point:function(t,e,i,n,r){const s=i.getImage(),o=i.getText();let a;if(s){if(s.getImageState()!=qr)return;let l=t;if(r){const h=s.getDeclutterMode();if("none"!==h)if(l=r,"obstacle"===h){const r=t.getBuilder(i.getZIndex(),"Image");r.setImageStyle(s,a),r.drawPoint(e,n)}else o&&o.getText()&&(a={})}const h=l.getBuilder(i.getZIndex(),"Image");h.setImageStyle(s,a),h.drawPoint(e,n)}if(o&&o.getText()){let s=t;r&&(s=r);const l=s.getBuilder(i.getZIndex(),"Text");l.setTextStyle(o,a),l.drawText(e,n)}},LineString:function(t,e,i,n,r){const s=i.getStroke();if(s){const r=t.getBuilder(i.getZIndex(),"LineString");r.setFillStrokeStyle(null,s),r.drawLineString(e,n)}const o=i.getText();if(o&&o.getText()){const s=(r||t).getBuilder(i.getZIndex(),"Text");s.setTextStyle(o),s.drawText(e,n)}},Polygon:function(t,e,i,n,r){const s=i.getFill(),o=i.getStroke();if(s||o){const r=t.getBuilder(i.getZIndex(),"Polygon");r.setFillStrokeStyle(s,o),r.drawPolygon(e,n)}const a=i.getText();if(a&&a.getText()){const s=(r||t).getBuilder(i.getZIndex(),"Text");s.setTextStyle(a),s.drawText(e,n)}},MultiPoint:function(t,e,i,n,r){const s=i.getImage(),o=i.getText();let a;if(s){if(s.getImageState()!=qr)return;let l=t;if(r){const h=s.getDeclutterMode();if("none"!==h)if(l=r,"obstacle"===h){const r=t.getBuilder(i.getZIndex(),"Image");r.setImageStyle(s,a),r.drawMultiPoint(e,n)}else o&&o.getText()&&(a={})}const h=l.getBuilder(i.getZIndex(),"Image");h.setImageStyle(s,a),h.drawMultiPoint(e,n)}if(o&&o.getText()){let s=t;r&&(s=r);const l=s.getBuilder(i.getZIndex(),"Text");l.setTextStyle(o,a),l.drawText(e,n)}},MultiLineString:function(t,e,i,n,r){const s=i.getStroke();if(s){const r=t.getBuilder(i.getZIndex(),"LineString");r.setFillStrokeStyle(null,s),r.drawMultiLineString(e,n)}const o=i.getText();if(o&&o.getText()){const s=(r||t).getBuilder(i.getZIndex(),"Text");s.setTextStyle(o),s.drawText(e,n)}},MultiPolygon:function(t,e,i,n,r){const s=i.getFill(),o=i.getStroke();if(o||s){const r=t.getBuilder(i.getZIndex(),"Polygon");r.setFillStrokeStyle(s,o),r.drawMultiPolygon(e,n)}const a=i.getText();if(a&&a.getText()){const s=(r||t).getBuilder(i.getZIndex(),"Text");s.setTextStyle(a),s.drawText(e,n)}},GeometryCollection:function(t,e,i,n,r){const s=e.getGeometriesArray();let o,a;for(o=0,a=s.length;o2||Math.abs(t[4*e+3]-191.25)>2}function ih(t,e,i,n){const r=gn(i,e,t);let s=rn(e,n,i);const o=e.getMetersPerUnit();void 0!==o&&(s*=o);const a=t.getMetersPerUnit();void 0!==a&&(s/=a);const l=t.getExtent();if(!l||ne(l,r)){const e=rn(t,s,r)/s;isFinite(e)&&e>0&&(s/=e)}return s}function nh(t,e,i,n){const r=Te(i);let s=ih(t,e,r,n);return(!isFinite(s)||s<=0)&&ve(i,(function(i){return s=ih(t,e,i,n),isFinite(s)&&s>0})),s}function rh(t,e,i,n,r,s,o,a,l,h,c,u){const d=yt(Math.round(i*t),Math.round(i*e),Ql);if(u||(d.imageSmoothingEnabled=!1),0===l.length)return d.canvas;function g(t){return Math.round(t*i)/i}d.scale(i,i),d.globalCompositeOperation="lighter";const f=[1/0,1/0,-1/0,-1/0];l.forEach((function(t,e,i){fe(f,t.extent)}));const p=Me(f),m=Pe(f),_=yt(Math.round(i*p/n),Math.round(i*m/n),Ql);u||(_.imageSmoothingEnabled=!1);const y=i/n;l.forEach((function(t,e,i){const n=t.extent[0]-f[0],r=-(t.extent[3]-f[3]),s=Me(t.extent),o=Pe(t.extent);t.image.width>0&&t.image.height>0&&_.drawImage(t.image,h,h,t.image.width-2*h,t.image.height-2*h,n*y,r*y,s*y,o*y)}));const x=Fe(o);return a.getTriangles().forEach((function(t,e,r){const o=t.source,a=t.target;let l=o[0][0],h=o[0][1],c=o[1][0],p=o[1][1],m=o[2][0],y=o[2][1];const v=g((a[0][0]-x[0])/s),S=g(-(a[0][1]-x[1])/s),w=g((a[1][0]-x[0])/s),E=g(-(a[1][1]-x[1])/s),T=g((a[2][0]-x[0])/s),C=g(-(a[2][1]-x[1])/s),R=l,b=h;l=0,h=0,c-=R,p-=b,m-=R,y-=b;const P=mi([[c,p,0,0,w-v],[m,y,0,0,T-v],[0,0,c,p,E-S],[0,0,m,y,C-S]]);if(P){if(d.save(),d.beginPath(),function(){if(void 0===Jl){const t=yt(6,6,Ql);t.globalCompositeOperation="lighter",t.fillStyle="rgba(210, 0, 0, 0.75)",th(t,4,5,4,0),th(t,4,5,0,5);const e=t.getImageData(0,0,3,3).data;Jl=eh(e,0)||eh(e,4)||eh(e,8),xt(t),Ql.push(t.canvas)}return Jl}()||!u){d.moveTo(w,E);const t=4,e=v-w,i=S-E;for(let n=0;n=Me(this.sourceProj_.getExtent()),this.sourceWorldWidth_=this.sourceProj_.getExtent()?Me(this.sourceProj_.getExtent()):null,this.targetWorldWidth_=this.targetProj_.getExtent()?Me(this.targetProj_.getExtent()):null;const l=Fe(i),h=Le(i),c=Ee(i),u=we(i),d=this.transformInv_(l),g=this.transformInv_(h),f=this.transformInv_(c),p=this.transformInv_(u),m=10+(s?Math.max(0,Math.ceil(Math.log2(Se(i)/(s*s*256*256)))):0);if(this.addQuad_(l,h,c,u,d,g,f,p,m),this.wrapsXInSource_){let t=1/0;this.triangles_.forEach((function(e,i,n){t=Math.min(t,e.source[0][0],e.source[1][0],e.source[2][0])})),this.triangles_.forEach((e=>{if(Math.max(e.source[0][0],e.source[1][0],e.source[2][0])-t>this.sourceWorldWidth_/2){const i=[[e.source[0][0],e.source[0][1]],[e.source[1][0],e.source[1][1]],[e.source[2][0],e.source[2][1]]];i[0][0]-t>this.sourceWorldWidth_/2&&(i[0][0]-=this.sourceWorldWidth_),i[1][0]-t>this.sourceWorldWidth_/2&&(i[1][0]-=this.sourceWorldWidth_),i[2][0]-t>this.sourceWorldWidth_/2&&(i[2][0]-=this.sourceWorldWidth_);const n=Math.min(i[0][0],i[1][0],i[2][0]);Math.max(i[0][0],i[1][0],i[2][0])-n.5&&c<1;let g=!1;if(l>0){if(this.targetProj_.isGlobal()&&this.targetWorldWidth_){g=Me(Qt([t,e,i,n]))/this.targetWorldWidth_>.25||g}!d&&this.sourceProj_.isGlobal()&&c&&(g=c>.25||g)}if(!g&&this.maxSourceExtent_&&isFinite(h[0])&&isFinite(h[1])&&isFinite(h[2])&&isFinite(h[3])&&!Ae(h,this.maxSourceExtent_))return;let f=0;if(!(g||isFinite(r[0])&&isFinite(r[1])&&isFinite(s[0])&&isFinite(s[1])&&isFinite(o[0])&&isFinite(o[1])&&isFinite(a[0])&&isFinite(a[1])))if(l>0)g=!0;else if(f=(isFinite(r[0])&&isFinite(r[1])?0:8)+(isFinite(s[0])&&isFinite(s[1])?0:4)+(isFinite(o[0])&&isFinite(o[1])?0:2)+(isFinite(a[0])&&isFinite(a[1])?0:1),1!=f&&2!=f&&4!=f&&8!=f)return;if(l>0){if(!g){const e=[(t[0]+i[0])/2,(t[1]+i[1])/2],n=this.transformInv_(e);let s;if(d){s=(xi(r[0],u)+xi(o[0],u))/2-xi(n[0],u)}else s=(r[0]+o[0])/2-n[0];const a=(r[1]+o[1])/2-n[1];g=s*s+a*a>this.errorThresholdSquared_}if(g){if(Math.abs(t[0]-i[0])<=Math.abs(t[1]-i[1])){const h=[(e[0]+i[0])/2,(e[1]+i[1])/2],c=this.transformInv_(h),u=[(n[0]+t[0])/2,(n[1]+t[1])/2],d=this.transformInv_(u);this.addQuad_(t,e,h,u,r,s,c,d,l-1),this.addQuad_(u,h,i,n,d,c,o,a,l-1)}else{const h=[(t[0]+e[0])/2,(t[1]+e[1])/2],c=this.transformInv_(h),u=[(i[0]+n[0])/2,(i[1]+n[1])/2],d=this.transformInv_(u);this.addQuad_(t,h,u,n,r,c,d,a,l-1),this.addQuad_(h,e,i,u,c,s,o,d,l-1)}return}}if(d){if(!this.canWrapXInSource_)return;this.wrapsXInSource_=!0}0==(11&f)&&this.addTriangle_(t,i,n,r,o,a),0==(14&f)&&this.addTriangle_(t,i,e,r,o,s),f&&(0==(13&f)&&this.addTriangle_(e,n,t,s,a,r),0==(7&f)&&this.addTriangle_(e,n,i,s,a,o))}calculateSourceExtent(){const t=[1/0,1/0,-1/0,-1/0];return this.triangles_.forEach((function(e,i,n){const r=e.source;pe(t,r[0]),pe(t,r[1]),pe(t,r[2])})),t}getTriangles(){return this.triangles_}};var ah=class extends at{constructor(t,e,i,n,r,s,o,a,l,h,c,u){super(r,J,{interpolate:!!u}),this.renderEdges_=void 0!==c&&c,this.pixelRatio_=o,this.gutter_=a,this.canvas_=null,this.sourceTileGrid_=e,this.targetTileGrid_=n,this.wrappedTileCoord_=s||r,this.sourceTiles_=[],this.sourcesListenerKeys_=null,this.sourceZ_=0;const d=n.getTileCoordExtent(this.wrappedTileCoord_),g=this.targetTileGrid_.getExtent();let f=this.sourceTileGrid_.getExtent();const p=g?Ie(d,g):d;if(0===Se(p))return void(this.state=it);const m=t.getExtent();m&&(f=f?Ie(f,m):m);const _=n.getResolution(this.wrappedTileCoord_[0]),y=nh(t,i,p,_);if(!isFinite(y)||y<=0)return void(this.state=it);const x=void 0!==h?h:sh;if(this.triangulation_=new oh(t,i,p,f,y*x,_),0===this.triangulation_.getTriangles().length)return void(this.state=it);this.sourceZ_=e.getZForResolution(y);let v=this.triangulation_.calculateSourceExtent();if(f&&(t.canWrapX()?(v[1]=gi(v[1],f[1],f[3]),v[3]=gi(v[3],f[1],f[3])):v=Ie(v,f)),Se(v)){const t=e.getTileRangeForExtentAndZ(v,this.sourceZ_);for(let e=t.minX;e<=t.maxX;e++)for(let i=t.minY;i<=t.maxY;i++){const t=l(this.sourceZ_,e,i,o);t&&this.sourceTiles_.push(t)}0===this.sourceTiles_.length&&(this.state=it)}else this.state=it}getImage(){return this.canvas_}reproject_(){const t=[];if(this.sourceTiles_.forEach((e=>{e&&e.getState()==tt&&t.push({extent:this.sourceTileGrid_.getTileCoordExtent(e.tileCoord),image:e.getImage()})})),this.sourceTiles_.length=0,0===t.length)this.state=et;else{const e=this.wrappedTileCoord_[0],i=this.targetTileGrid_.getTileSize(e),n="number"==typeof i?i:i[0],r="number"==typeof i?i:i[1],s=this.targetTileGrid_.getResolution(e),o=this.sourceTileGrid_.getResolution(this.sourceZ_),a=this.targetTileGrid_.getTileCoordExtent(this.wrappedTileCoord_);this.canvas_=rh(n,r,this.pixelRatio_,o,this.sourceTileGrid_.getExtent(),s,a,this.triangulation_,t,this.gutter_,this.renderEdges_,this.interpolate),this.state=tt}this.changed()}load(){if(this.state==J){this.state=Q,this.changed();let t=0;this.sourcesListenerKeys_=[],this.sourceTiles_.forEach((e=>{const i=e.getState();if(i==J||i==Q){t++;const i=D(e,E,(function(n){const r=e.getState();r!=tt&&r!=et&&r!=it||(G(i),t--,0===t&&(this.unlistenSources_(),this.reproject_()))}),this);this.sourcesListenerKeys_.push(i)}})),0===t?setTimeout(this.reproject_.bind(this),0):this.sourceTiles_.forEach((function(t,e,i){t.getState()==J&&t.load()}))}}unlistenSources_(){this.sourcesListenerKeys_.forEach(G),this.sourcesListenerKeys_=null}release(){this.canvas_&&(xt(this.canvas_.getContext("2d")),Ql.push(this.canvas_),this.canvas_=null),super.release()}},lh="tileloadstart",hh="tileloadend",ch="tileloaderror";function uh(t){return t?Array.isArray(t)?function(e){return t}:"function"==typeof t?t:function(e){return[t]}:null}var dh=class extends Z{constructor(t){super(),this.projection=nn(t.projection),this.attributions_=uh(t.attributions),this.attributionsCollapsible_=void 0===t.attributionsCollapsible||t.attributionsCollapsible,this.loading=!1,this.state_=void 0!==t.state?t.state:"ready",this.wrapX_=void 0!==t.wrapX&&t.wrapX,this.interpolate_=!!t.interpolate,this.viewResolver=null,this.viewRejector=null;const e=this;this.viewPromise_=new Promise((function(t,i){e.viewResolver=t,e.viewRejector=i}))}getAttributions(){return this.attributions_}getAttributionsCollapsible(){return this.attributionsCollapsible_}getProjection(){return this.projection}getResolutions(t){return null}getView(){return this.viewPromise_}getState(){return this.state_}getWrapX(){return this.wrapX_}getInterpolate(){return this.interpolate_}refresh(){this.changed()}setAttributions(t){this.attributions_=uh(t),this.changed()}setState(t){this.state_=t,this.changed()}};const gh=[0,0,0];var fh=class{constructor(t){let e;if(this.minZoom=void 0!==t.minZoom?t.minZoom:0,this.resolutions_=t.resolutions,Mt(f(this.resolutions_,(function(t,e){return e-t}),!0),17),!t.origins)for(let t=0,i=this.resolutions_.length-1;t=this.minZoom;){if(2===this.zoomFactor_?(s=Math.floor(s/2),o=Math.floor(o/2),r=Rl(s,s,o,o,i)):r=this.getTileRangeForExtentAndZ(a,l,i),e(l,r))return!0;--l}return!1}getExtent(){return this.extent_}getMaxZoom(){return this.maxZoom}getMinZoom(){return this.minZoom}getOrigin(t){return this.origin_?this.origin_:this.origins_[t]}getResolution(t){return this.resolutions_[t]}getResolutions(){return this.resolutions_}getTileCoordChildTileRange(t,e,i){if(t[0]this.maxZoom||e0?n:Math.max(s/i[0],r/i[1]);const o=e+1,a=new Array(o);for(let t=0;ti.highWaterMark&&(i.highWaterMark=t)}useTile(t,e,i,n){}};function Th(t,e){const i=/\{z\}/g,n=/\{x\}/g,r=/\{y\}/g,s=/\{-y\}/g;return function(o,a,l){if(o)return t.replace(i,o[0].toString()).replace(n,o[1].toString()).replace(r,o[2].toString()).replace(s,(function(){const t=o[0],i=e.getFullTileRange(t);Mt(i,55);return(i.getHeight()-o[2]-1).toString()}))}}function Ch(t,e){const i=t.length,n=new Array(i);for(let r=0;rthis.getTileInternal(t,e,i,n,s)),this.reprojectionErrorThreshold_,this.renderReprojectionEdges_,this.getInterpolate());return f.key=c,l?(f.interimTile=l,f.refreshInterimChain(),o.replace(h,f)):o.set(h,f),f}getTileInternal(t,e,i,n,r){let s=null;const o=yl(t,e,i),a=this.getKey();if(this.tileCache.containsKey(o)){if(s=this.tileCache.get(o),s.key!=a){const l=s;s=this.createTile_(t,e,i,n,r,a),l.getState()==J?s.interimTile=l.interimTile:s.interimTile=l,s.refreshInterimChain(),this.tileCache.replace(o,s)}}else s=this.createTile_(t,e,i,n,r,a),this.tileCache.set(o,s);return s}setRenderReprojectionEdges(t){if(this.renderReprojectionEdges_!=t){this.renderReprojectionEdges_=t;for(const t in this.tileCacheForProjection)this.tileCacheForProjection[t].clear();this.changed()}}setTileGridForProjection(t,e){const i=nn(t);if(i){const t=V(i);t in this.tileGridForProjection||(this.tileGridForProjection[t]=e)}}clear(){super.clear();for(const t in this.tileCacheForProjection)this.tileCacheForProjection[t].clear()}};function Ah(t){const e=t[0],i=new Array(e);let n,r,s=1<>=1;return i.join("")}var Oh=class extends Mh{constructor(t){const e=void 0!==t.hidpi&&t.hidpi;super({cacheSize:t.cacheSize,crossOrigin:"anonymous",interpolate:t.interpolate,opaque:!0,projection:nn("EPSG:3857"),reprojectionErrorThreshold:t.reprojectionErrorThreshold,state:"loading",tileLoadFunction:t.tileLoadFunction,tilePixelRatio:e?2:1,wrapX:void 0===t.wrapX||t.wrapX,transition:t.transition,zDirection:t.zDirection}),this.hidpi_=e,this.culture_=void 0!==t.culture?t.culture:"en-us",this.maxZoom_=void 0!==t.maxZoom?t.maxZoom:-1,this.apiKey_=t.key,this.imagerySet_=t.imagerySet,this.placeholderTiles_=t.placeholderTiles;const i="https://dev.virtualearth.net/REST/v1/Imagery/Metadata/"+this.imagerySet_+"?uriScheme=https&include=ImageryProviders&key="+this.apiKey_+"&c="+this.culture_;fetch(i).then((t=>t.json())).then((t=>this.handleImageryMetadataResponse(t)))}getApiKey(){return this.apiKey_}getImagerySet(){return this.imagerySet_}handleImageryMetadataResponse(t){if(200!=t.statusCode||"OK"!=t.statusDescription||"ValidCredentials"!=t.authenticationResultCode||1!=t.resourceSets.length||1!=t.resourceSets[0].resources.length)return void this.setState("error");const e=t.resourceSets[0].resources[0],i=-1==this.maxZoom_?e.zoomMax:this.maxZoom_,n=Sh(this.getProjection()),r=this.hidpi_?2:1,s=e.imageWidth==e.imageHeight?e.imageWidth/r:[e.imageWidth/r,e.imageHeight/r],o=yh({extent:n,minZoom:e.zoomMin,maxZoom:i,tileSize:s});this.tileGrid=o;const a=this.culture_,l=this.hidpi_,h=this.placeholderTiles_;if(this.tileUrlFunction=Rh(e.imageUrlSubdomains.map((function(t){const i=[0,0,0],n=e.imageUrl.replace("{subdomain}",t).replace("{culture}",a);return function(t,e,r){if(!t)return;_l(t[0],t[1],t[2],i);const s=new URL(n.replace("{quadkey}",Ah(i))),o=s.searchParams;return l&&(o.set("dpi","d1"),o.set("device","mobile")),!0===h?o.delete("n"):!1===h&&o.set("n","z"),s.toString()}}))),e.imageryProviders){const t=un(nn("EPSG:4326"),this.getProjection());this.setAttributions((i=>{const n=[],r=i.viewState,s=this.getTileGrid(),o=s.getZForResolution(r.resolution,this.zDirection),a=s.getTileCoordForCoordAndZ(r.center,o)[0];return e.imageryProviders.map((function(e){let r=!1;const s=e.coverageAreas;for(let e=0,n=s.length;e=n.zoomMin&&a<=n.zoomMax){const e=n.bbox;if(Ae(Ge([e[1],e[0],e[3],e[2]],t),i.extent)){r=!0;break}}}r&&n.push(e.attribution)})),n.push('Terms of Use'),n}))}this.setState("ready")}};var Nh=class extends Mh{constructor(t){const e=void 0!==(t=t||{}).projection?t.projection:"EPSG:3857",i=void 0!==t.tileGrid?t.tileGrid:yh({extent:Sh(e),maxResolution:t.maxResolution,maxZoom:t.maxZoom,minZoom:t.minZoom,tileSize:t.tileSize});super({attributions:t.attributions,cacheSize:t.cacheSize,crossOrigin:t.crossOrigin,interpolate:t.interpolate,opaque:t.opaque,projection:e,reprojectionErrorThreshold:t.reprojectionErrorThreshold,tileGrid:i,tileLoadFunction:t.tileLoadFunction,tilePixelRatio:t.tilePixelRatio,tileUrlFunction:t.tileUrlFunction,url:t.url,urls:t.urls,wrapX:void 0===t.wrapX||t.wrapX,transition:t.transition,attributionsCollapsible:t.attributionsCollapsible,zDirection:t.zDirection}),this.gutter_=void 0!==t.gutter?t.gutter:0}getGutter(){return this.gutter_}};var Dh=class extends Nh{constructor(t){super({attributions:t.attributions,cacheSize:t.cacheSize,crossOrigin:t.crossOrigin,maxZoom:void 0!==t.maxZoom?t.maxZoom:18,minZoom:t.minZoom,projection:t.projection,transition:t.transition,wrapX:t.wrapX,zDirection:t.zDirection}),this.account_=t.account,this.mapId_=t.map||"",this.config_=t.config||{},this.templateCache_={},this.initializeMap_()}getConfig(){return this.config_}updateConfig(t){Object.assign(this.config_,t),this.initializeMap_()}setConfig(t){this.config_=t||{},this.initializeMap_()}initializeMap_(){const t=JSON.stringify(this.config_);if(this.templateCache_[t])return void this.applyTemplate_(this.templateCache_[t]);let e="https://"+this.account_+".carto.com/api/v1/map";this.mapId_&&(e+="/named/"+this.mapId_);const i=new XMLHttpRequest;i.addEventListener("load",this.handleInitResponse_.bind(this,t)),i.addEventListener("error",this.handleInitError_.bind(this)),i.open("POST",e),i.setRequestHeader("Content-type","application/json"),i.send(JSON.stringify(this.config_))}handleInitResponse_(t,e){const i=e.target;if(!i.status||i.status>=200&&i.status<300){let e;try{e=JSON.parse(i.responseText)}catch(t){return void this.setState("error")}this.applyTemplate_(e),this.templateCache_[t]=e,this.setState("ready")}else this.setState("error")}handleInitError_(t){this.setState("error")}applyTemplate_(t){const e="https://"+t.cdn_url.https+"/"+this.account_+"/api/v1/map/"+t.layergroupid+"/{z}/{x}/{y}.png";this.setUrl(e)}};function kh(t,e,i,n,r){Gh(t,e,i||0,n||t.length-1,r||Bh)}function Gh(t,e,i,n,r){for(;n>i;){if(n-i>600){var s=n-i+1,o=e-i+1,a=Math.log(s),l=.5*Math.exp(2*a/3),h=.5*Math.sqrt(a*l*(s-l)/s)*(o-s/2<0?-1:1);Gh(t,e,Math.max(i,Math.floor(e-o*l/s+h)),Math.min(n,Math.floor(e+(s-o)*l/s+h)),r)}var c=t[e],u=i,d=n;for(jh(t,i,e),r(t[n],c)>0&&jh(t,i,n);u0;)d--}0===r(t[i],c)?jh(t,i,d):jh(t,++d,n),d<=e&&(i=d+1),e<=d&&(n=d-1)}}function jh(t,e,i){var n=t[e];t[e]=t[i],t[i]=n}function Bh(t,e){return te?1:0}class Uh{constructor(t=9){this._maxEntries=Math.max(4,t),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(t){let e=this.data;const i=[];if(!Jh(t,e))return i;const n=this.toBBox,r=[];for(;e;){for(let s=0;s=0&&r[e].children.length>this._maxEntries;)this._split(r,e),e--;this._adjustParentBBoxes(n,r,e)}_split(t,e){const i=t[e],n=i.children.length,r=this._minEntries;this._chooseSplitAxis(i,r,n);const s=this._chooseSplitIndex(i,r,n),o=Qh(i.children.splice(s,i.children.length-s));o.height=i.height,o.leaf=i.leaf,Xh(i,this.toBBox),Xh(o,this.toBBox),e?t[e-1].children.push(o):this._splitRoot(i,o)}_splitRoot(t,e){this.data=Qh([t,e]),this.data.height=t.height+1,this.data.leaf=!1,Xh(this.data,this.toBBox)}_chooseSplitIndex(t,e,i){let n,r=1/0,s=1/0;for(let o=e;o<=i-e;o++){const e=Vh(t,0,o,this.toBBox),a=Vh(t,o,i,this.toBBox),l=qh(e,a),h=Kh(e)+Kh(a);l=e;n--){const e=t.children[n];Wh(o,t.leaf?r(e):e),a+=Hh(o)}return a}_adjustParentBBoxes(t,e,i){for(let n=i;n>=0;n--)Wh(e[n],t)}_condense(t){for(let e,i=t.length-1;i>=0;i--)0===t[i].children.length?i>0?(e=t[i-1].children,e.splice(e.indexOf(t[i]),1)):this.clear():Xh(t[i],this.toBBox)}}function zh(t,e,i){if(!i)return e.indexOf(t);for(let n=0;n=t.minX&&e.maxY>=t.minY}function Qh(t){return{children:t,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function tc(t,e,i,n,r){const s=[e,i];for(;s.length;){if((i=s.pop())-(e=s.pop())<=n)continue;const o=e+Math.ceil((i-e)/n/2)*n;kh(t,o,e,i,r),s.push(e,o,o,i)}}var ec=class{constructor(t){this.rbush_=new Uh(t),this.items_={}}insert(t,e){const i={minX:t[0],minY:t[1],maxX:t[2],maxY:t[3],value:e};this.rbush_.insert(i),this.items_[V(e)]=i}load(t,e){const i=new Array(e.length);for(let n=0,r=e.length;n{e||(e=!0,this.addFeature(t.element),e=!1)})),t.addEventListener(K,(t=>{e||(e=!0,this.removeFeature(t.element),e=!1)})),this.featuresCollection_=t}clear(t){if(t){for(const t in this.featureChangeKeys_){this.featureChangeKeys_[t].forEach(G)}this.featuresCollection_||(this.featureChangeKeys_={},this.idIndex_={},this.uidIndex_={})}else if(this.featuresRtree_){const t=t=>{this.removeFeatureInternal(t)};this.featuresRtree_.forEach(t);for(const t in this.nullGeometryFeatures_)this.removeFeatureInternal(this.nullGeometryFeatures_[t])}this.featuresCollection_&&this.featuresCollection_.clear(),this.featuresRtree_&&this.featuresRtree_.clear(),this.nullGeometryFeatures_={};const e=new hc(rc);this.dispatchEvent(e),this.changed()}forEachFeature(t){if(this.featuresRtree_)return this.featuresRtree_.forEach(t);this.featuresCollection_&&this.featuresCollection_.forEach(t)}forEachFeatureAtCoordinateDirect(t,e){const i=[t[0],t[1],t[0],t[1]];return this.forEachFeatureInExtent(i,(function(i){if(i.getGeometry().intersectsCoordinate(t))return e(i)}))}forEachFeatureInExtent(t,e){if(this.featuresRtree_)return this.featuresRtree_.forEachInExtent(t,e);this.featuresCollection_&&this.featuresCollection_.forEach(e)}forEachFeatureIntersectingExtent(t,e){return this.forEachFeatureInExtent(t,(function(i){if(i.getGeometry().intersectsExtent(t)){const t=e(i);if(t)return t}}))}getFeaturesCollection(){return this.featuresCollection_}getFeatures(){let t;return this.featuresCollection_?t=this.featuresCollection_.getArray().slice(0):this.featuresRtree_&&(t=this.featuresRtree_.getAll(),S(this.nullGeometryFeatures_)||d(t,Object.values(this.nullGeometryFeatures_))),t}getFeaturesAtCoordinate(t){const e=[];return this.forEachFeatureAtCoordinateDirect(t,(function(t){e.push(t)})),e}getFeaturesInExtent(t,e){if(this.featuresRtree_){if(!(e&&e.canWrapX()&&this.getWrapX()))return this.featuresRtree_.getInExtent(t);const i=Be(t,e);return[].concat(...i.map((t=>this.featuresRtree_.getInExtent(t))))}return this.featuresCollection_?this.featuresCollection_.getArray().slice(0):[]}getClosestFeatureToCoordinate(t,e){const i=t[0],n=t[1];let r=null;const s=[NaN,NaN];let o=1/0;const a=[-1/0,-1/0,1/0,1/0];return e=e||p,this.featuresRtree_.forEachInExtent(a,(function(t){if(e(t)){const e=t.getGeometry(),l=o;if(o=e.closestPointXY(i,n,s,o),o{--this.loadingExtentsCount_,this.dispatchEvent(new hc(ac,void 0,t))}),(()=>{--this.loadingExtentsCount_,this.dispatchEvent(new hc(lc))})),n.insert(s,{extent:s.slice()}))}this.loading=!(this.loader_.length<4)&&this.loadingExtentsCount_>0}refresh(){this.clear(!0),this.loadedExtentsRtree_.clear(),super.refresh()}removeLoadedExtent(t){const e=this.loadedExtentsRtree_;let i;e.forEachInExtent(t,(function(e){if(de(e.extent,t))return i=e,!0})),i&&e.remove(i)}removeFeature(t){if(!t)return;const e=V(t);e in this.nullGeometryFeatures_?delete this.nullGeometryFeatures_[e]:this.featuresRtree_&&this.featuresRtree_.remove(t);this.removeFeatureInternal(t)&&this.changed()}removeFeatureInternal(t){const e=V(t),i=this.featureChangeKeys_[e];if(!i)return;i.forEach(G),delete this.featureChangeKeys_[e];const n=t.getId();return void 0!==n&&delete this.idIndex_[n.toString()],delete this.uidIndex_[e],this.dispatchEvent(new hc(sc,t)),t}removeFromIdIndex_(t){let e=!1;for(const i in this.idIndex_)if(this.idIndex_[i]===t){delete this.idIndex_[i],e=!0;break}return e}setLoader(t){this.loader_=t}setUrl(t){Mt(this.format_,7),this.url_=t,this.setLoader(Nl(t,this.format_))}};var uc=class extends cc{constructor(t){super({attributions:t.attributions,wrapX:t.wrapX}),this.resolution=void 0,this.distance=void 0!==t.distance?t.distance:20,this.minDistance=t.minDistance||0,this.interpolationRatio=0,this.features=[],this.geometryFunction=t.geometryFunction||function(t){const e=t.getGeometry();return Mt(!e||"Point"===e.getType(),10),e},this.createCustomCluster_=t.createCluster,this.source=null,this.boundRefresh_=this.refresh.bind(this),this.updateDistance(this.distance,this.minDistance),this.setSource(t.source||null)}clear(t){this.features.length=0,super.clear(t)}getDistance(){return this.distance}getSource(){return this.source}loadFeatures(t,e,i){this.source.loadFeatures(t,e,i),e!==this.resolution&&(this.resolution=e,this.refresh())}setDistance(t){this.updateDistance(t,this.minDistance)}setMinDistance(t){this.updateDistance(this.distance,t)}getMinDistance(){return this.minDistance}setSource(t){this.source&&this.source.removeEventListener(E,this.boundRefresh_),this.source=t,t&&t.addEventListener(E,this.boundRefresh_),this.refresh()}refresh(){this.clear(),this.cluster(),this.addFeatures(this.features)}updateDistance(t,e){const i=0===t?0:Math.min(e,t)/t,n=t!==this.distance||this.interpolationRatio!==i;this.distance=t,this.minDistance=e,this.interpolationRatio=i,n&&this.refresh()}cluster(){if(void 0===this.resolution||!this.source)return;const t=[1/0,1/0,-1/0,-1/0],e=this.distance*this.resolution,i=this.source.getFeatures(),n={};for(let r=0,s=i.length;r=0;--e){const n=this.geometryFunction(t[e]);n?bi(i,n.getCoordinates()):t.splice(e,1)}Oi(i,1/t.length);const n=Te(e),r=this.interpolationRatio,s=new lr([i[0]*(1-r)+n[0]*r,i[1]*(1-r)+n[1]*r]);return this.createCustomCluster_?this.createCustomCluster_(s,t):new Nt({geometry:s,features:t})}};var dc=class extends Lt{constructor(t){super({tileCoord:t.tileCoord,loader:()=>Promise.resolve(new Uint8Array(4)),interpolate:t.interpolate,transition:t.transition}),this.pixelRatio_=t.pixelRatio,this.gutter_=t.gutter,this.reprojData_=null,this.reprojError_=null,this.reprojSize_=void 0,this.sourceTileGrid_=t.sourceTileGrid,this.targetTileGrid_=t.targetTileGrid,this.wrappedTileCoord_=t.wrappedTileCoord||t.tileCoord,this.sourceTiles_=[],this.sourcesListenerKeys_=null,this.sourceZ_=0;const e=this.targetTileGrid_.getTileCoordExtent(this.wrappedTileCoord_),i=this.targetTileGrid_.getExtent();let n=this.sourceTileGrid_.getExtent();const r=i?Ie(e,i):e;if(0===Se(r))return void(this.state=it);const s=t.sourceProj,o=s.getExtent();o&&(n=n?Ie(n,o):o);const a=this.targetTileGrid_.getResolution(this.wrappedTileCoord_[0]),l=t.targetProj,h=nh(s,l,r,a);if(!isFinite(h)||h<=0)return void(this.state=it);const c=void 0!==t.errorThreshold?t.errorThreshold:sh;if(this.triangulation_=new oh(s,l,r,n,h*c,a),0===this.triangulation_.getTriangles().length)return void(this.state=it);this.sourceZ_=this.sourceTileGrid_.getZForResolution(h);let u=this.triangulation_.calculateSourceExtent();if(n&&(s.canWrapX()?(u[1]=gi(u[1],n[1],n[3]),u[3]=gi(u[3],n[1],n[3])):u=Ie(u,n)),Se(u)){const e=this.sourceTileGrid_.getTileRangeForExtentAndZ(u,this.sourceZ_),i=t.getTileFunction;for(let t=e.minX;t<=e.maxX;t++)for(let n=e.minY;n<=e.maxY;n++){const e=i(this.sourceZ_,t,n,this.pixelRatio_);e&&this.sourceTiles_.push(e)}0===this.sourceTiles_.length&&(this.state=it)}else this.state=it}getSize(){return this.reprojSize_}getData(){return this.reprojData_}getError(){return this.reprojError_}reproject_(){const t=[];if(this.sourceTiles_.forEach((e=>{if(!e||e.getState()!==tt)return;const i=e.getSize(),n=this.gutter_;let r;const s=bt(e.getData());r=s||It(Rt(e.getData()));const o=[i[0]+2*n,i[1]+2*n],a=r instanceof Float32Array,l=o[0]*o[1],h=a?Float32Array:Uint8Array,c=new h(r.buffer),u=h.BYTES_PER_ELEMENT,d=u*c.length/l,g=c.byteLength/o[1],f=Math.floor(g/u/o[0]),p=l*f;let m=c;if(c.length!==p){m=new h(p);let t=0,e=0;const i=o[0]*f;for(let n=0;n=0;--e){const i=[];for(let n=0,r=t.length;n{const i=e.getState();if(i!==J&&i!==Q)return;t++;const n=D(e,E,(function(){const i=e.getState();i!=tt&&i!=et&&i!=it||(G(n),t--,0===t&&(this.unlistenSources_(),this.reproject_()))}),this);this.sourcesListenerKeys_.push(n)})),0===t?setTimeout(this.reproject_.bind(this),0):this.sourceTiles_.forEach((function(t){t.getState()==J&&t.load()}))}unlistenSources_(){this.sourcesListenerKeys_.forEach(G),this.sourcesListenerKeys_=null}};var gc=class extends Eh{constructor(t){const e=void 0===t.projection?"EPSG:3857":t.projection;let i=t.tileGrid;void 0===i&&e&&(i=yh({extent:Sh(e),maxResolution:t.maxResolution,maxZoom:t.maxZoom,minZoom:t.minZoom,tileSize:t.tileSize})),super({cacheSize:.1,attributions:t.attributions,attributionsCollapsible:t.attributionsCollapsible,projection:e,tileGrid:i,opaque:t.opaque,state:t.state,wrapX:t.wrapX,transition:t.transition,interpolate:t.interpolate}),this.gutter_=void 0!==t.gutter?t.gutter:0,this.tileSize_=t.tileSize?ol(t.tileSize):null,this.tileSizes_=null,this.tileLoadingKeys_={},this.loader_=t.loader,this.handleTileChange_=this.handleTileChange_.bind(this),this.bandCount=void 0===t.bandCount?4:t.bandCount,this.tileGridForProjection_={},this.tileCacheForProjection_={}}setTileSizes(t){this.tileSizes_=t}getTileSize(t){if(this.tileSizes_)return this.tileSizes_[t];if(this.tileSize_)return this.tileSize_;const e=this.getTileGrid();return e?ol(e.getTileSize(t)):[256,256]}getGutterForProjection(t){const e=this.getProjection();return!e||cn(e,t)?this.gutter_:0}setLoader(t){this.loader_=t}getReprojTile_(t,e,i,n,r){const s=this.getTileCacheForProjection(n),o=yl(t,e,i);if(s.containsKey(o)){const t=s.get(o);if(t&&t.key==this.getKey())return t}const a=this.getTileGrid(),l=Math.max.apply(null,a.getResolutions().map(((t,e)=>{const i=ol(a.getTileSize(e)),n=this.getTileSize(e);return Math.max(n[0]/i[0],n[1]/i[1])}))),h=this.getTileGridForProjection(r),c=this.getTileGridForProjection(n),u=[t,e,i],d=this.getTileCoordForTileUrlFunction(u,n),g=Object.assign({sourceProj:r,sourceTileGrid:h,targetProj:n,targetTileGrid:c,tileCoord:u,wrappedTileCoord:d,pixelRatio:l,gutter:this.getGutterForProjection(r),getTileFunction:(t,e,i,n)=>this.getTile(t,e,i,n,r)},this.tileOptions),f=new dc(g);return f.key=this.getKey(),f}getTile(t,e,i,n,r){const s=this.getProjection();if(s&&r&&!cn(s,r))return this.getReprojTile_(t,e,i,r,s);const o=this.getTileSize(t),a=yl(t,e,i);if(this.tileCache.containsKey(a))return this.tileCache.get(a);const l=this.loader_;const h=Object.assign({tileCoord:[t,e,i],loader:function(){return x((function(){return l(t,e,i)}))},size:o},this.tileOptions),c=new Lt(h);return c.key=this.getKey(),c.addEventListener(E,this.handleTileChange_),this.tileCache.set(a,c),c}handleTileChange_(t){const e=t.target,i=V(e),n=e.getState();let r;n==Q?(this.tileLoadingKeys_[i]=!0,r=lh):i in this.tileLoadingKeys_&&(delete this.tileLoadingKeys_[i],r=n==et?ch:n==tt?hh:void 0),r&&this.dispatchEvent(new wh(r,e))}getTileGridForProjection(t){const e=this.getProjection();if(this.tileGrid&&(!e||cn(e,t)))return this.tileGrid;const i=V(t);return i in this.tileGridForProjection_||(this.tileGridForProjection_[i]=ph(t)),this.tileGridForProjection_[i]}setTileGridForProjection(t,e){const i=nn(t);if(i){const t=V(i);t in this.tileGridForProjection_||(this.tileGridForProjection_[t]=e)}}getTileCacheForProjection(t){const e=this.getProjection();if(!e||cn(e,t))return this.tileCache;const i=V(t);return i in this.tileCacheForProjection_||(this.tileCacheForProjection_[i]=new Tl(.1)),this.tileCacheForProjection_[i]}expireCache(t,e){const i=this.getTileCacheForProjection(t);this.tileCache.expireCache(this.tileCache==i?e:{});for(const t in this.tileCacheForProjection_){const n=this.tileCacheForProjection_[t];n.expireCache(n==i?e:{})}}clear(){super.clear();for(const t in this.tileCacheForProjection_)this.tileCacheForProjection_[t].clear()}};function fc(t,e){if(!t)return!1;if(!0===t)return!0;if(3!==e.getSamplesPerPixel())return!1;const i=e.fileDirectory.PhotometricInterpretation,n=GeoTIFF.globals.photometricInterpretations;return i===n.CMYK||i===n.YCbCr||i===n.CIELab||i===n.ICCLab}const pc="STATISTICS_MAXIMUM",mc="STATISTICS_MINIMUM";let _c;function yc(t){try{return t.getBoundingBox()}catch(e){return[0,0,t.getWidth(),t.getHeight()]}}function xc(t){try{return t.getOrigin().slice(0,2)}catch(e){return[0,t.getHeight()]}}function vc(t,e){try{return t.getResolution(e)}catch(i){return[e.getWidth()/t.getWidth(),e.getHeight()/t.getHeight()]}}function Sc(t){const e=t.geoKeys;if(!e)return null;if(e.ProjectedCSTypeGeoKey&&32767!==e.ProjectedCSTypeGeoKey){const t="EPSG:"+e.ProjectedCSTypeGeoKey;let i=nn(t);if(!i){const n=ze(e.ProjLinearUnitsGeoKey);n&&(i=new Ve({code:t,units:n}))}return i}if(e.GeographicTypeGeoKey&&32767!==e.GeographicTypeGeoKey){const t="EPSG:"+e.GeographicTypeGeoKey;let i=nn(t);if(!i){const n=ze(e.GeogAngularUnitsGeoKey);n&&(i=new Ve({code:t,units:n}))}return i}return null}function wc(t){return t.getImageCount().then((function(e){const i=new Array(e);for(let n=0;ni*t)throw new Error(n)}function Cc(t){return t instanceof Int8Array?127:t instanceof Uint8Array||t instanceof Uint8ClampedArray?255:t instanceof Int16Array?32767:t instanceof Uint16Array?65535:t instanceof Int32Array?2147483647:t instanceof Uint32Array?4294967295:t instanceof Float32Array?34e37:255}class Rc extends gc{constructor(t){super({state:"loading",tileGrid:null,projection:null,opaque:t.opaque,transition:t.transition,interpolate:!1!==t.interpolate,wrapX:t.wrapX}),this.sourceInfo_=t.sources;const e=this.sourceInfo_.length;this.sourceOptions_=t.sourceOptions,this.sourceImagery_=new Array(e),this.sourceMasks_=new Array(e),this.resolutionFactors_=new Array(e),this.samplesPerPixel_,this.nodataValues_,this.metadata_,this.normalize_=!1!==t.normalize,this.addAlpha_=!1,this.error_=null,this.convertToRGB_=t.convertToRGB||!1,this.setKey(this.sourceInfo_.map((t=>t.url)).join(","));const i=this,n=new Array(e);for(let t=0;t=0;--t){const i=Sc(e[t]);if(i){this.projection=i;break}}}configure_(t){let e,i,n,r,s;const o=new Array(t.length),a=new Array(t.length),l=new Array(t.length);let h=0;const c=t.length;for(let u=0;u{4==(4&(t.fileDirectory.NewSubfileType||0))?d.push(t):c.push(t)}));const g=c.length;if(d.length>0&&d.length!==g)throw new Error(`Expected one mask per image found ${d.length} masks and ${g} images`);let f,p;const m=new Array(g),_=new Array(g),y=new Array(g);a[u]=new Array(g),l[u]=new Array(g);for(let t=0;ty.length&&(h=s.length-y.length);const t=s[s.length-1]/y[y.length-1];this.resolutionFactors_[u]=t;const e=y.map((e=>e*t)),i=`Resolution mismatch for source ${u}, got [${e}] but expected [${s}]`;Tc(s.slice(h,s.length),e,.02,i,this.viewRejector)}else s=y,this.resolutionFactors_[u]=1;n?Tc(n.slice(h,n.length),_,.01,`Tile size mismatch for source ${u}`,this.viewRejector):n=_,r?Tc(r.slice(h,r.length),m,0,`Tile size mismatch for source ${u}`,this.viewRejector):r=m,this.sourceImagery_[u]=c.reverse(),this.sourceMasks_[u]=d.reverse()}for(let t=0,e=this.sourceImagery_.length;tl||s>l;)o.push([Math.ceil(r/l),Math.ceil(s/l)]),l+=l;break;case"truncated":let t=r,e=s;for(;t>l||e>l;)o.push([Math.ceil(t/l),Math.ceil(e/l)]),t>>=1,e>>=1;break;default:Mt(!1,53)}o.push([1,1]),o.reverse();const h=[n],c=[0];for(let t=1,e=o.length;t{f=a,this.changed()})),y.src=_}};const Fc="version1",Lc="version2",Mc="version3",Ac={};Ac[Fc]={level0:{supports:[],formats:[],qualities:["native"]},level1:{supports:["regionByPx","sizeByW","sizeByH","sizeByPct"],formats:["jpg"],qualities:["native"]},level2:{supports:["regionByPx","regionByPct","sizeByW","sizeByH","sizeByPct","sizeByConfinedWh","sizeByWh"],formats:["jpg","png"],qualities:["native","color","grey","bitonal"]}},Ac[Lc]={level0:{supports:[],formats:["jpg"],qualities:["default"]},level1:{supports:["regionByPx","sizeByW","sizeByH","sizeByPct"],formats:["jpg"],qualities:["default"]},level2:{supports:["regionByPx","regionByPct","sizeByW","sizeByH","sizeByPct","sizeByConfinedWh","sizeByDistortedWh","sizeByWh"],formats:["jpg","png"],qualities:["default","bitonal"]}},Ac[Mc]={level0:{supports:[],formats:["jpg"],qualities:["default"]},level1:{supports:["regionByPx","regionSquare","sizeByW","sizeByH","sizeByWh"],formats:["jpg"],qualities:["default"]},level2:{supports:["regionByPx","regionSquare","regionByPct","sizeByW","sizeByH","sizeByPct","sizeByConfinedWh","sizeByWh"],formats:["jpg","png"],qualities:["default"]}},Ac.none={none:{supports:[],formats:[],qualities:[]}};const Oc=/^https?:\/\/library\.stanford\.edu\/iiif\/image-api\/(?:1\.1\/)?compliance\.html#level[0-2]$/,Nc=/^https?:\/\/iiif\.io\/api\/image\/2\/level[0-2](?:\.json)?$/,Dc=/(^https?:\/\/iiif\.io\/api\/image\/3\/level[0-2](?:\.json)?$)|(^level[0-2]$)/;const kc={};kc[Fc]=function(t){let e=t.getComplianceLevelSupportedFeatures();return void 0===e&&(e=Ac[Fc].level0),{url:void 0===t.imageInfo["@id"]?void 0:t.imageInfo["@id"].replace(/\/?(?:info\.json)?$/g,""),supports:e.supports,formats:[...e.formats,void 0===t.imageInfo.formats?[]:t.imageInfo.formats],qualities:[...e.qualities,void 0===t.imageInfo.qualities?[]:t.imageInfo.qualities],resolutions:t.imageInfo.scale_factors,tileSize:void 0!==t.imageInfo.tile_width?void 0!==t.imageInfo.tile_height?[t.imageInfo.tile_width,t.imageInfo.tile_height]:[t.imageInfo.tile_width,t.imageInfo.tile_width]:null!=t.imageInfo.tile_height?[t.imageInfo.tile_height,t.imageInfo.tile_height]:void 0}},kc[Lc]=function(t){const e=t.getComplianceLevelSupportedFeatures(),i=Array.isArray(t.imageInfo.profile)&&t.imageInfo.profile.length>1,n=i&&t.imageInfo.profile[1].supports?t.imageInfo.profile[1].supports:[],r=i&&t.imageInfo.profile[1].formats?t.imageInfo.profile[1].formats:[],s=i&&t.imageInfo.profile[1].qualities?t.imageInfo.profile[1].qualities:[];return{url:t.imageInfo["@id"].replace(/\/?(?:info\.json)?$/g,""),sizes:void 0===t.imageInfo.sizes?void 0:t.imageInfo.sizes.map((function(t){return[t.width,t.height]})),tileSize:void 0===t.imageInfo.tiles?void 0:[t.imageInfo.tiles.map((function(t){return t.width}))[0],t.imageInfo.tiles.map((function(t){return void 0===t.height?t.width:t.height}))[0]],resolutions:void 0===t.imageInfo.tiles?void 0:t.imageInfo.tiles.map((function(t){return t.scaleFactors}))[0],supports:[...e.supports,...n],formats:[...e.formats,...r],qualities:[...e.qualities,...s]}},kc[Mc]=function(t){const e=t.getComplianceLevelSupportedFeatures(),i=void 0===t.imageInfo.extraFormats?e.formats:[...e.formats,...t.imageInfo.extraFormats],n=void 0!==t.imageInfo.preferredFormats&&Array.isArray(t.imageInfo.preferredFormats)&&t.imageInfo.preferredFormats.length>0?t.imageInfo.preferredFormats.filter((function(t){return["jpg","png","gif"].includes(t)})).reduce((function(t,e){return void 0===t&&i.includes(e)?e:t}),void 0):void 0;return{url:t.imageInfo.id,sizes:void 0===t.imageInfo.sizes?void 0:t.imageInfo.sizes.map((function(t){return[t.width,t.height]})),tileSize:void 0===t.imageInfo.tiles?void 0:[t.imageInfo.tiles.map((function(t){return t.width}))[0],t.imageInfo.tiles.map((function(t){return t.height}))[0]],resolutions:void 0===t.imageInfo.tiles?void 0:t.imageInfo.tiles.map((function(t){return t.scaleFactors}))[0],supports:void 0===t.imageInfo.extraFeatures?e.supports:[...e.supports,...t.imageInfo.extraFeatures],formats:i,qualities:void 0===t.imageInfo.extraQualities?e.qualities:[...e.qualities,...t.imageInfo.extraQualities],preferredFormat:n}};var Gc=class{constructor(t){this.setImageInfo(t)}setImageInfo(t){this.imageInfo="string"==typeof t?JSON.parse(t):t}getImageApiVersion(){if(void 0===this.imageInfo)return;let t=this.imageInfo["@context"]||"ol-no-context";"string"==typeof t&&(t=[t]);for(let e=0;e0&&"string"==typeof this.imageInfo.profile[0]&&Nc.test(this.imageInfo.profile[0]))return this.imageInfo.profile[0]}}getComplianceLevelFromProfile(t){const e=this.getComplianceLevelEntryFromProfile(t);if(void 0===e)return;const i=e.match(/level[0-2](?:\.json)?$/g);return Array.isArray(i)?i[0].replace(".json",""):void 0}getComplianceLevelSupportedFeatures(){if(void 0===this.imageInfo)return;const t=this.getImageApiVersion(),e=this.getComplianceLevelFromProfile(t);return void 0===e?Ac.none.none:Ac[t][e]}getTileSourceOptions(t){const e=t||{},i=this.getImageApiVersion();if(void 0===i)return;const n=void 0===i?void 0:kc[i](this);return void 0!==n?{url:n.url,version:i,size:[this.imageInfo.width,this.imageInfo.height],sizes:n.sizes,format:void 0!==e.format&&n.formats.includes(e.format)?e.format:void 0!==n.preferredFormat?n.preferredFormat:"jpg",supports:n.supports,quality:e.quality&&n.qualities.includes(e.quality)?e.quality:n.qualities.includes("native")?"native":"default",resolutions:Array.isArray(n.resolutions)?n.resolutions.sort((function(t,e){return e-t})):void 0,tileSize:n.tileSize}:void 0}};function jc(t){return t.toLocaleString("en",{maximumFractionDigits:10})}var Bc=class extends Mh{constructor(t){const e=t||{};let i=e.url||"";i+=i.lastIndexOf("/")===i.length-1||""===i?"":"/";const n=e.version||Lc,r=e.sizes||[],s=e.size;Mt(null!=s&&Array.isArray(s)&&2==s.length&&!isNaN(s[0])&&s[0]>0&&!isNaN(s[1])&&s[1]>0,60);const o=s[0],a=s[1],l=e.tileSize,h=e.tilePixelRatio||1,c=e.format||"jpg",u=e.quality||(e.version==Fc?"native":"default");let d=e.resolutions||[];const g=e.supports||[],f=e.extent||[0,-a,o,0],p=null!=r&&Array.isArray(r)&&r.length>0,m=void 0!==l&&("number"==typeof l&&Number.isInteger(l)&&l>0||Array.isArray(l)&&l.length>0),_=null!=g&&Array.isArray(g)&&(g.includes("regionByPx")||g.includes("regionByPct"))&&(g.includes("sizeByWh")||g.includes("sizeByH")||g.includes("sizeByW")||g.includes("sizeByPct"));let y,x,v;if(d.sort((function(t,e){return e-t})),m||_)if(null!=l&&("number"==typeof l&&Number.isInteger(l)&&l>0?(y=l,x=l):Array.isArray(l)&&l.length>0&&((1==l.length||null==l[1]&&Number.isInteger(l[0]))&&(y=l[0],x=l[0]),2==l.length&&(Number.isInteger(l[0])&&Number.isInteger(l[1])?(y=l[0],x=l[1]):null==l[0]&&Number.isInteger(l[1])&&(y=l[1],x=l[1])))),void 0!==y&&void 0!==x||(y=ks,x=ks),0==d.length){v=Math.max(Math.ceil(Math.log(o/y)/Math.LN2),Math.ceil(Math.log(a/x)/Math.LN2));for(let t=v;t>=0;t--)d.push(Math.pow(2,t))}else{const t=Math.max(...d);v=Math.round(Math.log(t)/Math.LN2)}else if(y=o,x=a,d=[],p){r.sort((function(t,e){return t[0]-e[0]})),v=-1;const t=[];for(let e=0;e0&&d[d.length-1]==i?t.push(e):(d.push(i),v++)}if(t.length>0)for(let e=0;ev)return;const S=t[1],w=t[2],E=d[f];if(!(void 0===S||void 0===w||void 0===E||S<0||Math.ceil(o/E/y)<=S||w<0||Math.ceil(a/E/x)<=w)){if(_||m){const t=S*y*E,e=w*x*E;let i=y*E,r=x*E,s=y,c=x;if(t+i>o&&(i=o-t),e+r>a&&(r=a-e),t+y*E>o&&(s=Math.floor((o-t+E-1)/E)),e+x*E>a&&(c=Math.floor((a-e+E-1)/E)),0==t&&i==o&&0==e&&r==a)l="full";else if(!_||g.includes("regionByPx"))l=t+","+e+","+i+","+r;else if(g.includes("regionByPct")){l="pct:"+jc(t/o*100)+","+jc(e/a*100)+","+jc(i/o*100)+","+jc(r/a*100)}n!=Mc||_&&!g.includes("sizeByWh")?!_||g.includes("sizeByW")?h=s+",":g.includes("sizeByH")?h=","+c:g.includes("sizeByWh")?h=s+","+c:g.includes("sizeByPct")&&(h="pct:"+jc(100/E)):h=s+","+c}else if(l="full",p){const t=r[f][0],e=r[f][1];h=n==Mc?t==o&&e==a?"max":t+","+e:t==o?"full":t+","}else h=n==Mc?"max":"full";return i+l+"/"+h+"/0/"+u+"."+c}},transition:e.transition}),this.zDirection=e.zDirection}};var Uc=class extends Yr{constructor(t,e,i,n,r,s,o){let a=t.getExtent();a&&t.canWrapX()&&(a=a.slice(),a[0]=-1/0,a[2]=1/0);let l=e.getExtent();l&&e.canWrapX()&&(l=l.slice(),l[0]=-1/0,l[2]=1/0);const h=l?Ie(i,l):i,c=ih(t,e,Te(h),n),u=new oh(t,e,h,a,.5*c,n),d=u.calculateSourceExtent(),g=Oe(d)?null:s(d,c,r),f=g?Kr:Jr,p=g?g.getPixelRatio():1;super(i,n,p,f),this.targetProj_=e,this.maxSourceExtent_=a,this.triangulation_=u,this.targetResolution_=n,this.targetExtent_=i,this.sourceImage_=g,this.sourcePixelRatio_=p,this.interpolate_=o,this.canvas_=null,this.sourceListenerKey_=null}disposeInternal(){this.state==Hr&&this.unlistenSource_(),super.disposeInternal()}getImage(){return this.canvas_}getProjection(){return this.targetProj_}reproject_(){const t=this.sourceImage_.getState();if(t==qr){const t=Me(this.targetExtent_)/this.targetResolution_,e=Pe(this.targetExtent_)/this.targetResolution_;this.canvas_=rh(t,e,this.sourcePixelRatio_,this.sourceImage_.getResolution(),this.maxSourceExtent_,this.targetResolution_,this.targetExtent_,this.triangulation_,[{extent:this.sourceImage_.getExtent(),image:this.sourceImage_.getImage()}],0,void 0,this.interpolate_)}this.state=t,this.changed()}load(){if(this.state==Kr){this.state=Hr,this.changed();const t=this.sourceImage_.getState();t==qr||t==$r?this.reproject_():(this.sourceListenerKey_=D(this.sourceImage_,E,(function(t){const e=this.sourceImage_.getState();e!=qr&&e!=$r||(this.unlistenSource_(),this.reproject_())}),this),this.sourceImage_.load())}}unlistenSource_(){G(this.sourceListenerKey_),this.sourceListenerKey_=null}};const zc="imageloadstart",Xc="imageloadend",Vc="imageloaderror";class Wc extends r{constructor(t,e){super(t),this.image=e}}function Zc(t,e){t.getImage().src=e}var Yc=class extends dh{constructor(t){super({attributions:t.attributions,projection:t.projection,state:t.state,interpolate:void 0===t.interpolate||t.interpolate}),this.on,this.once,this.un,this.resolutions_=void 0!==t.resolutions?t.resolutions:null,this.reprojectedImage_=null,this.reprojectedRevision_=0}getResolutions(){return this.resolutions_}setResolutions(t){this.resolutions_=t}findNearestResolution(t){const e=this.getResolutions();if(e){t=e[c(e,t,0)]}return t}getImage(t,e,i,n){const r=this.getProjection();if(!r||!n||cn(r,n))return r&&(n=r),this.getImageInternal(t,e,i,n);if(this.reprojectedImage_){if(this.reprojectedRevision_==this.getRevision()&&cn(this.reprojectedImage_.getProjection(),n)&&this.reprojectedImage_.getResolution()==e&&de(this.reprojectedImage_.getExtent(),t))return this.reprojectedImage_;this.reprojectedImage_.dispose(),this.reprojectedImage_=null}return this.reprojectedImage_=new Uc(r,n,t,e,i,((t,e,i)=>this.getImageInternal(t,e,i,r)),this.getInterpolate()),this.reprojectedRevision_=this.getRevision(),this.reprojectedImage_}getImageInternal(t,e,i,n){return z()}handleImageChange(t){const e=t.target;let i;switch(e.getState()){case Hr:this.loading=!0,i=zc;break;case qr:this.loading=!1,i=Xc;break;case $r:this.loading=!1,i=Vc;break;default:return}this.hasListener(i)&&this.dispatchEvent(new Wc(i,e))}};function Kc(t,e){const i=[];Object.keys(e).forEach((function(t){null!==e[t]&&void 0!==e[t]&&i.push(t+"="+encodeURIComponent(e[t]))}));const n=i.join("&");return t=t.replace(/[?&]$/,""),(t+=t.includes("?")?"&":"?")+n}var Hc=class extends Yc{constructor(t){super({attributions:(t=t||{}).attributions,interpolate:t.interpolate,projection:t.projection,resolutions:t.resolutions}),this.context_=yt(1,1),this.crossOrigin_=void 0!==t.crossOrigin?t.crossOrigin:null,this.hidpi_=void 0===t.hidpi||t.hidpi,this.url_=t.url,this.imageLoadFunction_=void 0!==t.imageLoadFunction?t.imageLoadFunction:Zc,this.params_=t.params||{},this.image_=null,this.imageSize_=[0,0],this.renderedRevision_=0,this.ratio_=void 0!==t.ratio?t.ratio:1.5}getParams(){return this.params_}getImageInternal(t,e,i,n){if(void 0===this.url_)return null;e=this.findNearestResolution(e),i=this.hidpi_?i:1;const r=this.image_;if(r&&this.renderedRevision_==this.getRevision()&&r.getResolution()==e&&r.getPixelRatio()==i&&re(r.getExtent(),t))return r;const s={F:"image",FORMAT:"PNG32",TRANSPARENT:!0};Object.assign(s,this.params_);const o=((t=t.slice())[0]+t[2])/2,a=(t[1]+t[3])/2;if(1!=this.ratio_){const e=this.ratio_*Me(t)/2,i=this.ratio_*Pe(t)/2;t[0]=o-e,t[1]=a-i,t[2]=o+e,t[3]=a+i}const l=e/i,h=Math.ceil(Me(t)/l),c=Math.ceil(Pe(t)/l);t[0]=o-l*h/2,t[2]=o+l*h/2,t[1]=a-l*c/2,t[3]=a+l*c/2,this.imageSize_[0]=h,this.imageSize_[1]=c;const u=this.getRequestUrl_(t,this.imageSize_,i,n,s);return this.image_=new ts(t,e,i,u,this.crossOrigin_,this.imageLoadFunction_,this.context_),this.renderedRevision_=this.getRevision(),this.image_.addEventListener(E,this.handleImageChange.bind(this)),this.image_}getImageLoadFunction(){return this.imageLoadFunction_}getRequestUrl_(t,e,i,n,r){const s=n.getCode().split(/:(?=\d+$)/).pop();r.SIZE=e[0]+","+e[1],r.BBOX=t.join(","),r.BBOXSR=s,r.IMAGESR=s,r.DPI=Math.round(90*i);const o=this.url_,a=o.replace(/MapServer\/?$/,"MapServer/export").replace(/ImageServer\/?$/,"ImageServer/exportImage");return a==o&&Mt(!1,50),Kc(a,r)}getUrl(){return this.url_}setImageLoadFunction(t){this.image_=null,this.imageLoadFunction_=t,this.changed()}setUrl(t){t!=this.url_&&(this.url_=t,this.image_=null,this.changed())}updateParams(t){Object.assign(this.params_,t),this.image_=null,this.changed()}};var qc=class extends Yc{constructor(t){super({attributions:(t=t||{}).attributions,interpolate:t.interpolate,projection:t.projection,resolutions:t.resolutions,state:t.state}),this.canvasFunction_=t.canvasFunction,this.canvas_=null,this.renderedRevision_=0,this.ratio_=void 0!==t.ratio?t.ratio:1.5}getImageInternal(t,e,i,n){e=this.findNearestResolution(e);let r=this.canvas_;if(r&&this.renderedRevision_==this.getRevision()&&r.getResolution()==e&&r.getPixelRatio()==i&&re(r.getExtent(),t))return r;De(t=t.slice(),this.ratio_);const s=[Me(t)/e*i,Pe(t)/e*i],o=this.canvasFunction_.call(this,t,e,i,s,n);return o&&(r=new es(t,e,i,o)),this.canvas_=r,this.renderedRevision_=this.getRevision(),r}};var $c=class extends Yc{constructor(t){super({interpolate:t.interpolate,projection:t.projection,resolutions:t.resolutions}),this.context_=yt(1,1),this.crossOrigin_=void 0!==t.crossOrigin?t.crossOrigin:null,this.displayDpi_=void 0!==t.displayDpi?t.displayDpi:96,this.params_=t.params||{},this.url_=t.url,this.imageLoadFunction_=void 0!==t.imageLoadFunction?t.imageLoadFunction:Zc,this.hidpi_=void 0===t.hidpi||t.hidpi,this.metersPerUnit_=void 0!==t.metersPerUnit?t.metersPerUnit:1,this.ratio_=void 0!==t.ratio?t.ratio:1,this.useOverlay_=void 0!==t.useOverlay&&t.useOverlay,this.image_=null,this.renderedRevision_=0}getParams(){return this.params_}getImageInternal(t,e,i,n){e=this.findNearestResolution(e),i=this.hidpi_?i:1;let r=this.image_;if(r&&this.renderedRevision_==this.getRevision()&&r.getResolution()==e&&r.getPixelRatio()==i&&re(r.getExtent(),t))return r;1!=this.ratio_&&De(t=t.slice(),this.ratio_);const s=[Me(t)/e*i,Pe(t)/e*i];if(void 0!==this.url_){const o=this.getUrl(this.url_,this.params_,t,s,n);r=new ts(t,e,i,o,this.crossOrigin_,this.imageLoadFunction_,this.context_),r.addEventListener(E,this.handleImageChange.bind(this))}else r=null;return this.image_=r,this.renderedRevision_=this.getRevision(),r}getImageLoadFunction(){return this.imageLoadFunction_}updateParams(t){Object.assign(this.params_,t),this.changed()}getUrl(t,e,i,n,r){const s=function(t,e,i,n){const r=Me(t),s=Pe(t),o=e[0],a=e[1],l=.0254/n;if(a*r>o*s)return r*i/(o*l);return s*i/(a*l)}(i,n,this.metersPerUnit_,this.displayDpi_),o=Te(i),a={OPERATION:this.useOverlay_?"GETDYNAMICMAPOVERLAYIMAGE":"GETMAPIMAGE",VERSION:"2.0.0",LOCALE:"en",CLIENTAGENT:"ol/source/ImageMapGuide source",CLIP:"1",SETDISPLAYDPI:this.displayDpi_,SETDISPLAYWIDTH:Math.round(n[0]),SETDISPLAYHEIGHT:Math.round(n[1]),SETVIEWSCALE:s,SETVIEWCENTERX:o[0],SETVIEWCENTERY:o[1]};return Object.assign(a,e),Kc(t,a)}setImageLoadFunction(t){this.image_=null,this.imageLoadFunction_=t,this.changed()}};var Jc=class extends Yc{constructor(t){const e=void 0!==t.crossOrigin?t.crossOrigin:null,i=void 0!==t.imageLoadFunction?t.imageLoadFunction:Zc;super({attributions:t.attributions,interpolate:t.interpolate,projection:nn(t.projection)}),this.url_=t.url,this.imageExtent_=t.imageExtent,this.image_=new ts(this.imageExtent_,void 0,1,this.url_,e,i,yt(1,1)),this.imageSize_=t.imageSize?t.imageSize:null,this.image_.addEventListener(E,this.handleImageChange.bind(this))}getImageExtent(){return this.imageExtent_}getImageInternal(t,e,i,n){return Ae(t,this.image_.getExtent())?this.image_:null}getUrl(){return this.url_}handleImageChange(t){if(this.image_.getState()==qr){const t=this.image_.getExtent(),e=this.image_.getImage();let i,n;this.imageSize_?(i=this.imageSize_[0],n=this.imageSize_[1]):(i=e.width,n=e.height);const r=Me(t),s=Pe(t),o=r/i,a=s/n;let l=i,h=n;if(o>a?l=Math.round(r/a):h=Math.round(s/o),l!==i||h!==n){const t=yt(l,h);this.getInterpolate()||(t.imageSmoothingEnabled=!1);const r=t.canvas;t.drawImage(e,0,0,i,n,0,0,r.width,r.height),this.image_.setImage(r)}}super.handleImageChange(t)}};const Qc="1.3.0",tu=[101,101];var eu=class extends Yc{constructor(t){super({attributions:(t=t||{}).attributions,interpolate:t.interpolate,projection:t.projection,resolutions:t.resolutions}),this.context_=yt(1,1),this.crossOrigin_=void 0!==t.crossOrigin?t.crossOrigin:null,this.url_=t.url,this.imageLoadFunction_=void 0!==t.imageLoadFunction?t.imageLoadFunction:Zc,this.params_=Object.assign({},t.params),this.v13_=!0,this.updateV13_(),this.serverType_=t.serverType,this.hidpi_=void 0===t.hidpi||t.hidpi,this.image_=null,this.imageSize_=[0,0],this.renderedRevision_=0,this.ratio_=void 0!==t.ratio?t.ratio:1.5}getFeatureInfoUrl(t,e,i,n){if(void 0===this.url_)return;const r=nn(i),s=this.getProjection();s&&s!==r&&(e=ih(s,r,t,e),t=gn(t,r,s));const o=Re(t,e,0,tu),a={SERVICE:"WMS",VERSION:Qc,REQUEST:"GetFeatureInfo",FORMAT:"image/png",TRANSPARENT:!0,QUERY_LAYERS:this.params_.LAYERS};Object.assign(a,this.params_,n);const l=Ei((t[0]-o[0])/e,4),h=Ei((o[3]-t[1])/e,4);return a[this.v13_?"I":"X"]=l,a[this.v13_?"J":"Y"]=h,this.getRequestUrl_(o,tu,1,s||r,a)}getLegendUrl(t,e){if(void 0===this.url_)return;const i={SERVICE:"WMS",VERSION:Qc,REQUEST:"GetLegendGraphic",FORMAT:"image/png"};if(void 0===e||void 0===e.LAYER){const t=this.params_.LAYERS;if(!(!Array.isArray(t)||1===t.length))return;i.LAYER=t}if(void 0!==t){const e=this.getProjection()?this.getProjection().getMetersPerUnit():1,n=28e-5;i.SCALE=t*e/n}return Object.assign(i,e),Kc(this.url_,i)}getParams(){return this.params_}getImageInternal(t,e,i,n){if(void 0===this.url_)return null;e=this.findNearestResolution(e),1==i||this.hidpi_&&void 0!==this.serverType_||(i=1);const r=e/i,s=Te(t),o=Ti(Me(t)/r,4),a=Ti(Pe(t)/r,4),l=Re(s,r,0,[o,a]),h=Re(s,r,0,[o+2*Ti((this.ratio_-1)*o/2,4),a+2*Ti((this.ratio_-1)*a/2,4)]),c=this.image_;if(c&&this.renderedRevision_==this.getRevision()&&c.getResolution()==e&&c.getPixelRatio()==i&&re(c.getExtent(),l))return c;const u={SERVICE:"WMS",VERSION:Qc,REQUEST:"GetMap",FORMAT:"image/png",TRANSPARENT:!0};Object.assign(u,this.params_),this.imageSize_[0]=wi(Me(h)/r,4),this.imageSize_[1]=wi(Pe(h)/r,4);const d=this.getRequestUrl_(h,this.imageSize_,i,n,u);return this.image_=new ts(h,e,i,d,this.crossOrigin_,this.imageLoadFunction_,this.context_),this.renderedRevision_=this.getRevision(),this.image_.addEventListener(E,this.handleImageChange.bind(this)),this.image_}getImageLoadFunction(){return this.imageLoadFunction_}getRequestUrl_(t,e,i,n,r){if(Mt(void 0!==this.url_,9),r[this.v13_?"CRS":"SRS"]=n.getCode(),"STYLES"in this.params_||(r.STYLES=""),1!=i)switch(this.serverType_){case"geoserver":const t=90*i+.5|0;"FORMAT_OPTIONS"in r?r.FORMAT_OPTIONS+=";dpi:"+t:r.FORMAT_OPTIONS="dpi:"+t;break;case"mapserver":r.MAP_RESOLUTION=90*i;break;case"carmentaserver":case"qgis":r.DPI=90*i;break;default:Mt(!1,8)}r.WIDTH=e[0],r.HEIGHT=e[1];const s=n.getAxisOrientation();let o;return o=this.v13_&&"ne"==s.substr(0,2)?[t[1],t[0],t[3],t[2]]:t,r.BBOX=o.join(","),Kc(this.url_,r)}getUrl(){return this.url_}setImageLoadFunction(t){this.image_=null,this.imageLoadFunction_=t,this.changed()}setUrl(t){t!=this.url_&&(this.url_=t,this.image_=null,this.changed())}updateParams(t){Object.assign(this.params_,t),this.updateV13_(),this.image_=null,this.changed()}updateV13_(){const t=this.params_.VERSION||Qc;this.v13_=Ri(t,"1.3")>=0}};const iu={"image/png":!0,"image/jpeg":!0,"image/gif":!0,"image/webp":!0},nu={"application/vnd.mapbox-vector-tile":!0,"application/geo+json":!0};function ru(t,e){let i,n;for(let r=0;rt.maxTileCol||u.tileRowt.maxTileRow)return}Object.assign(u,_);const d=i.replace(/\{(\w+?)\}/g,(function(t,e){return u[e]}));return Ul(y,d)}}}function au(t){return Bl(t.url).then((function(e){return function(t,e){const i=e.tileMatrixSetLimits;let n;if("map"===e.dataType)n=ru(e.links,t.mediaType);else{if("vector"!==e.dataType)throw new Error('Expected tileset data type to be "map" or "vector"');n=su(e.links,t.mediaType,t.supportedMediaTypes)}if(e.tileMatrixSet)return ou(t,e.tileMatrixSet,n,i);const r=e.links.find((t=>"http://www.opengis.net/def/rel/ogc/1.0/tiling-scheme"===t.rel));if(!r)throw new Error("Expected http://www.opengis.net/def/rel/ogc/1.0/tiling-scheme link or tileMatrixSet");const s=r.href;return Bl(Ul(t.url,s)).then((function(e){return ou(t,e,n,i)}))}(t,e)}))}var lu=class extends Mh{constructor(t){super({attributions:t.attributions,cacheSize:t.cacheSize,crossOrigin:t.crossOrigin,interpolate:t.interpolate,projection:t.projection,reprojectionErrorThreshold:t.reprojectionErrorThreshold,state:"loading",tileLoadFunction:t.tileLoadFunction,wrapX:void 0===t.wrapX||t.wrapX,transition:t.transition});au({url:t.url,projection:this.getProjection(),mediaType:t.mediaType,context:t.context||null}).then(this.handleTileSetInfo_.bind(this)).catch(this.handleError_.bind(this))}handleTileSetInfo_(t){this.tileGrid=t.grid,this.setTileUrlFunction(t.urlFunction,t.urlTemplate),this.setState("ready")}handleError_(t){Hi(t),this.setState("error")}};var hu=class extends Fh{constructor(t){const e=t.projection||"EPSG:3857",i=t.extent||Sh(e),n=t.tileGrid||yh({extent:i,maxResolution:t.maxResolution,maxZoom:void 0!==t.maxZoom?t.maxZoom:22,minZoom:t.minZoom,tileSize:t.tileSize||512});super({attributions:t.attributions,attributionsCollapsible:t.attributionsCollapsible,cacheSize:t.cacheSize,interpolate:!0,opaque:!1,projection:e,state:t.state,tileGrid:n,tileLoadFunction:t.tileLoadFunction?t.tileLoadFunction:cu,tileUrlFunction:t.tileUrlFunction,url:t.url,urls:t.urls,wrapX:void 0===t.wrapX||t.wrapX,transition:t.transition,zDirection:void 0===t.zDirection?1:t.zDirection}),this.format_=t.format?t.format:null,this.sourceTileCache=new Tl(this.tileCache.highWaterMark),this.overlaps_=null==t.overlaps||t.overlaps,this.tileClass=t.tileClass?t.tileClass:Fl,this.tileGrids_={}}getFeaturesInExtent(t){const e=[],i=this.tileCache;if(0===i.getCount())return e;const n=Sl(i.peekFirstKey())[0],r=this.tileGrid;return i.forEach((function(i){if(i.tileCoord[0]!==n||i.getState()!==tt)return;const s=i.getSourceTiles();for(let i=0,n=s.length;i{const n=vl(e),r=i.peek(n);if(r){const e=r.sourceTiles;for(let i=0,n=e.length;i{const r=this.tileUrlFunction(n,t,e),s=this.sourceTileCache.containsKey(r)?this.sourceTileCache.get(r):new this.tileClass(n,r?J:it,r,this.format_,this.tileLoadFunction);i.sourceTiles.push(s);const o=s.getState();if(o{this.handleTileChange(e);const n=s.getState();if(n===tt||n===et){const e=s.getKey();e in i.errorTileKeys?s.getState()===tt&&delete i.errorTileKeys[e]:i.loadingSourceTiles--,n===et?i.errorTileKeys[e]=!0:s.removeEventListener(E,t),0===i.loadingSourceTiles&&i.setState(S(i.errorTileKeys)?tt:et)}};s.addEventListener(E,t),i.loadingSourceTiles++}o===J&&(s.extent=l.getTileCoordExtent(n),s.projection=e,s.resolution=l.getResolution(n[0]),this.sourceTileCache.set(r,s),s.load())})),i.loadingSourceTiles||i.setState(i.sourceTiles.some((t=>t.getState()===et))?et:tt)}return i.sourceTiles}getTile(t,e,i,n,r){const s=yl(t,e,i),o=this.getKey();let a;if(this.tileCache.containsKey(s)&&(a=this.tileCache.get(s),a.key===o))return a;const l=[t,e,i];let h=this.getTileCoordForTileUrlFunction(l,r);const c=this.getTileGrid().getExtent(),u=this.getTileGridForProjection(r);if(h&&c){const e=u.getTileCoordExtent(h);te(e,-u.getResolution(t),e),Ae(c,e)||(h=null)}let d=!0;if(null!==h){const e=this.tileGrid,i=u.getResolution(t),s=e.getZForResolution(i,1),o=u.getTileCoordExtent(h);te(o,-i,o),e.forEachTileCoord(o,s,(t=>{d=d&&!this.tileUrlFunction(t,n,r)}))}const g=new Il(l,d?it:J,h,this.getSourceTiles.bind(this,n,r));return g.key=o,a?(g.interimTile=a,g.refreshInterimChain(),this.tileCache.replace(s,g)):this.tileCache.set(s,g),g}getTileGridForProjection(t){const e=t.getCode();let i=this.tileGrids_[e];if(!i){const t=this.tileGrid,n=t.getResolutions().slice(),r=n.map((function(e,i){return t.getOrigin(i)})),s=n.map((function(e,i){return t.getTileSize(i)})),o=Ds+1;for(let t=n.length;t{const s=this.loadedTileCallback.bind(this,i,n);return t.forEachLoadedTile(e,n,r,s)}}forEachFeatureAtCoordinate(t,e,i,n,r){}getLayer(){return this.layer_}handleFontsChanged(){}handleImageChange_(t){const e=t.target;e.getState()!==qr&&e.getState()!==$r||this.renderIfReadyAndVisible()}loadImage(t){let e=t.getState();return e!=qr&&e!=$r&&t.addEventListener(E,this.boundHandleImageChange_),e==Kr&&(t.load(),e=t.getState()),e==qr}renderIfReadyAndVisible(){const t=this.getLayer();t&&t.getVisible()&&"ready"===t.getSourceState()&&t.changed()}disposeInternal(){delete this.layer_,super.disposeInternal()}};const mu=[];let _u=null;var yu=class extends pu{constructor(t){super(t),this.container=null,this.renderedResolution,this.tempTransform=[1,0,0,1,0,0],this.pixelTransform=[1,0,0,1,0,0],this.inversePixelTransform=[1,0,0,1,0,0],this.context=null,this.containerReused=!1,this.pixelContext_=null,this.frameState=null}getImageData(t,e,i){let n;_u||(_u=yt(1,1,void 0,{willReadFrequently:!0})),_u.clearRect(0,0,1,1);try{_u.drawImage(t,e,i,1,1,0,0,1,1),n=_u.getImageData(0,0,1,1).data}catch(t){return _u=null,null}return n}getBackground(t){let e=this.getLayer().getBackground();return"function"==typeof e&&(e=e(t.viewState.resolution)),e||void 0}useContainer(t,e,i){const n=this.getLayer().getClassName();let r,s;if(t&&t.className===n&&(!i||t&&t.style.backgroundColor&&g(hs(t.style.backgroundColor),hs(i)))){const e=t.firstElementChild;e instanceof HTMLCanvasElement&&(s=e.getContext("2d"))}if(s&&s.canvas.style.transform===e?(this.container=t,this.context=s,this.containerReused=!0):this.containerReused?(this.container=null,this.context=null,this.containerReused=!1):this.container&&(this.container.style.backgroundColor=null),!this.container){r=document.createElement("div"),r.className=n;let t=r.style;t.position="absolute",t.width="100%",t.height="100%",s=yt();const e=s.canvas;r.appendChild(e),t=e.style,t.position="absolute",t.left="0",t.transformOrigin="top left",this.container=r,this.context=s}this.containerReused||!i||this.container.style.backgroundColor||(this.container.style.backgroundColor=i)}clipUnrotated(t,e,i){const n=Fe(i),r=Le(i),s=Ee(i),o=we(i);zt(e.coordinateToPixelTransform,n),zt(e.coordinateToPixelTransform,r),zt(e.coordinateToPixelTransform,s),zt(e.coordinateToPixelTransform,o);const a=this.inversePixelTransform;zt(a,n),zt(a,r),zt(a,s),zt(a,o),t.save(),t.beginPath(),t.moveTo(Math.round(n[0]),Math.round(n[1])),t.lineTo(Math.round(r[0]),Math.round(r[1])),t.lineTo(Math.round(s[0]),Math.round(s[1])),t.lineTo(Math.round(o[0]),Math.round(o[1])),t.clip()}dispatchRenderEvent_(t,e,i){const n=this.getLayer();if(n.hasListener(t)){const r=new oo(t,this.inversePixelTransform,i,e);n.dispatchEvent(r)}}preRender(t,e){this.frameState=e,this.dispatchRenderEvent_(Ps,t,e)}postRender(t,e){this.dispatchRenderEvent_(Is,t,e)}getRenderTransform(t,e,i,n,r,s,o){const a=r/2,l=s/2,h=n/e,c=-h,u=-t[0]+o,d=-t[1];return Yt(this.tempTransform,a,l,h,c,-i,u,d)}disposeInternal(){delete this.frameState,super.disposeInternal()}};var xu=class extends yu{constructor(t){super(t),this.image_=null}getImage(){return this.image_?this.image_.getImage():null}prepareFrame(t){const e=t.layerStatesArray[t.layerIndex],i=t.pixelRatio,n=t.viewState,r=n.resolution,s=this.getLayer().getSource(),o=t.viewHints;let a=t.extent;if(void 0!==e.extent&&(a=Ie(a,Sn(e.extent,n.projection))),!o[As]&&!o[Os]&&!Oe(a))if(s){const t=n.projection,e=s.getImage(a,r,i,t);e&&(this.loadImage(e)?this.image_=e:e.getState()===Jr&&(this.image_=null))}else this.image_=null;return!!this.image_}getData(t){const e=this.frameState;if(!e)return null;const i=this.getLayer(),n=zt(e.pixelToCoordinateTransform,t.slice()),r=i.getExtent();if(r&&!ne(r,n))return null;const s=this.image_.getExtent(),o=this.getImage(),a=Me(s),l=Math.floor(o.width*((n[0]-s[0])/a));if(l<0||l>=o.width)return null;const h=Pe(s),c=Math.floor(o.height*((s[3]-n[1])/h));return c<0||c>=o.height?null:this.getImageData(o,l,c)}renderFrame(t,e){const i=this.image_,n=i.getExtent(),r=i.getResolution(),s=i.getPixelRatio(),o=t.layerStatesArray[t.layerIndex],a=t.pixelRatio,l=t.viewState,h=l.center,c=a*r/(l.resolution*s),u=t.extent,d=l.resolution,g=l.rotation,f=Math.round(Me(u)/d*a),p=Math.round(Pe(u)/d*a);Yt(this.pixelTransform,t.size[0]/2,t.size[1]/2,1/a,1/a,g,-f/2,-p/2),Kt(this.inversePixelTransform,this.pixelTransform);const m=$t(this.pixelTransform);this.useContainer(e,m,this.getBackground(t));const _=this.context,y=_.canvas;y.width!=f||y.height!=p?(y.width=f,y.height=p):this.containerReused||_.clearRect(0,0,f,p);let x=!1,v=!0;if(o.extent){const e=Sn(o.extent,l.projection);v=Ae(e,t.extent),x=v&&!re(e,t.extent),x&&this.clipUnrotated(_,t,e)}const S=this.getImage(),w=Yt(this.tempTransform,f/2,p/2,c,c,0,s*(n[0]-h[0])/r,s*(h[1]-n[3])/r);this.renderedResolution=r*a/s;const E=S.width*w[0],T=S.height*w[3];if(this.getLayer().getSource().getInterpolate()||(_.imageSmoothingEnabled=!1),this.preRender(_,t),v&&E>=.5&&T>=.5){const t=w[4],e=w[5],i=o.opacity;let n;1!==i&&(n=_.globalAlpha,_.globalAlpha=i),_.drawImage(S,0,0,+S.width,+S.height,t,e,E,T),1!==i&&(_.globalAlpha=n)}return this.postRender(_,t),x&&_.restore(),_.imageSmoothingEnabled=!0,m!==y.style.transform&&(y.style.transform=m),this.container}};var vu=class extends fu{constructor(t){super(t)}createRenderer(){return new xu(this)}getData(t){return super.getData(t)}},Su="preload",wu="useInterimTilesOnError";var Eu=class extends no{constructor(t){t=t||{};const e=Object.assign({},t);delete e.preload,delete e.useInterimTilesOnError,super(e),this.on,this.once,this.un,this.setPreload(void 0!==t.preload?t.preload:0),this.setUseInterimTilesOnError(void 0===t.useInterimTilesOnError||t.useInterimTilesOnError)}getPreload(){return this.get(Su)}setPreload(t){this.set(Su,t)}getUseInterimTilesOnError(){return this.get(wu)}setUseInterimTilesOnError(t){this.set(wu,t)}getData(t){return super.getData(t)}};var Tu=class extends yu{constructor(t){super(t),this.extentChanged=!0,this.renderedExtent_=null,this.renderedPixelRatio,this.renderedProjection=null,this.renderedRevision,this.renderedTiles=[],this.newTiles_=!1,this.tmpExtent=[1/0,1/0,-1/0,-1/0],this.tmpTileRange_=new bl(0,0,0,0)}isDrawableTile(t){const e=this.getLayer(),i=t.getState(),n=e.getUseInterimTilesOnError();return i==tt||i==it||i==et&&!n}getTile(t,e,i,n){const r=n.pixelRatio,s=n.viewState.projection,o=this.getLayer();let a=o.getSource().getTile(t,e,i,r,s);return a.getState()==et&&o.getUseInterimTilesOnError()&&o.getPreload()>0&&(this.newTiles_=!0),this.isDrawableTile(a)||(a=a.getInterimTile()),a}getData(t){const e=this.frameState;if(!e)return null;const i=this.getLayer(),n=zt(e.pixelToCoordinateTransform,t.slice()),r=i.getExtent();if(r&&!ne(r,n))return null;const s=e.pixelRatio,o=e.viewState.projection,a=e.viewState,l=i.getRenderSource(),h=l.getTileGridForProjection(a.projection),c=l.getTilePixelRatio(e.pixelRatio);for(let t=h.getZForResolution(a.resolution);t>=h.getMinZoom();--t){const e=h.getTileCoordForCoordAndZ(n,t),i=l.getTile(t,e[1],e[2],s,o);if(!(i instanceof is||i instanceof ah)||i instanceof ah&&i.getState()===it)return null;if(i.getState()!==tt)continue;const r=h.getOrigin(t),u=ol(h.getTileSize(t)),d=h.getResolution(t),g=Math.floor(c*((n[0]-r[0])/d-e[1]*u[0])),f=Math.floor(c*((r[1]-n[1])/d-e[2]*u[1])),p=Math.round(c*l.getGutterForProjection(a.projection));return this.getImageData(i.getImage(),g+p,f+p)}return null}loadedTileCallback(t,e,i){return!!this.isDrawableTile(i)&&super.loadedTileCallback(t,e,i)}prepareFrame(t){return!!this.getLayer().getSource()}renderFrame(t,e){const i=t.layerStatesArray[t.layerIndex],n=t.viewState,r=n.projection,s=n.resolution,o=n.center,a=n.rotation,h=t.pixelRatio,c=this.getLayer(),u=c.getSource(),d=u.getRevision(),g=u.getTileGridForProjection(r),f=g.getZForResolution(s,u.zDirection),p=g.getResolution(f);let m=t.extent;const _=t.viewState.resolution,y=u.getTilePixelRatio(h),x=Math.round(Me(m)/_*h),v=Math.round(Pe(m)/_*h),S=i.extent&&Sn(i.extent,r);S&&(m=Ie(m,Sn(i.extent,r)));const w=p*x/2/y,E=p*v/2/y,T=[o[0]-w,o[1]-E,o[0]+w,o[1]+E],C=g.getTileRangeForExtentAndZ(m,f),R={};R[f]={};const b=this.createLoadedTileFinder(u,r,R),P=this.tmpExtent,I=this.tmpTileRange_;this.newTiles_=!1;const F=a?be(n.center,_,a,t.size):void 0;for(let e=C.minX;e<=C.maxX;++e)for(let n=C.minY;n<=C.maxY;++n){if(a&&!g.tileCoordIntersectsViewport([f,e,n],F))continue;const r=this.getTile(f,e,n,t);if(this.isDrawableTile(r)){const e=V(this);if(r.getState()==tt){R[f][r.tileCoord.toString()]=r;let t=r.inTransition(e);t&&1!==i.opacity&&(r.endTransition(e),t=!1),this.newTiles_||!t&&this.renderedTiles.includes(r)||(this.newTiles_=!0)}if(1===r.getAlpha(e,t.time))continue}const s=g.getTileCoordChildTileRange(r.tileCoord,I,P);let o=!1;s&&(o=b(f+1,s)),o||g.forEachTileCoordParentTileRange(r.tileCoord,b,I,P)}const L=p/s*h/y;Yt(this.pixelTransform,t.size[0]/2,t.size[1]/2,1/h,1/h,a,-x/2,-v/2);const M=$t(this.pixelTransform);this.useContainer(e,M,this.getBackground(t));const A=this.context,O=A.canvas;Kt(this.inversePixelTransform,this.pixelTransform),Yt(this.tempTransform,x/2,v/2,L,L,0,-x/2,-v/2),O.width!=x||O.height!=v?(O.width=x,O.height=v):this.containerReused||A.clearRect(0,0,x,v),S&&this.clipUnrotated(A,t,S),u.getInterpolate()||(A.imageSmoothingEnabled=!1),this.preRender(A,t),this.renderedTiles.length=0;let N,D,k,G=Object.keys(R).map(Number);G.sort(l),1!==i.opacity||this.containerReused&&!u.getOpaque(t.viewState.projection)?(N=[],D=[]):G=G.reverse();for(let e=G.length-1;e>=0;--e){const i=G[e],n=u.getTilePixelSize(i,h,r),s=g.getResolution(i)/p,o=n[0]*s*L,a=n[1]*s*L,l=g.getTileCoordForCoordAndZ(Fe(T),i),c=g.getTileCoordExtent(l),d=zt(this.tempTransform,[y*(c[0]-T[0])/p,y*(T[3]-c[3])/p]),m=y*u.getGutterForProjection(r),_=R[i];for(const e in _){const n=_[e],r=n.tileCoord,s=l[1]-r[1],h=Math.round(d[0]-(s-1)*o),c=l[2]-r[2],g=Math.round(d[1]-(c-1)*a),p=Math.round(d[0]-s*o),y=Math.round(d[1]-c*a),x=h-p,v=g-y,S=f===i,w=S&&1!==n.getAlpha(V(this),t.time);let E=!1;if(!w)if(N){k=[p,y,p+x,y,p+x,y+v,p,y+v];for(let t=0,e=N.length;tthis._maxQueueLength;)this._queue.shift().callback(null,null)}_dispatch(){if(this._running||0===this._queue.length)return;const t=this._queue.shift();this._job=t;const e=t.inputs[0].width,i=t.inputs[0].height,n=t.inputs.map((function(t){return t.data.buffer})),r=this._workers.length;if(this._running=r,1===r)return void this._workers[0].postMessage({buffers:n,meta:t.meta,imageOps:this._imageOps,width:e,height:i},n);const s=t.inputs[0].data.length,o=4*Math.ceil(s/4/r);for(let s=0;sStamen Design, under CC BY 3.0.',du],Uu={terrain:{extension:"png",opaque:!0},"terrain-background":{extension:"png",opaque:!0},"terrain-labels":{extension:"png",opaque:!1},"terrain-lines":{extension:"png",opaque:!1},"toner-background":{extension:"png",opaque:!0},toner:{extension:"png",opaque:!0},"toner-hybrid":{extension:"png",opaque:!1},"toner-labels":{extension:"png",opaque:!1},"toner-lines":{extension:"png",opaque:!1},"toner-lite":{extension:"png",opaque:!0},watercolor:{extension:"jpg",opaque:!0}},zu={terrain:{minZoom:0,maxZoom:18},toner:{minZoom:0,maxZoom:20},watercolor:{minZoom:0,maxZoom:18}};var Xu=class extends Nh{constructor(t){const e=t.layer.indexOf("-"),i=-1==e?t.layer:t.layer.slice(0,e),n=zu[i],r=Uu[t.layer],s=void 0!==t.url?t.url:"https://stamen-tiles-{a-d}.a.ssl.fastly.net/"+t.layer+"/{z}/{x}/{y}."+r.extension;super({attributions:Bu,cacheSize:t.cacheSize,crossOrigin:"anonymous",interpolate:t.interpolate,maxZoom:null!=t.maxZoom?t.maxZoom:n.maxZoom,minZoom:null!=t.minZoom?t.minZoom:n.minZoom,opaque:r.opaque,reprojectionErrorThreshold:t.reprojectionErrorThreshold,tileLoadFunction:t.tileLoadFunction,transition:t.transition,url:s,wrapX:t.wrapX,zDirection:t.zDirection})}};var Vu=class extends Mh{constructor(t){super({attributions:(t=t||{}).attributions,cacheSize:t.cacheSize,crossOrigin:t.crossOrigin,interpolate:t.interpolate,projection:t.projection,reprojectionErrorThreshold:t.reprojectionErrorThreshold,tileGrid:t.tileGrid,tileLoadFunction:t.tileLoadFunction,url:t.url,urls:t.urls,wrapX:void 0===t.wrapX||t.wrapX,transition:t.transition,zDirection:t.zDirection}),this.params_=t.params||{},this.hidpi_=void 0===t.hidpi||t.hidpi,this.tmpExtent_=[1/0,1/0,-1/0,-1/0],this.setKey(this.getKeyForParams_())}getKeyForParams_(){let t=0;const e=[];for(const i in this.params_)e[t++]=i+"-"+this.params_[i];return e.join("/")}getParams(){return this.params_}getRequestUrl_(t,e,i,n,r,s){const o=this.urls;if(!o)return;const a=r.getCode().split(/:(?=\d+$)/).pop();let l;if(s.SIZE=e[0]+","+e[1],s.BBOX=i.join(","),s.BBOXSR=a,s.IMAGESR=a,s.DPI=Math.round(s.DPI?s.DPI*n:90*n),1==o.length)l=o[0];else{l=o[xi(wl(t),o.length)]}return Kc(l.replace(/MapServer\/?$/,"MapServer/export").replace(/ImageServer\/?$/,"ImageServer/exportImage"),s)}getTilePixelRatio(t){return this.hidpi_?t:1}updateParams(t){Object.assign(this.params_,t),this.setKey(this.getKeyForParams_())}tileUrlFunction(t,e,i){let n=this.getTileGrid();if(n||(n=this.getTileGridForProjection(i)),n.getResolutions().length<=t[0])return;1==e||this.hidpi_||(e=1);const r=n.getTileCoordExtent(t,this.tmpExtent_);let s=ol(n.getTileSize(t[0]),this.tmpSize);1!=e&&(s=sl(s,e,this.tmpSize));const o={F:"image",FORMAT:"PNG32",TRANSPARENT:!0};return Object.assign(o,this.params_),this.getRequestUrl_(t,s,r,e,i,o)}};var Wu=class extends Nh{constructor(t){super({opaque:!1,projection:(t=t||{}).projection,tileGrid:t.tileGrid,wrapX:void 0===t.wrapX||t.wrapX,zDirection:t.zDirection,url:t.template||"z:{z} x:{x} y:{y}",tileLoadFunction:(t,e)=>{const i=t.getTileCoord()[0],n=ol(this.tileGrid.getTileSize(i)),r=yt(n[0],n[1]);r.strokeStyle="grey",r.strokeRect(.5,.5,n[0]+.5,n[1]+.5),r.fillStyle="grey",r.strokeStyle="white",r.textAlign="center",r.textBaseline="middle",r.font="24px sans-serif",r.lineWidth=4,r.strokeText(e,n[0]/2,n[1]/2,n[0]),r.fillText(e,n[0]/2,n[1]/2,n[0]),t.setImage(r.canvas)}})}};var Zu=class extends Mh{constructor(t){if(super({attributions:t.attributions,cacheSize:t.cacheSize,crossOrigin:t.crossOrigin,interpolate:t.interpolate,projection:nn("EPSG:3857"),reprojectionErrorThreshold:t.reprojectionErrorThreshold,state:"loading",tileLoadFunction:t.tileLoadFunction,wrapX:void 0===t.wrapX||t.wrapX,transition:t.transition,zDirection:t.zDirection}),this.tileJSON_=null,this.tileSize_=t.tileSize,t.url)if(t.jsonp)kl(t.url,this.handleTileJSONResponse.bind(this),this.handleTileJSONError.bind(this));else{const e=new XMLHttpRequest;e.addEventListener("load",this.onXHRLoad_.bind(this)),e.addEventListener("error",this.onXHRError_.bind(this)),e.open("GET",t.url),e.send()}else t.tileJSON?this.handleTileJSONResponse(t.tileJSON):Mt(!1,51)}onXHRLoad_(t){const e=t.target;if(!e.status||e.status>=200&&e.status<300){let t;try{t=JSON.parse(e.responseText)}catch(t){return void this.handleTileJSONError()}this.handleTileJSONResponse(t)}else this.handleTileJSONError()}onXHRError_(t){this.handleTileJSONError()}getTileJSON(){return this.tileJSON_}handleTileJSONResponse(t){const e=nn("EPSG:4326"),i=this.getProjection();let n;if(void 0!==t.bounds){const r=un(e,i);n=Ge(t.bounds,r)}const r=Sh(i),s=t.minzoom||0,o=yh({extent:r,maxZoom:t.maxzoom||22,minZoom:s,tileSize:this.tileSize_});if(this.tileGrid=o,this.tileUrlFunction=Ch(t.tiles,o),t.attribution&&!this.getAttributions()){const e=void 0!==n?n:r;this.setAttributions((function(i){return Ae(e,i.extent)?[t.attribution]:null}))}this.tileJSON_=t,this.setState("ready")}handleTileJSONError(){this.setState("error")}};var Yu=class extends Mh{constructor(t){t=t||{};const e=Object.assign({},t.params),i=!("TRANSPARENT"in e)||e.TRANSPARENT;super({attributions:t.attributions,attributionsCollapsible:t.attributionsCollapsible,cacheSize:t.cacheSize,crossOrigin:t.crossOrigin,interpolate:t.interpolate,opaque:!i,projection:t.projection,reprojectionErrorThreshold:t.reprojectionErrorThreshold,tileClass:t.tileClass,tileGrid:t.tileGrid,tileLoadFunction:t.tileLoadFunction,url:t.url,urls:t.urls,wrapX:void 0===t.wrapX||t.wrapX,transition:t.transition,zDirection:t.zDirection}),this.gutter_=void 0!==t.gutter?t.gutter:0,this.params_=e,this.v13_=!0,this.serverType_=t.serverType,this.hidpi_=void 0===t.hidpi||t.hidpi,this.tmpExtent_=[1/0,1/0,-1/0,-1/0],this.updateV13_(),this.setKey(this.getKeyForParams_())}getFeatureInfoUrl(t,e,i,n){const r=nn(i),s=this.getProjection();let o=this.getTileGrid();o||(o=this.getTileGridForProjection(r));const a=o.getZForResolution(e,this.zDirection),l=o.getTileCoordForCoordAndZ(t,a);if(o.getResolutions().length<=l[0])return;let h=o.getResolution(l[0]),c=o.getTileCoordExtent(l,this.tmpExtent_),u=ol(o.getTileSize(l[0]),this.tmpSize);const d=this.gutter_;0!==d&&(u=nl(u,d,this.tmpSize),c=te(c,h*d,c)),s&&s!==r&&(h=ih(s,r,t,h),c=fn(c,r,s),t=gn(t,r,s));const g={SERVICE:"WMS",VERSION:Qc,REQUEST:"GetFeatureInfo",FORMAT:"image/png",TRANSPARENT:!0,QUERY_LAYERS:this.params_.LAYERS};Object.assign(g,this.params_,n);const f=Math.floor((t[0]-c[0])/h),p=Math.floor((c[3]-t[1])/h);return g[this.v13_?"I":"X"]=f,g[this.v13_?"J":"Y"]=p,this.getRequestUrl_(l,u,c,1,s||r,g)}getLegendUrl(t,e){if(void 0===this.urls[0])return;const i={SERVICE:"WMS",VERSION:Qc,REQUEST:"GetLegendGraphic",FORMAT:"image/png"};if(void 0===e||void 0===e.LAYER){const t=this.params_.LAYERS;if(!(!Array.isArray(t)||1===t.length))return;i.LAYER=t}if(void 0!==t){const e=this.getProjection()?this.getProjection().getMetersPerUnit():1,n=28e-5;i.SCALE=t*e/n}return Object.assign(i,e),Kc(this.urls[0],i)}getGutter(){return this.gutter_}getParams(){return this.params_}getRequestUrl_(t,e,i,n,r,s){const o=this.urls;if(!o)return;if(s.WIDTH=e[0],s.HEIGHT=e[1],s[this.v13_?"CRS":"SRS"]=r.getCode(),"STYLES"in this.params_||(s.STYLES=""),1!=n)switch(this.serverType_){case"geoserver":const t=90*n+.5|0;"FORMAT_OPTIONS"in s?s.FORMAT_OPTIONS+=";dpi:"+t:s.FORMAT_OPTIONS="dpi:"+t;break;case"mapserver":s.MAP_RESOLUTION=90*n;break;case"carmentaserver":case"qgis":s.DPI=90*n;break;default:Mt(!1,52)}const a=r.getAxisOrientation(),l=i;if(this.v13_&&"ne"==a.substr(0,2)){let t;t=i[0],l[0]=i[1],l[1]=t,t=i[2],l[2]=i[3],l[3]=t}let h;if(s.BBOX=l.join(","),1==o.length)h=o[0];else{h=o[xi(wl(t),o.length)]}return Kc(h,s)}getTilePixelRatio(t){return this.hidpi_&&void 0!==this.serverType_?t:1}getKeyForParams_(){let t=0;const e=[];for(const i in this.params_)e[t++]=i+"-"+this.params_[i];return e.join("/")}updateParams(t){Object.assign(this.params_,t),this.updateV13_(),this.setKey(this.getKeyForParams_())}updateV13_(){const t=this.params_.VERSION||Qc;this.v13_=Ri(t,"1.3")>=0}tileUrlFunction(t,e,i){let n=this.getTileGrid();if(n||(n=this.getTileGridForProjection(i)),n.getResolutions().length<=t[0])return;1==e||this.hidpi_&&void 0!==this.serverType_||(e=1);const r=n.getResolution(t[0]);let s=n.getTileCoordExtent(t,this.tmpExtent_),o=ol(n.getTileSize(t[0]),this.tmpSize);const a=this.gutter_;0!==a&&(o=nl(o,a,this.tmpSize),s=te(s,r*a,s)),1!=e&&(o=sl(o,e,this.tmpSize));const l={SERVICE:"WMS",VERSION:Qc,REQUEST:"GetMap",FORMAT:"image/png",TRANSPARENT:!0};return Object.assign(l,this.params_),this.getRequestUrl_(t,o,s,e,i,l)}};class Ku extends at{constructor(t,e,i,n,r,s){super(t,e),this.src_=i,this.extent_=n,this.preemptive_=r,this.grid_=null,this.keys_=null,this.data_=null,this.jsonp_=s}getImage(){return null}getData(t){if(!this.grid_||!this.keys_)return null;const e=(t[0]-this.extent_[0])/(this.extent_[2]-this.extent_[0]),i=(t[1]-this.extent_[1])/(this.extent_[3]-this.extent_[1]),n=this.grid_[Math.floor((1-i)*this.grid_.length)];if("string"!=typeof n)return null;let r=n.charCodeAt(Math.floor(e*n.length));r>=93&&r--,r>=35&&r--,r-=32;let s=null;if(r in this.keys_){const t=this.keys_[r];s=this.data_&&t in this.data_?this.data_[t]:t}return s}forDataAtCoordinate(t,e,i){this.state==it&&!0===i?(this.state=J,k(this,E,(function(i){e(this.getData(t))}),this),this.loadInternal_()):!0===i?setTimeout((()=>{e(this.getData(t))}),0):e(this.getData(t))}getKey(){return this.src_}handleError_(){this.state=et,this.changed()}handleLoad_(t){this.grid_=t.grid,this.keys_=t.keys,this.data_=t.data,this.state=tt,this.changed()}loadInternal_(){if(this.state==J)if(this.state=Q,this.jsonp_)kl(this.src_,this.handleLoad_.bind(this),this.handleError_.bind(this));else{const t=new XMLHttpRequest;t.addEventListener("load",this.onXHRLoad_.bind(this)),t.addEventListener("error",this.onXHRError_.bind(this)),t.open("GET",this.src_),t.send()}}onXHRLoad_(t){const e=t.target;if(!e.status||e.status>=200&&e.status<300){let t;try{t=JSON.parse(e.responseText)}catch(t){return void this.handleError_()}this.handleLoad_(t)}else this.handleError_()}onXHRError_(t){this.handleError_()}load(){this.preemptive_?this.loadInternal_():this.setState(it)}}var Hu=class extends Eh{constructor(t){if(super({projection:nn("EPSG:3857"),state:"loading",zDirection:t.zDirection}),this.preemptive_=void 0===t.preemptive||t.preemptive,this.tileUrlFunction_=bh,this.template_=void 0,this.jsonp_=t.jsonp||!1,t.url)if(this.jsonp_)kl(t.url,this.handleTileJSONResponse.bind(this),this.handleTileJSONError.bind(this));else{const e=new XMLHttpRequest;e.addEventListener("load",this.onXHRLoad_.bind(this)),e.addEventListener("error",this.onXHRError_.bind(this)),e.open("GET",t.url),e.send()}else t.tileJSON?this.handleTileJSONResponse(t.tileJSON):Mt(!1,51)}onXHRLoad_(t){const e=t.target;if(!e.status||e.status>=200&&e.status<300){let t;try{t=JSON.parse(e.responseText)}catch(t){return void this.handleTileJSONError()}this.handleTileJSONResponse(t)}else this.handleTileJSONError()}onXHRError_(t){this.handleTileJSONError()}getTemplate(){return this.template_}forDataAtCoordinateAndResolution(t,e,i,n){if(this.tileGrid){const r=this.tileGrid.getZForResolution(e,this.zDirection),s=this.tileGrid.getTileCoordForCoordAndZ(t,r);this.getTile(s[0],s[1],s[2],1,this.getProjection()).forDataAtCoordinate(t,i,n)}else!0===n?setTimeout((function(){i(null)}),0):i(null)}handleTileJSONError(){this.setState("error")}handleTileJSONResponse(t){const e=nn("EPSG:4326"),i=this.getProjection();let n;if(void 0!==t.bounds){const r=un(e,i);n=Ge(t.bounds,r)}const r=Sh(i),s=t.minzoom||0,o=yh({extent:r,maxZoom:t.maxzoom||22,minZoom:s});this.tileGrid=o,this.template_=t.template;const a=t.grids;if(a){if(this.tileUrlFunction_=Ch(a,o),void 0!==t.attribution){const e=void 0!==n?n:r;this.setAttributions((function(i){return Ae(e,i.extent)?[t.attribution]:null}))}this.setState("ready")}else this.setState("error")}getTile(t,e,i,n,r){const s=yl(t,e,i);if(this.tileCache.containsKey(s))return this.tileCache.get(s);const o=[t,e,i],a=this.getTileCoordForTileUrlFunction(o,r),l=this.tileUrlFunction_(a,n,r),h=new Ku(o,void 0!==l?J:it,void 0!==l?l:"",this.tileGrid.getTileCoordExtent(o),this.preemptive_,this.jsonp_);return this.tileCache.set(s,h),h}useTile(t,e,i){const n=yl(t,e,i);this.tileCache.containsKey(n)&&this.tileCache.get(n)}};class qu extends fh{constructor(t){super({extent:t.extent,origin:t.origin,origins:t.origins,resolutions:t.resolutions,tileSize:t.tileSize,tileSizes:t.tileSizes,sizes:t.sizes}),this.matrixIds_=t.matrixIds}getMatrixId(t){return this.matrixIds_[t]}getMatrixIds(){return this.matrixIds_}}var $u=qu;function Ju(t,e,i){const n=[],r=[],s=[],o=[],a=[];i=void 0!==i?i:[];const l="TileMatrix",h="Identifier",c="ScaleDenominator",u="TopLeftCorner",d=nn(t.SupportedCRS),g=d.getMetersPerUnit(),f="ne"==d.getAxisOrientation().substr(0,2);return t[l].sort((function(t,e){return e[c]-t[c]})),t[l].forEach((function(e){let d;if(d=!(i.length>0)||i.find((function(i){return e[h]==i[l]||!e[h].includes(":")&&t[h]+":"+e[h]===i[l]})),d){r.push(e[h]);const t=28e-5*e[c]/g,i=e.TileWidth,l=e.TileHeight;f?s.push([e[u][1],e[u][0]]):s.push(e[u]),n.push(t),o.push(i==l?i:[i,l]),a.push([e.MatrixWidth,e.MatrixHeight])}})),new qu({extent:e,origins:s,resolutions:n,matrixIds:r,tileSizes:o,sizes:a})}var Qu=class extends Mh{constructor(t){const e=void 0!==t.requestEncoding?t.requestEncoding:"KVP",i=t.tileGrid;let n=t.urls;void 0===n&&void 0!==t.url&&(n=Ph(t.url)),super({attributions:t.attributions,attributionsCollapsible:t.attributionsCollapsible,cacheSize:t.cacheSize,crossOrigin:t.crossOrigin,interpolate:t.interpolate,projection:t.projection,reprojectionErrorThreshold:t.reprojectionErrorThreshold,tileClass:t.tileClass,tileGrid:i,tileLoadFunction:t.tileLoadFunction,tilePixelRatio:t.tilePixelRatio,urls:n,wrapX:void 0!==t.wrapX&&t.wrapX,transition:t.transition,zDirection:t.zDirection}),this.version_=void 0!==t.version?t.version:"1.0.0",this.format_=void 0!==t.format?t.format:"image/jpeg",this.dimensions_=void 0!==t.dimensions?t.dimensions:{},this.layer_=t.layer,this.matrixSet_=t.matrixSet,this.style_=t.style,this.requestEncoding_=e,this.setKey(this.getKeyForDimensions_()),n&&n.length>0&&(this.tileUrlFunction=Rh(n.map(this.createFromWMTSTemplate.bind(this))))}setUrls(t){this.urls=t;const e=t.join("\n");this.setTileUrlFunction(Rh(t.map(this.createFromWMTSTemplate.bind(this))),e)}getDimensions(){return this.dimensions_}getFormat(){return this.format_}getLayer(){return this.layer_}getMatrixSet(){return this.matrixSet_}getRequestEncoding(){return this.requestEncoding_}getStyle(){return this.style_}getVersion(){return this.version_}getKeyForDimensions_(){const t=this.urls?this.urls.slice(0):[];for(const e in this.dimensions_)t.push(e+"-"+this.dimensions_[e]);return t.join("/")}updateDimensions(t){Object.assign(this.dimensions_,t),this.setKey(this.getKeyForDimensions_())}createFromWMTSTemplate(t){const e=this.requestEncoding_,i={layer:this.layer_,style:this.style_,tilematrixset:this.matrixSet_};"KVP"==e&&Object.assign(i,{Service:"WMTS",Request:"GetTile",Version:this.version_,Format:this.format_}),t="KVP"==e?Kc(t,i):t.replace(/\{(\w+?)\}/g,(function(t,e){return e.toLowerCase()in i?i[e.toLowerCase()]:t}));const n=this.tileGrid,r=this.dimensions_;return function(i,s,o){if(!i)return;const a={TileMatrix:n.getMatrixId(i[0]),TileCol:i[1],TileRow:i[2]};Object.assign(a,r);let l=t;return l="KVP"==e?Kc(l,a):l.replace(/\{(\w+?)\}/g,(function(t,e){return a[e]})),l}}};const td=34962,ed=34963,id=35044,nd=35048,rd=5126,sd=["experimental-webgl","webgl","webkit-3d","moz-webgl"];function od(t,e){e=Object.assign({preserveDrawingBuffer:!0,antialias:!ut},e);const i=sd.length;for(let n=0;n{this.uniforms_.push({value:t.uniforms[i],location:e.getUniformLocation(this.renderTargetProgram_,i)})}))}getGL(){return this.gl_}init(t){const e=this.getGL(),i=[e.drawingBufferWidth*this.scaleRatio_,e.drawingBufferHeight*this.scaleRatio_];if(e.bindFramebuffer(e.FRAMEBUFFER,this.getFrameBuffer()),e.bindRenderbuffer(e.RENDERBUFFER,this.getDepthBuffer()),e.viewport(0,0,i[0],i[1]),!this.renderTargetTextureSize_||this.renderTargetTextureSize_[0]!==i[0]||this.renderTargetTextureSize_[1]!==i[1]){this.renderTargetTextureSize_=i;const t=0,n=e.RGBA,r=0,s=e.RGBA,o=e.UNSIGNED_BYTE,a=null;e.bindTexture(e.TEXTURE_2D,this.renderTargetTexture_),e.texImage2D(e.TEXTURE_2D,t,n,i[0],i[1],r,s,o,a),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.renderTargetTexture_,0),e.renderbufferStorage(e.RENDERBUFFER,e.DEPTH_COMPONENT16,i[0],i[1]),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.RENDERBUFFER,this.depthBuffer_)}}apply(t,e,i,n){const r=this.getGL(),s=t.size;if(r.bindFramebuffer(r.FRAMEBUFFER,e?e.getFrameBuffer():null),r.activeTexture(r.TEXTURE0),r.bindTexture(r.TEXTURE_2D,this.renderTargetTexture_),!e){const e=V(r.canvas);if(!t.renderTargets[e]){const i=r.getContextAttributes();i&&i.preserveDrawingBuffer&&(r.clearColor(0,0,0,0),r.clearDepth(1),r.clear(r.COLOR_BUFFER_BIT|r.DEPTH_BUFFER_BIT)),t.renderTargets[e]=!0}}r.disable(r.DEPTH_TEST),r.enable(r.BLEND),r.blendFunc(r.ONE,r.ONE_MINUS_SRC_ALPHA),r.viewport(0,0,r.drawingBufferWidth,r.drawingBufferHeight),r.bindBuffer(r.ARRAY_BUFFER,this.renderTargetVerticesBuffer_),r.useProgram(this.renderTargetProgram_),r.enableVertexAttribArray(this.renderTargetAttribLocation_),r.vertexAttribPointer(this.renderTargetAttribLocation_,2,r.FLOAT,!1,0,0),r.uniform2f(this.renderTargetUniformLocation_,s[0],s[1]),r.uniform1i(this.renderTargetTextureLocation_,0);const o=t.layerStatesArray[t.layerIndex].opacity;r.uniform1f(this.renderTargetOpacityLocation_,o),this.applyUniforms(t),i&&i(r,t),r.drawArrays(r.TRIANGLES,0,6),n&&n(r,t)}getFrameBuffer(){return this.frameBuffer_}getDepthBuffer(){return this.depthBuffer_}applyUniforms(t){const e=this.getGL();let i,n=1;this.uniforms_.forEach((function(r){if(i="function"==typeof r.value?r.value(t):r.value,i instanceof HTMLCanvasElement||i instanceof ImageData)r.texture||(r.texture=e.createTexture()),e.activeTexture(e[`TEXTURE${n}`]),e.bindTexture(e.TEXTURE_2D,r.texture),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),i instanceof ImageData?e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,i.width,i.height,0,e.UNSIGNED_BYTE,new Uint8Array(i.data)):e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,i),e.uniform1i(r.location,n++);else if(Array.isArray(i))switch(i.length){case 2:return void e.uniform2f(r.location,i[0],i[1]);case 3:return void e.uniform3f(r.location,i[0],i[1],i[2]);case 4:return void e.uniform4f(r.location,i[0],i[1],i[2],i[3]);default:return}else"number"==typeof i&&e.uniform1f(r.location,i)}))}};function Ud(){return[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]}function zd(t,e){return t[0]=e[0],t[1]=e[1],t[4]=e[2],t[5]=e[3],t[12]=e[4],t[13]=e[5],t}const Xd={PROJECTION_MATRIX:"u_projectionMatrix",OFFSET_SCALE_MATRIX:"u_offsetScaleMatrix",OFFSET_ROTATION_MATRIX:"u_offsetRotateMatrix",TIME:"u_time",ZOOM:"u_zoom",RESOLUTION:"u_resolution",VIEWPORT_SIZE_PX:"u_viewportSizePx",PIXEL_RATIO:"u_pixelRatio",HIT_DETECTION:"u_hitDetection"},Vd={UNSIGNED_BYTE:5121,UNSIGNED_SHORT:5123,UNSIGNED_INT:5125,FLOAT:rd},Wd={};function Zd(t){return"shared/"+t}let Yd=0;function Kd(t){let e=0;for(let i=0;inew Bd({webGlContext:this.gl_,scaleRatio:t.scaleRatio,vertexShader:t.vertexShader,fragmentShader:t.fragmentShader,uniforms:t.uniforms}))):[new Bd({webGlContext:this.gl_})],this.shaderCompileErrors_=null,this.startTime_=Date.now()}setUniforms(t){this.uniforms_=[];for(const e in t)this.uniforms_.push({name:e,value:t[e]})}canvasCacheKeyMatches(t){return this.canvasCacheKey_===Zd(t)}getExtension(t){if(t in this.extensionCache_)return this.extensionCache_[t];const e=this.gl_.getExtension(t);return this.extensionCache_[t]=e,e}bindBuffer(t){const e=this.gl_,i=V(t);let n=this.bufferCache_[i];if(!n){n={buffer:t,webGlBuffer:e.createBuffer()},this.bufferCache_[i]=n}e.bindBuffer(t.getType(),n.webGlBuffer)}flushBufferData(t){const e=this.gl_;this.bindBuffer(t),e.bufferData(t.getType(),t.getArray(),t.getUsage())}deleteBuffer(t){const e=this.gl_,i=V(t),n=this.bufferCache_[i];n&&!e.isContextLost()&&e.deleteBuffer(n.webGlBuffer),delete this.bufferCache_[i]}disposeInternal(){const t=this.gl_.canvas;t.removeEventListener(Gd,this.boundHandleWebGLContextLost_),t.removeEventListener(jd,this.boundHandleWebGLContextRestored_),function(t){const e=Wd[t];if(!e)return;if(e.users-=1,e.users>0)return;const i=e.context,n=i.getExtension("WEBGL_lose_context");n&&n.loseContext();const r=i.canvas;r.width=1,r.height=1,delete Wd[t]}(this.canvasCacheKey_),delete this.gl_}prepareDraw(t,e,i){const n=this.gl_,r=this.getCanvas(),s=t.size,o=t.pixelRatio;r.width===s[0]*o&&r.height===s[1]*o||(r.width=s[0]*o,r.height=s[1]*o,r.style.width=s[0]+"px",r.style.height=s[1]+"px");for(let e=this.postProcessPasses_.length-1;e>=0;e--)this.postProcessPasses_[e].init(t);n.bindTexture(n.TEXTURE_2D,null),n.clearColor(0,0,0,0),n.depthRange(0,1),n.clearDepth(1),n.clear(n.COLOR_BUFFER_BIT|n.DEPTH_BUFFER_BIT),n.enable(n.BLEND),n.blendFunc(n.ONE,e?n.ZERO:n.ONE_MINUS_SRC_ALPHA),i?(n.enable(n.DEPTH_TEST),n.depthFunc(n.LEQUAL)):n.disable(n.DEPTH_TEST)}bindTexture(t,e,i){const n=this.gl_;n.activeTexture(n.TEXTURE0+e),n.bindTexture(n.TEXTURE_2D,t),n.uniform1i(this.getUniformLocation(i),e)}prepareDrawToRenderTarget(t,e,i,n){const r=this.gl_,s=e.getSize();r.bindFramebuffer(r.FRAMEBUFFER,e.getFramebuffer()),r.bindRenderbuffer(r.RENDERBUFFER,e.getDepthbuffer()),r.viewport(0,0,s[0],s[1]),r.bindTexture(r.TEXTURE_2D,e.getTexture()),r.clearColor(0,0,0,0),r.depthRange(0,1),r.clearDepth(1),r.clear(r.COLOR_BUFFER_BIT|r.DEPTH_BUFFER_BIT),r.enable(r.BLEND),r.blendFunc(r.ONE,i?r.ZERO:r.ONE_MINUS_SRC_ALPHA),n?(r.enable(r.DEPTH_TEST),r.depthFunc(r.LEQUAL)):r.disable(r.DEPTH_TEST)}drawElements(t,e){const i=this.gl_;this.getExtension("OES_element_index_uint");const n=i.UNSIGNED_INT,r=e-t,s=4*t;i.drawElements(i.TRIANGLES,r,n,s)}finalizeDraw(t,e,i){for(let n=0,r=this.postProcessPasses_.length;n{if(i="function"==typeof r.value?r.value(t):r.value,i instanceof HTMLCanvasElement||i instanceof HTMLImageElement||i instanceof ImageData){r.texture||(r.prevValue=void 0,r.texture=e.createTexture()),e.activeTexture(e[`TEXTURE${n}`]),e.bindTexture(e.TEXTURE_2D,r.texture),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE);(!(i instanceof HTMLImageElement)||i.complete)&&r.prevValue!==i&&(r.prevValue=i,e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,i)),e.uniform1i(this.getUniformLocation(r.name),n++)}else if(Array.isArray(i)&&6===i.length)this.setUniformMatrixValue(r.name,zd(this.tmpMat4_,i));else if(Array.isArray(i)&&i.length<=4)switch(i.length){case 2:return void e.uniform2f(this.getUniformLocation(r.name),i[0],i[1]);case 3:return void e.uniform3f(this.getUniformLocation(r.name),i[0],i[1],i[2]);case 4:return void e.uniform4f(this.getUniformLocation(r.name),i[0],i[1],i[2],i[3]);default:return}else"number"==typeof i&&e.uniform1f(this.getUniformLocation(r.name),i)}))}useProgram(t,e){this.gl_.useProgram(t),this.currentProgram_=t,this.applyFrameState(e),this.applyUniforms(e)}compileShader(t,e){const i=this.gl_,n=i.createShader(e);return i.shaderSource(n,t),i.compileShader(n),n}getProgram(t,e){const i=this.gl_,n=this.compileShader(t,i.FRAGMENT_SHADER),r=this.compileShader(e,i.VERTEX_SHADER),s=i.createProgram();if(i.attachShader(s,n),i.attachShader(s,r),i.linkProgram(s),!i.getShaderParameter(n,i.COMPILE_STATUS)){const t=`Fragment shader compilation failed: ${i.getShaderInfoLog(n)}`;throw new Error(t)}if(i.deleteShader(n),!i.getShaderParameter(r,i.COMPILE_STATUS)){const t=`Vertex shader compilation failed: ${i.getShaderInfoLog(r)}`;throw new Error(t)}if(i.deleteShader(r),!i.getProgramParameter(s,i.LINK_STATUS)){const t=`GL program linking failed: ${i.getProgramInfoLog(s)}`;throw new Error(t)}return s}getUniformLocation(t){const e=V(this.currentProgram_);return void 0===this.uniformLocationsByProgram_[e]&&(this.uniformLocationsByProgram_[e]={}),void 0===this.uniformLocationsByProgram_[e][t]&&(this.uniformLocationsByProgram_[e][t]=this.gl_.getUniformLocation(this.currentProgram_,t)),this.uniformLocationsByProgram_[e][t]}getAttributeLocation(t){const e=V(this.currentProgram_);return void 0===this.attribLocationsByProgram_[e]&&(this.attribLocationsByProgram_[e]={}),void 0===this.attribLocationsByProgram_[e][t]&&(this.attribLocationsByProgram_[e][t]=this.gl_.getAttribLocation(this.currentProgram_,t)),this.attribLocationsByProgram_[e][t]}makeProjectionTransform(t,e){const i=t.size,n=t.viewState.rotation,r=t.viewState.resolution,s=t.viewState.center;return Yt(e,0,0,2/(r*i[0]),2/(r*i[1]),-n,-s[0],-s[1]),e}setUniformFloatValue(t,e){this.gl_.uniform1f(this.getUniformLocation(t),e)}setUniformFloatVec2(t,e){this.gl_.uniform2fv(this.getUniformLocation(t),e)}setUniformFloatVec4(t,e){this.gl_.uniform4fv(this.getUniformLocation(t),e)}setUniformMatrixValue(t,e){this.gl_.uniformMatrix4fv(this.getUniformLocation(t),!1,e)}enableAttributeArray_(t,e,i,n,r){const s=this.getAttributeLocation(t);s<0||(this.gl_.enableVertexAttribArray(s),this.gl_.vertexAttribPointer(s,e,i,!1,n,r))}enableAttributes(t){const e=Kd(t);let i=0;for(let n=0;nthis.size_[0]||e>=this.size_[1])return Jd[0]=0,Jd[1]=0,Jd[2]=0,Jd[3]=0,Jd;this.readAll();const i=Math.floor(t)+(this.size_[1]-Math.floor(e)-1)*this.size_[0];return Jd[0]=this.data_[4*i],Jd[1]=this.data_[4*i+1],Jd[2]=this.data_[4*i+2],Jd[3]=this.data_[4*i+3],Jd}getTexture(){return this.texture_}getFramebuffer(){return this.framebuffer_}getDepthbuffer(){return this.depthbuffer_}updateSize_(){const t=this.size_,e=this.helper_.getGL();this.texture_=this.helper_.createTexture(t,null,this.texture_),e.bindFramebuffer(e.FRAMEBUFFER,this.framebuffer_),e.viewport(0,0,t[0],t[1]),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.texture_,0),e.bindRenderbuffer(e.RENDERBUFFER,this.depthbuffer_),e.renderbufferStorage(e.RENDERBUFFER,e.DEPTH_COMPONENT16,t[0],t[1]),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.RENDERBUFFER,this.depthbuffer_),this.data_=new Uint8Array(t[0]*t[1]*4)}};function tg(t,e,i){const n=i?t.LINEAR:t.NEAREST;t.bindTexture(t.TEXTURE_2D,e),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,n),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,n)}function eg(t,e,i,n,r,s){const o=t.getGL();let a,l;if(i instanceof Float32Array){a=o.FLOAT,t.getExtension("OES_texture_float");l=null!==t.getExtension("OES_texture_float_linear")}else a=o.UNSIGNED_BYTE,l=!0;tg(o,e,s&&l);const h=i.byteLength/n[1];let c,u=1;switch(h%8==0?u=8:h%4==0?u=4:h%2==0&&(u=2),r){case 1:c=o.LUMINANCE;break;case 2:c=o.LUMINANCE_ALPHA;break;case 3:c=o.RGB;break;case 4:c=o.RGBA;break;default:throw new Error(`Unsupported number of bands: ${r}`)}const d=o.getParameter(o.UNPACK_ALIGNMENT);o.pixelStorei(o.UNPACK_ALIGNMENT,u),o.texImage2D(o.TEXTURE_2D,0,c,n[0],n[1],0,c,a,i),o.pixelStorei(o.UNPACK_ALIGNMENT,d)}let ig=null;var ng=class extends Od{constructor(t){super(t),this.textures=[],this.renderSize_=ol(t.grid.getTileSize(t.tile.tileCoord[0])),this.bandCount=NaN;const e=new kd(td,id);e.fromArray([0,1,1,1,1,0,0,0]),this.helper_.flushBufferData(e),this.coords=e,this.setTile(t.tile)}uploadTile(){const t=this.helper_,e=t.getGL(),i=this.tile;let n;this.textures.length=0,n=i instanceof is||i instanceof ah?i.getImage():i.getData();const r=Rt(n);if(r){const t=e.createTexture();return this.textures.push(t),this.bandCount=4,function(t,e,i,n){tg(t,e,n),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,i)}(e,t,r,i.interpolate),void this.setReady()}n=bt(n);const s=i.getSize(),o=[s[0]+2*this.gutter_,s[1]+2*this.gutter_],a=n instanceof Float32Array,l=o[0]*o[1],h=a?Float32Array:Uint8Array,c=h.BYTES_PER_ELEMENT,u=n.byteLength/o[1];this.bandCount=Math.floor(u/c/o[0]);const d=Math.ceil(this.bandCount/4);if(1===d){const r=e.createTexture();return this.textures.push(r),eg(t,r,n,o,this.bandCount,i.interpolate),void this.setReady()}const g=new Array(d);for(let t=0;t=f;--r){const i=l.getTileRangeForExtentAndZ(e,r,this.tempTileRange_),o=l.getResolution(r);for(let e=i.minX;e<=i.maxX;++e)for(let g=i.minY;g<=i.maxY;++g){const i=_l(r,e,g,this.tempTileCoord_),f=dg(a,i);let p,m;if(d.containsKey(f)&&(p=d.get(f),m=p.tile),p&&p.tile.key===a.getKey()||(m=a.getTile(r,e,g,t.pixelRatio,s.projection)),hg(n,m))continue;if(p)if(this.isDrawableTile_(m))p.setTile(m);else{const t=m.getInterimTile();p.setTile(t)}else p=this.createTileRepresentation({tile:m,grid:l,helper:this.helper,gutter:h}),d.set(f,p);cg(n,p,r);const _=m.getKey();u[_]=!0,m.getState()===J&&(t.tileQueue.isKeyQueued(_)||t.tileQueue.enqueue([m,c,l.getTileCoordCenter(i),o]))}}}beforeTilesRender(t,e){this.helper.prepareDraw(this.frameState,!e,!0)}renderTile(t,e,i,n,r,s,o,a,l,h,c){}drawTile_(t,e,i,n,r,s,o){if(!e.loaded)return;const a=e.tile.tileCoord,l=xl(a),h=l in s?s[l]:1,c=o.getResolution(i),u=ol(o.getTileSize(i),this.tempSize_),d=o.getOrigin(i),g=o.getTileCoordExtent(a),f=h<1?-1:1/(i+2);h<1&&(t.animate=!0);const p=t.viewState,m=p.center[0],_=p.center[1],y=u[0]+2*n,x=u[1]+2*n,v=y/x,S=(m-d[0])/(u[0]*c),w=(d[1]-_)/(u[1]*c),E=p.resolution/c,T=a[1],C=a[2];Gt(this.tileTransform_),Vt(this.tileTransform_,2/(t.size[0]*E/y),-2/(t.size[1]*E/y)),Xt(this.tileTransform_,p.rotation),Vt(this.tileTransform_,1,1/v),Zt(this.tileTransform_,(u[0]*(T-S)-n)/y,(u[1]*(C-w)-n)/x),this.renderTile(e,this.tileTransform_,t,r,c,u,d,g,f,n,h)}renderFrame(t){this.frameState=t,this.renderComplete=!0;const e=this.helper.getGL();this.preRender(e,t);const i=t.viewState,n=this.getLayer(),r=n.getRenderSource(),s=r.getTileGridForProjection(i.projection),o=r.getGutterForProjection(i.projection),a=ug(t,t.extent),l=s.getZForResolution(i.resolution,r.zDirection),c=lg(),u=n.getPreload();if(t.nextExtent){const e=s.getZForResolution(i.nextResolution,r.zDirection),n=ug(t,t.nextExtent);this.enqueueTiles(t,n,e,c,u)}this.enqueueTiles(t,a,l,c,0),u>0&&setTimeout((()=>{this.enqueueTiles(t,a,l-1,c,u-1)}),0);const d={},g=V(this),f=t.time;let p=!1;for(const t of c.representationsByZ[l]){const e=t.tile;if((e instanceof ah||e instanceof dc)&&e.getState()===it)continue;const i=e.tileCoord;if(t.loaded){const t=e.getAlpha(g,f);if(1===t){e.endTransition(g);continue}p=!0;d[xl(i)]=t}this.renderComplete=!1;if(this.findAltTiles_(s,i,l+1,c))continue;const n=s.getMinZoom();for(let t=l-1;t>=n;--t){if(this.findAltTiles_(s,i,t,c))break}}this.beforeTilesRender(t,p);const m=c.representationsByZ,_=Object.keys(m).map(Number).sort(h);for(let e=0,i=_.length;et.dispose())),t.clear()}removeHelper(){this.helper&&this.clearCache(),super.removeHelper()}disposeInternal(){super.disposeInternal(),delete this.frameState}};const fg={...og,TILE_TEXTURE_ARRAY:"u_tileTextures",TEXTURE_PIXEL_WIDTH:"u_texturePixelWidth",TEXTURE_PIXEL_HEIGHT:"u_texturePixelHeight",TEXTURE_RESOLUTION:"u_textureResolution",TEXTURE_ORIGIN_X:"u_textureOriginX",TEXTURE_ORIGIN_Y:"u_textureOriginY"},pg={TEXTURE_COORD:"a_textureCoord"},mg=[{name:pg.TEXTURE_COORD,size:2,type:Vd.FLOAT}];var _g=class extends gg{constructor(t,e){super(t,e),this.program_,this.vertexShader_=e.vertexShader,this.fragmentShader_=e.fragmentShader,this.indices_=new kd(ed,id),this.indices_.fromArray([0,1,3,1,2,3]),this.paletteTextures_=e.paletteTextures||[]}reset(t){super.reset(t),this.vertexShader_=t.vertexShader,this.fragmentShader_=t.fragmentShader,this.helper&&(this.program_=this.helper.getProgram(this.fragmentShader_,this.vertexShader_))}afterHelperCreated(){this.program_=this.helper.getProgram(this.fragmentShader_,this.vertexShader_),this.helper.flushBufferData(this.indices_)}createTileRepresentation(t){return new ng(t)}beforeTilesRender(t,e){super.beforeTilesRender(t,e),this.helper.useProgram(this.program_,t)}renderTile(t,e,i,n,r,s,o,a,l,h,c){const u=this.helper.getGL();this.helper.bindBuffer(t.coords),this.helper.bindBuffer(this.indices_),this.helper.enableAttributes(mg);let d=0;for(;d0&&(x=a,Ie(x,n,x)),this.helper.setUniformFloatVec4(fg.RENDER_EXTENT,x),this.helper.setUniformFloatValue(fg.RESOLUTION,g.resolution),this.helper.setUniformFloatValue(fg.ZOOM,g.zoom),this.helper.setUniformFloatValue(fg.TEXTURE_PIXEL_WIDTH,f),this.helper.setUniformFloatValue(fg.TEXTURE_PIXEL_HEIGHT,p),this.helper.setUniformFloatValue(fg.TEXTURE_RESOLUTION,r),this.helper.setUniformFloatValue(fg.TEXTURE_ORIGIN_X,o[0]+_*s[0]*r-h*r),this.helper.setUniformFloatValue(fg.TEXTURE_ORIGIN_Y,o[1]-y*s[1]*r+h*r),this.helper.drawElements(0,this.indices_.getSize())}getData(t){if(!this.helper.getGL())return null;const e=this.frameState;if(!e)return null;const i=this.getLayer(),n=zt(e.pixelToCoordinateTransform,t.slice()),r=e.viewState,s=i.getExtent();if(s&&!ne(Sn(s,r.projection),n))return null;const o=i.getSources(Qt([n]),r.resolution);let a,l,h;for(a=o.length-1;a>=0;--a)if(l=o[a],"ready"===l.getState()){if(h=l.getTileGridForProjection(r.projection),l.getWrapX())break;const t=h.getExtent();if(!t||ne(t,n))break}if(a<0)return null;const c=this.tileRepresentationCache;for(let t=h.getZForResolution(r.resolution);t>=h.getMinZoom();--t){const e=h.getTileCoordForCoordAndZ(n,t),i=dg(l,e);if(!c.containsKey(i))continue;const r=c.get(i),s=r.tile;if((s instanceof ah||s instanceof dc)&&s.getState()===it)return null;if(!r.loaded)continue;const o=h.getOrigin(t),a=ol(h.getTileSize(t)),u=h.getResolution(t),d=(n[0]-o[0])/u-e[1]*a[0],g=(o[1]-n[1])/u-e[2]*a[1];return r.getPixelData(d,g)}return null}disposeInternal(){const t=this.helper;if(t){t.getGL().deleteProgram(this.program_),delete this.program_,t.deleteBuffer(this.indices_)}super.disposeInternal(),delete this.indices_}};const yg={NUMBER:1,STRING:2,COLOR:4,BOOLEAN:8,NUMBER_ARRAY:16,ANY:31,NONE:0};const xg={};function vg(t){if("number"==typeof t)return yg.NUMBER;if("boolean"==typeof t)return yg.BOOLEAN;if("string"==typeof t)return ds(t)?yg.COLOR|yg.STRING:yg.STRING;if(!Array.isArray(t))throw new Error(`Unhandled value type: ${JSON.stringify(t)}`);const e=t;if(e.every((function(t){return"number"==typeof t})))return 3===e.length||4===e.length?yg.COLOR|yg.NUMBER_ARRAY:yg.NUMBER_ARRAY;if("string"!=typeof e[0])throw new Error(`Expected an expression operator but received: ${JSON.stringify(e)}`);const i=xg[e[0]];if(void 0===i)throw new Error(`Unrecognized expression operator: ${JSON.stringify(e)}`);return i.getReturnType(e.slice(1))}function Sg(t){return Math.log2(t)%1==0}function wg(t){const e=[];return(t&yg.NUMBER)>0&&e.push("number"),(t&yg.COLOR)>0&&e.push("color"),(t&yg.BOOLEAN)>0&&e.push("boolean"),(t&yg.NUMBER_ARRAY)>0&&e.push("number[]"),(t&yg.STRING)>0&&e.push("string"),e.length>0?e.join(", "):"(no type)"}function Eg(t){const e=t.toString();return e.includes(".")?e:e+".0"}function Tg(t){if(t.length<2||t.length>4)throw new Error("`formatArray` can only output `vec2`, `vec3` or `vec4` arrays.");return`vec${t.length}(${t.map(Eg).join(", ")})`}function Cg(t){const e=hs(t),i=e.length>3?e[3]:1;return Tg([e[0]/255*i,e[1]/255*i,e[2]/255*i,i])}function Rg(t,e){return void 0===t.stringLiteralsMap[e]&&(t.stringLiteralsMap[e]=Object.keys(t.stringLiteralsMap).length),t.stringLiteralsMap[e]}function bg(t,e){return Eg(Rg(t,e))}function Pg(t,e,i){const n=void 0!==i?i:yg.NUMBER;if(Array.isArray(e)&&"string"==typeof e[0]){const i=xg[e[0]];if(void 0===i)throw new Error(`Unrecognized expression operator: ${JSON.stringify(e)}`);return i.toGlsl(t,e.slice(1),n)}const r=vg(e)&n;if(kg(e,r,""),(r&yg.NUMBER)>0)return Eg(e);if((r&yg.BOOLEAN)>0)return e.toString();if((r&yg.STRING)>0)return bg(t,e.toString());if((r&yg.COLOR)>0)return Cg(e);if((r&yg.NUMBER_ARRAY)>0)return Tg(e);throw new Error(`Unexpected expression ${e} (expected type ${wg(n)})`)}function Ig(t){if(0==(vg(t)&yg.NUMBER))throw new Error(`A numeric value was expected, got ${JSON.stringify(t)} instead`)}function Fg(t){for(let e=0;ee)throw new Error(`At most ${e} arguments were expected, got ${t.length} instead`)}function Dg(t){if(t.length%2!=0)throw new Error(`An even amount of arguments was expected, got ${JSON.stringify(t)} instead`)}function kg(t,e,i){if(e===yg.NONE)throw new Error(`No matching type was found for the following expression ${i}: ${JSON.stringify(t)}`)}function Gg(t,e,i){if(kg(t,e,i),!Sg(e))throw new Error(`Expected to have a unique type for the following expression ${i}: ${JSON.stringify(t)}\nGot the following types instead: ${wg(e)}`)}function jg(t,e,i,n){if((e&i)===yg.NONE)throw new Error(`Expected the ${n} type of the following expression: ${JSON.stringify(t)} to be of the following types: ${wg(i)}\nGot these types instead: ${wg(e)}`)}function Bg(t){return"u_var_"+t}xg.get={getReturnType:function(t){if(2===t.length){return function(t){switch(t){case"string":return yg.STRING;case"color":return yg.COLOR;case"number":return yg.NUMBER;case"boolean":return yg.BOOLEAN;case"number[]":return yg.NUMBER_ARRAY;default:throw new Error(`Unrecognized type hint: ${t}`)}}(t[1])}return yg.ANY},toGlsl:function(t,e,i){Og(e,1),Ng(e,2),Lg(e[0]);const n=i&xg.get.getReturnType(e);Gg(["get",...e],n,"");const r=e[0].toString(),s=t.attributes.find((t=>t.name===r));if(s){if(n!==s.type)throw new Error(`The following attribute was used in different places with incompatible types: ${r}\nTypes were: ${wg(s.type)} and ${wg(n)}`)}else t.attributes.push({name:r,type:n});return(t.inFragmentShader?"v_":"a_")+r}},xg.var={getReturnType:function(){return yg.ANY},toGlsl:function(t,e,i){Ag(e,1),Lg(e[0]);const n=e[0].toString();if(!t.style.variables||void 0===t.style.variables[n])throw new Error(`The following variable is missing from the style: ${n}`);const r=i&vg(t.style.variables[n]);Gg(["var",...e],r,"");const s=t.variables.find((t=>t.name===n));if(s){if(r!==s.type)throw new Error(`The following variable was used in different places with incompatible types: ${n}\nTypes were: ${wg(s.type)} and ${wg(r)}`)}else t.variables.push({name:n,type:r});return Bg(n)}};const Ug="u_paletteTextures";xg.palette={getReturnType:function(){return yg.COLOR},toGlsl:function(t,e){Ag(e,2),Ig(e[0]);const i=Pg(t,e[0]),n=e[1];if(!Array.isArray(n))throw new Error("The second argument of palette must be an array");const r=n.length,s=new Uint8Array(4*r);for(let t=0;tPg(e,t,yg.BOOLEAN))).join(` ${t} `);return n=`(${n})`,n}}}xg.band={getReturnType:function(){return yg.NUMBER},toGlsl:function(t,e){Og(e,1),Ng(e,3);const i=e[0];if(!(zg in t.functions)){let e="";const i=t.bandCount||1;for(let t=0;t{const e=t.getType();switch(e){case"Point":case"LineString":case"Polygon":return e;case"MultiPoint":case"MultiLineString":case"MultiPolygon":return e.substring(5);case"Circle":return"Polygon";case"GeometryCollection":return n(t.getGeometries()[0])}};t.attributes.find((t=>t.name===i))||t.attributes.push({name:i,type:yg.STRING,callback:t=>n(t.getGeometry())});return(t.inFragmentShader?"v_":"a_")+i}},xg["*"]={getReturnType:function(t){let e=yg.NUMBER|yg.COLOR;for(let i=0;iPg(t,e,n))).join(" * ")})`}},xg["/"]={getReturnType:function(){return yg.NUMBER},toGlsl:function(t,e){return Ag(e,2),Fg(e),`(${Pg(t,e[0])} / ${Pg(t,e[1])})`}},xg["+"]={getReturnType:function(){return yg.NUMBER},toGlsl:function(t,e){return Og(e,2),Fg(e),`(${e.map((e=>Pg(t,e))).join(" + ")})`}},xg["-"]={getReturnType:function(){return yg.NUMBER},toGlsl:function(t,e){return Ag(e,2),Fg(e),`(${Pg(t,e[0])} - ${Pg(t,e[1])})`}},xg.clamp={getReturnType:function(){return yg.NUMBER},toGlsl:function(t,e){Ag(e,3),Fg(e);const i=Pg(t,e[1]),n=Pg(t,e[2]);return`clamp(${Pg(t,e[0])}, ${i}, ${n})`}},xg["%"]={getReturnType:function(){return yg.NUMBER},toGlsl:function(t,e){return Ag(e,2),Fg(e),`mod(${Pg(t,e[0])}, ${Pg(t,e[1])})`}},xg["^"]={getReturnType:function(){return yg.NUMBER},toGlsl:function(t,e){return Ag(e,2),Fg(e),`pow(${Pg(t,e[0])}, ${Pg(t,e[1])})`}},xg.abs={getReturnType:function(){return yg.NUMBER},toGlsl:function(t,e){return Ag(e,1),Fg(e),`abs(${Pg(t,e[0])})`}},xg.floor={getReturnType:function(){return yg.NUMBER},toGlsl:function(t,e){return Ag(e,1),Fg(e),`floor(${Pg(t,e[0])})`}},xg.round={getReturnType:function(){return yg.NUMBER},toGlsl:function(t,e){return Ag(e,1),Fg(e),`floor(${Pg(t,e[0])} + 0.5)`}},xg.ceil={getReturnType:function(){return yg.NUMBER},toGlsl:function(t,e){return Ag(e,1),Fg(e),`ceil(${Pg(t,e[0])})`}},xg.sin={getReturnType:function(){return yg.NUMBER},toGlsl:function(t,e){return Ag(e,1),Fg(e),`sin(${Pg(t,e[0])})`}},xg.cos={getReturnType:function(){return yg.NUMBER},toGlsl:function(t,e){return Ag(e,1),Fg(e),`cos(${Pg(t,e[0])})`}},xg.atan={getReturnType:function(){return yg.NUMBER},toGlsl:function(t,e){return Og(e,1),Ng(e,2),Fg(e),2===e.length?`atan(${Pg(t,e[0])}, ${Pg(t,e[1])})`:`atan(${Pg(t,e[0])})`}},xg.sqrt={getReturnType:function(){return yg.NUMBER},toGlsl:function(t,e){return Ag(e,1),Fg(e),`sqrt(${Pg(t,e[0])})`}},xg[">"]={getReturnType:function(){return yg.BOOLEAN},toGlsl:function(t,e){return Ag(e,2),Fg(e),`(${Pg(t,e[0])} > ${Pg(t,e[1])})`}},xg[">="]={getReturnType:function(){return yg.BOOLEAN},toGlsl:function(t,e){return Ag(e,2),Fg(e),`(${Pg(t,e[0])} >= ${Pg(t,e[1])})`}},xg["<"]={getReturnType:function(){return yg.BOOLEAN},toGlsl:function(t,e){return Ag(e,2),Fg(e),`(${Pg(t,e[0])} < ${Pg(t,e[1])})`}},xg["<="]={getReturnType:function(){return yg.BOOLEAN},toGlsl:function(t,e){return Ag(e,2),Fg(e),`(${Pg(t,e[0])} <= ${Pg(t,e[1])})`}},xg["=="]=Xg("=="),xg["!="]=Xg("!="),xg["!"]={getReturnType:function(){return yg.BOOLEAN},toGlsl:function(t,e){return Ag(e,1),Mg(e[0]),`(!${Pg(t,e[0],yg.BOOLEAN)})`}},xg.all=Vg("&&"),xg.any=Vg("||"),xg.between={getReturnType:function(){return yg.BOOLEAN},toGlsl:function(t,e){Ag(e,3),Fg(e);const i=Pg(t,e[1]),n=Pg(t,e[2]),r=Pg(t,e[0]);return`(${r} >= ${i} && ${r} <= ${n})`}},xg.array={getReturnType:function(){return yg.NUMBER_ARRAY},toGlsl:function(t,e){Og(e,2),Ng(e,4),Fg(e);const i=e.map((function(e){return Pg(t,e)}));return`vec${e.length}(${i.join(", ")})`}},xg.color={getReturnType:function(){return yg.COLOR},toGlsl:function(t,e){Og(e,3),Ng(e,4),Fg(e);const i=e.slice(0,3).map((e=>`${Pg(t,e)} / 255.0`));if(3===e.length)return`vec4(${i.join(", ")}, 1.0)`;return`(${Pg(t,e[3])} * vec4(${i.join(", ")}, 1.0))`}},xg.interpolate={getReturnType:function(t){let e=yg.COLOR|yg.NUMBER;for(let i=3;i=1;i-=2){a=`(${s} == ${Pg(t,e[i],n)} ? ${Pg(t,e[i+1],r)} : ${a||o})`}return a}},xg.case={getReturnType:function(t){let e=yg.ANY;for(let i=1;i=0;i-=2){s=`(${Pg(t,e[i],yg.BOOLEAN)} ? ${Pg(t,e[i+1],n)} : ${s||r})`}return s}},xg.in={getReturnType:function(t){return yg.BOOLEAN},toGlsl:function(t,e){Ag(e,2);const i=e[0];let n=e[1];if(!Array.isArray(n))throw new Error('The "in" operator expects an array literal as its second argument.');if("string"==typeof n[0]){if("literal"!==n[0])throw new Error('For the "in" operator, a string array should be wrapped in a "literal" operator to disambiguate from expressions.');if(!Array.isArray(n[1]))throw new Error('The "in" operator was provided a literal value which was not an array as second argument.');n=n[1]}let r=vg(i);for(let t=0;t0,6),Mt(!((void 0!==t.width||void 0!==t.height)&&void 0!==t.scale),69);const a=void 0!==t.src?Kr:qr;if(this.color_=void 0!==t.color?hs(t.color):null,this.iconImage_=ef(s,o,void 0!==this.imgSize_?this.imgSize_:null,this.crossOrigin_,a,this.color_),this.offset_=void 0!==t.offset?t.offset:[0,0],this.offsetOrigin_=void 0!==t.offsetOrigin?t.offsetOrigin:"top-left",this.origin_=null,this.size_=void 0!==t.size?t.size:null,void 0!==t.width||void 0!==t.height){let e,i;if(t.size)[e,i]=t.size;else{const n=this.getImage(1);if(!(n instanceof HTMLCanvasElement||n.src&&n.complete)){this.initialOptions_=t;const e=()=>{if(this.unlistenImageChange(e),!this.initialOptions_)return;const i=this.iconImage_.getSize();this.setScale(rf(i[0],i[1],t.width,t.height))};return void this.listenImageChange(e)}e=n.width,i=n.height}void 0!==e&&this.setScale(rf(e,i,t.width,t.height))}}clone(){let t,e,i;this.initialOptions_?(e=this.initialOptions_.width,i=this.initialOptions_.height):(t=this.getScale(),t=Array.isArray(t)?t.slice():t);return new sf({anchor:this.anchor_.slice(),anchorOrigin:this.anchorOrigin_,anchorXUnits:this.anchorXUnits_,anchorYUnits:this.anchorYUnits_,color:this.color_&&this.color_.slice?this.color_.slice():this.color_||void 0,crossOrigin:this.crossOrigin_,imgSize:this.imgSize_,offset:this.offset_.slice(),offsetOrigin:this.offsetOrigin_,opacity:this.getOpacity(),rotateWithView:this.getRotateWithView(),rotation:this.getRotation(),scale:t,width:e,height:i,size:null!==this.size_?this.size_.slice():void 0,src:this.getSrc(),displacement:this.getDisplacement().slice(),declutterMode:this.getDeclutterMode()})}getAnchor(){let t=this.normalizedAnchor_;if(!t){t=this.anchor_;const e=this.getSize();if("fraction"==this.anchorXUnits_||"fraction"==this.anchorYUnits_){if(!e)return null;t=this.anchor_.slice(),"fraction"==this.anchorXUnits_&&(t[0]*=e[0]),"fraction"==this.anchorYUnits_&&(t[1]*=e[1])}if("top-left"!=this.anchorOrigin_){if(!e)return null;t===this.anchor_&&(t=this.anchor_.slice()),"top-right"!=this.anchorOrigin_&&"bottom-right"!=this.anchorOrigin_||(t[0]=-t[0]+e[0]),"bottom-left"!=this.anchorOrigin_&&"bottom-right"!=this.anchorOrigin_||(t[1]=-t[1]+e[1])}this.normalizedAnchor_=t}const e=this.getDisplacement(),i=this.getScaleArray();return[t[0]-e[0]/i[0],t[1]+e[1]/i[1]]}setAnchor(t){this.anchor_=t,this.normalizedAnchor_=null}getColor(){return this.color_}getImage(t){return this.iconImage_.getImage(t)}getPixelRatio(t){return this.iconImage_.getPixelRatio(t)}getImageSize(){return this.iconImage_.getSize()}getImageState(){return this.iconImage_.getImageState()}getHitDetectionImage(){return this.iconImage_.getHitDetectionImage()}getOrigin(){if(this.origin_)return this.origin_;let t=this.offset_;if("top-left"!=this.offsetOrigin_){const e=this.getSize(),i=this.iconImage_.getSize();if(!e||!i)return null;t=t.slice(),"top-right"!=this.offsetOrigin_&&"bottom-right"!=this.offsetOrigin_||(t[0]=i[0]-e[0]-t[0]),"bottom-left"!=this.offsetOrigin_&&"bottom-right"!=this.offsetOrigin_||(t[1]=i[1]-e[1]-t[1])}return this.origin_=t,this.origin_}getSrc(){return this.iconImage_.getSrc()}getSize(){return this.size_?this.size_:this.iconImage_.getSize()}getWidth(){const t=this.getScaleArray();return this.size_?this.size_[0]*t[0]:this.iconImage_.getImageState()==qr?this.iconImage_.getSize()[0]*t[0]:void 0}getHeight(){const t=this.getScaleArray();return this.size_?this.size_[1]*t[1]:this.iconImage_.getImageState()==qr?this.iconImage_.getSize()[1]*t[1]:void 0}setScale(t){delete this.initialOptions_,super.setScale(t)}listenImageChange(t){this.iconImage_.addEventListener(E,t)}load(){this.iconImage_.load()}unlistenImageChange(t){this.iconImage_.removeEventListener(E,t)}}var of=sf;class af{constructor(t){t=t||{},this.color_=void 0!==t.color?t.color:null,this.lineCap_=t.lineCap,this.lineDash_=void 0!==t.lineDash?t.lineDash:null,this.lineDashOffset_=t.lineDashOffset,this.lineJoin_=t.lineJoin,this.miterLimit_=t.miterLimit,this.width_=t.width}clone(){const t=this.getColor();return new af({color:Array.isArray(t)?t.slice():t||void 0,lineCap:this.getLineCap(),lineDash:this.getLineDash()?this.getLineDash().slice():void 0,lineDashOffset:this.getLineDashOffset(),lineJoin:this.getLineJoin(),miterLimit:this.getMiterLimit(),width:this.getWidth()})}getColor(){return this.color_}getLineCap(){return this.lineCap_}getLineDash(){return this.lineDash_}getLineDashOffset(){return this.lineDashOffset_}getLineJoin(){return this.lineJoin_}getMiterLimit(){return this.miterLimit_}getWidth(){return this.width_}setColor(t){this.color_=t}setLineCap(t){this.lineCap_=t}setLineDash(t){this.lineDash_=t}setLineDashOffset(t){this.lineDashOffset_=t}setLineJoin(t){this.lineJoin_=t}setMiterLimit(t){this.miterLimit_=t}setWidth(t){this.width_=t}}var lf=af;class hf{constructor(t){t=t||{},this.geometry_=null,this.geometryFunction_=ff,void 0!==t.geometry&&this.setGeometry(t.geometry),this.fill_=void 0!==t.fill?t.fill:null,this.image_=void 0!==t.image?t.image:null,this.renderer_=void 0!==t.renderer?t.renderer:null,this.hitDetectionRenderer_=void 0!==t.hitDetectionRenderer?t.hitDetectionRenderer:null,this.stroke_=void 0!==t.stroke?t.stroke:null,this.text_=void 0!==t.text?t.text:null,this.zIndex_=t.zIndex}clone(){let t=this.getGeometry();return t&&"object"==typeof t&&(t=t.clone()),new hf({geometry:t,fill:this.getFill()?this.getFill().clone():void 0,image:this.getImage()?this.getImage().clone():void 0,renderer:this.getRenderer(),stroke:this.getStroke()?this.getStroke().clone():void 0,text:this.getText()?this.getText().clone():void 0,zIndex:this.getZIndex()})}getRenderer(){return this.renderer_}setRenderer(t){this.renderer_=t}setHitDetectionRenderer(t){this.hitDetectionRenderer_=t}getHitDetectionRenderer(){return this.hitDetectionRenderer_}getGeometry(){return this.geometry_}getGeometryFunction(){return this.geometryFunction_}getFill(){return this.fill_}setFill(t){this.fill_=t}getImage(){return this.image_}setImage(t){this.image_=t}getStroke(){return this.stroke_}setStroke(t){this.stroke_=t}getText(){return this.text_}setText(t){this.text_=t}getZIndex(){return this.zIndex_}setGeometry(t){"function"==typeof t?this.geometryFunction_=t:"string"==typeof t?this.geometryFunction_=function(e){return e.get(t)}:t?void 0!==t&&(this.geometryFunction_=function(){return t}):this.geometryFunction_=ff,this.geometry_=t}setZIndex(t){this.zIndex_=t}}function cf(t){let e;if("function"==typeof t)e=t;else{let i;if(Array.isArray(t))i=t;else{Mt("function"==typeof t.getZIndex,41);i=[t]}e=function(){return i}}return e}let uf=null;function df(t,e){if(!uf){const t=new Jg({color:"rgba(255,255,255,0.4)"}),e=new lf({color:"#3399CC",width:1.25});uf=[new hf({image:new qg({fill:t,stroke:e,radius:5}),fill:t,stroke:e})]}return uf}function gf(){const t={},e=[255,255,255,1],i=[0,153,255,1];return t.Polygon=[new hf({fill:new Jg({color:[255,255,255,.5]})})],t.MultiPolygon=t.Polygon,t.LineString=[new hf({stroke:new lf({color:e,width:5})}),new hf({stroke:new lf({color:i,width:3})})],t.MultiLineString=t.LineString,t.Circle=t.Polygon.concat(t.LineString),t.Point=[new hf({image:new qg({radius:6,fill:new Jg({color:i}),stroke:new lf({color:e,width:1.5})}),zIndex:1/0})],t.MultiPoint=t.Point,t.GeometryCollection=t.Polygon.concat(t.LineString,t.Point),t}function ff(t){return t.getGeometry()}var pf=hf;class mf{constructor(t){t=t||{},this.font_=t.font,this.rotation_=t.rotation,this.rotateWithView_=t.rotateWithView,this.scale_=t.scale,this.scaleArray_=ol(void 0!==t.scale?t.scale:1),this.text_=t.text,this.textAlign_=t.textAlign,this.justify_=t.justify,this.repeat_=t.repeat,this.textBaseline_=t.textBaseline,this.fill_=void 0!==t.fill?t.fill:new Jg({color:"#333"}),this.maxAngle_=void 0!==t.maxAngle?t.maxAngle:Math.PI/4,this.placement_=void 0!==t.placement?t.placement:"point",this.overflow_=!!t.overflow,this.stroke_=void 0!==t.stroke?t.stroke:null,this.offsetX_=void 0!==t.offsetX?t.offsetX:0,this.offsetY_=void 0!==t.offsetY?t.offsetY:0,this.backgroundFill_=t.backgroundFill?t.backgroundFill:null,this.backgroundStroke_=t.backgroundStroke?t.backgroundStroke:null,this.padding_=void 0===t.padding?null:t.padding}clone(){const t=this.getScale();return new mf({font:this.getFont(),placement:this.getPlacement(),repeat:this.getRepeat(),maxAngle:this.getMaxAngle(),overflow:this.getOverflow(),rotation:this.getRotation(),rotateWithView:this.getRotateWithView(),scale:Array.isArray(t)?t.slice():t,text:this.getText(),textAlign:this.getTextAlign(),justify:this.getJustify(),textBaseline:this.getTextBaseline(),fill:this.getFill()?this.getFill().clone():void 0,stroke:this.getStroke()?this.getStroke().clone():void 0,offsetX:this.getOffsetX(),offsetY:this.getOffsetY(),backgroundFill:this.getBackgroundFill()?this.getBackgroundFill().clone():void 0,backgroundStroke:this.getBackgroundStroke()?this.getBackgroundStroke().clone():void 0,padding:this.getPadding()||void 0})}getOverflow(){return this.overflow_}getFont(){return this.font_}getMaxAngle(){return this.maxAngle_}getPlacement(){return this.placement_}getRepeat(){return this.repeat_}getOffsetX(){return this.offsetX_}getOffsetY(){return this.offsetY_}getFill(){return this.fill_}getRotateWithView(){return this.rotateWithView_}getRotation(){return this.rotation_}getScale(){return this.scale_}getScaleArray(){return this.scaleArray_}getStroke(){return this.stroke_}getText(){return this.text_}getTextAlign(){return this.textAlign_}getJustify(){return this.justify_}getTextBaseline(){return this.textBaseline_}getBackgroundFill(){return this.backgroundFill_}getBackgroundStroke(){return this.backgroundStroke_}getPadding(){return this.padding_}setOverflow(t){this.overflow_=t}setFont(t){this.font_=t}setMaxAngle(t){this.maxAngle_=t}setOffsetX(t){this.offsetX_=t}setOffsetY(t){this.offsetY_=t}setPlacement(t){this.placement_=t}setRepeat(t){this.repeat_=t}setRotateWithView(t){this.rotateWithView_=t}setFill(t){this.fill_=t}setRotation(t){this.rotation_=t}setScale(t){this.scale_=t,this.scaleArray_=ol(void 0!==t?t:1)}setStroke(t){this.stroke_=t}setText(t){this.text_=t}setTextAlign(t){this.textAlign_=t}setJustify(t){this.justify_=t}setTextBaseline(t){this.textBaseline_=t}setBackgroundFill(t){this.backgroundFill_=t}setBackgroundStroke(t){this.backgroundStroke_=t}setPadding(t){this.padding_=t}}var _f=mf;function yf(t){return new pf({fill:xf(t,""),stroke:vf(t,""),text:Sf(t),image:wf(t)})}function xf(t,e){const i=t[e+"fill-color"];if(i)return"none"===i?null:new Jg({color:i})}function vf(t,e){const i=t[e+"stroke-width"],n=t[e+"stroke-color"];if(i||n)return new lf({width:i,color:n,lineCap:t[e+"stroke-line-cap"],lineJoin:t[e+"stroke-line-join"],lineDash:t[e+"stroke-line-dash"],lineDashOffset:t[e+"stroke-line-dash-offset"],miterLimit:t[e+"stroke-miter-limit"]})}function Sf(t){const e=t["text-value"];if(!e)return;return new _f({text:e,font:t["text-font"],maxAngle:t["text-max-angle"],offsetX:t["text-offset-x"],offsetY:t["text-offset-y"],overflow:t["text-overflow"],placement:t["text-placement"],repeat:t["text-repeat"],scale:t["text-scale"],rotateWithView:t["text-rotate-with-view"],rotation:t["text-rotation"],textAlign:t["text-align"],justify:t["text-justify"],textBaseline:t["text-baseline"],padding:t["text-padding"],fill:xf(t,"text-"),backgroundFill:xf(t,"text-background-"),stroke:vf(t,"text-"),backgroundStroke:vf(t,"text-background-")})}function wf(t){const e=t["icon-src"],i=t["icon-img"];if(e||i){return new of({src:e,img:i,imgSize:t["icon-img-size"],anchor:t["icon-anchor"],anchorOrigin:t["icon-anchor-origin"],anchorXUnits:t["icon-anchor-x-units"],anchorYUnits:t["icon-anchor-y-units"],color:t["icon-color"],crossOrigin:t["icon-cross-origin"],offset:t["icon-offset"],displacement:t["icon-displacement"],opacity:t["icon-opacity"],scale:t["icon-scale"],width:t["icon-width"],height:t["icon-height"],rotation:t["icon-rotation"],rotateWithView:t["icon-rotate-with-view"],size:t["icon-size"],declutterMode:t["icon-declutter-mode"]})}const n=t["shape-points"];if(n){const e="shape-";return new Kg({points:n,fill:xf(t,e),stroke:vf(t,e),radius:t["shape-radius"],radius1:t["shape-radius1"],radius2:t["shape-radius2"],angle:t["shape-angle"],displacement:t["shape-displacement"],rotation:t["shape-rotation"],rotateWithView:t["shape-rotate-with-view"],scale:t["shape-scale"],declutterMode:t["shape-declutter-mode"]})}const r=t["circle-radius"];if(r){const e="circle-";return new qg({radius:r,fill:xf(t,e),stroke:vf(t,e),displacement:t["circle-displacement"],scale:t["circle-scale"],rotation:t["circle-rotation"],rotateWithView:t["circle-rotate-with-view"],declutterMode:t["circle-declutter-mode"]})}}function Ef(){return{"fill-color":"rgba(255,255,255,0.4)","stroke-color":"#3399CC","stroke-width":1.25,"circle-radius":5,"circle-fill-color":"rgba(255,255,255,0.4)","circle-stroke-width":1.25,"circle-stroke-color":"#3399CC"}}const Tf="uniform mat4 u_projectionMatrix;\nuniform mat4 u_screenToWorldMatrix;\nuniform vec2 u_viewportSizePx;\nuniform float u_pixelRatio;\nuniform float u_globalAlpha;\nuniform float u_time;\nuniform float u_zoom;\nuniform float u_resolution;\nuniform vec4 u_renderExtent;\nuniform mediump int u_hitDetection;\n",Cf={"fill-color":"rgba(255,255,255,0.4)","stroke-color":"#3399CC","stroke-width":1.25,"circle-radius":5,"circle-fill-color":"rgba(255,255,255,0.4)","circle-stroke-width":1.25,"circle-stroke-color":"#3399CC"};class Rf{constructor(){this.uniforms_=[],this.attributes_=[],this.varyings_=[],this.hasSymbol_=!1,this.symbolSizeExpression_=`vec2(${Eg(Cf["circle-radius"])})`,this.symbolRotationExpression_="0.0",this.symbolOffsetExpression_="vec2(0.0)",this.symbolColorExpression_=Cg(Cf["circle-fill-color"]),this.texCoordExpression_="vec4(0.0, 0.0, 1.0, 1.0)",this.discardExpression_="false",this.symbolRotateWithView_=!1,this.hasStroke_=!1,this.strokeWidthExpression_=Eg(Cf["stroke-width"]),this.strokeColorExpression_=Cg(Cf["stroke-color"]),this.hasFill_=!1,this.fillColorExpression_=Cg(Cf["fill-color"]),this.vertexShaderFunctions_=[],this.fragmentShaderFunctions_=[]}addUniform(t){return this.uniforms_.push(t),this}addAttribute(t){return this.attributes_.push(t),this}addVarying(t,e,i){return this.varyings_.push({name:t,type:e,expression:i}),this}setSymbolSizeExpression(t){return this.hasSymbol_=!0,this.symbolSizeExpression_=t,this}getSymbolSizeExpression(){return this.symbolSizeExpression_}setSymbolRotationExpression(t){return this.symbolRotationExpression_=t,this}setSymbolOffsetExpression(t){return this.symbolOffsetExpression_=t,this}setSymbolColorExpression(t){return this.hasSymbol_=!0,this.symbolColorExpression_=t,this}getSymbolColorExpression(){return this.symbolColorExpression_}setTextureCoordinateExpression(t){return this.texCoordExpression_=t,this}setFragmentDiscardExpression(t){return this.discardExpression_=t,this}setSymbolRotateWithView(t){return this.symbolRotateWithView_=t,this}setStrokeWidthExpression(t){return this.hasStroke_=!0,this.strokeWidthExpression_=t,this}setStrokeColorExpression(t){return this.hasStroke_=!0,this.strokeColorExpression_=t,this}setFillColorExpression(t){return this.hasFill_=!0,this.fillColorExpression_=t,this}addVertexShaderFunction(t){this.vertexShaderFunctions_.includes(t)||this.vertexShaderFunctions_.push(t)}addFragmentShaderFunction(t){this.fragmentShaderFunctions_.includes(t)||this.fragmentShaderFunctions_.push(t)}getSymbolVertexShader(){if(!this.hasSymbol_)return null;const t=this.symbolRotateWithView_?"u_offsetScaleMatrix * u_offsetRotateMatrix":"u_offsetScaleMatrix";return`precision mediump float;\nuniform mat4 u_projectionMatrix;\nuniform mat4 u_offsetScaleMatrix;\nuniform mat4 u_offsetRotateMatrix;\nuniform float u_time;\nuniform float u_zoom;\nuniform float u_resolution;\nuniform mediump int u_hitDetection;\n\n${this.uniforms_.map((function(t){return"uniform "+t+";"})).join("\n")}\nattribute vec2 a_position;\nattribute float a_index;\nattribute vec4 a_hitColor;\n${this.attributes_.map((function(t){return"attribute "+t+";"})).join("\n")}\nvarying vec2 v_texCoord;\nvarying vec2 v_quadCoord;\nvarying vec4 v_hitColor;\n${this.varyings_.map((function(t){return"varying "+t.type+" "+t.name+";"})).join("\n")}\n${this.vertexShaderFunctions_.join("\n")}\nvoid main(void) {\n mat4 offsetMatrix = ${t};\n vec2 halfSize = ${this.symbolSizeExpression_} * 0.5;\n vec2 offset = ${this.symbolOffsetExpression_};\n float angle = ${this.symbolRotationExpression_};\n float offsetX;\n float offsetY;\n if (a_index == 0.0) {\n offsetX = (offset.x - halfSize.x) * cos(angle) + (offset.y - halfSize.y) * sin(angle);\n offsetY = (offset.y - halfSize.y) * cos(angle) - (offset.x - halfSize.x) * sin(angle);\n } else if (a_index == 1.0) {\n offsetX = (offset.x + halfSize.x) * cos(angle) + (offset.y - halfSize.y) * sin(angle);\n offsetY = (offset.y - halfSize.y) * cos(angle) - (offset.x + halfSize.x) * sin(angle);\n } else if (a_index == 2.0) {\n offsetX = (offset.x + halfSize.x) * cos(angle) + (offset.y + halfSize.y) * sin(angle);\n offsetY = (offset.y + halfSize.y) * cos(angle) - (offset.x + halfSize.x) * sin(angle);\n } else {\n offsetX = (offset.x - halfSize.x) * cos(angle) + (offset.y + halfSize.y) * sin(angle);\n offsetY = (offset.y + halfSize.y) * cos(angle) - (offset.x - halfSize.x) * sin(angle);\n }\n vec4 offsets = offsetMatrix * vec4(offsetX, offsetY, 0.0, 0.0);\n gl_Position = u_projectionMatrix * vec4(a_position, 0.0, 1.0) + offsets;\n vec4 texCoord = ${this.texCoordExpression_};\n float u = a_index == 0.0 || a_index == 3.0 ? texCoord.s : texCoord.p;\n float v = a_index == 2.0 || a_index == 3.0 ? texCoord.t : texCoord.q;\n v_texCoord = vec2(u, v);\n u = a_index == 0.0 || a_index == 3.0 ? 0.0 : 1.0;\n v = a_index == 2.0 || a_index == 3.0 ? 0.0 : 1.0;\n v_quadCoord = vec2(u, v);\n v_hitColor = a_hitColor;\n${this.varyings_.map((function(t){return" "+t.name+" = "+t.expression+";"})).join("\n")}\n}`}getSymbolFragmentShader(){return this.hasSymbol_?`precision mediump float;\nuniform float u_time;\nuniform float u_zoom;\nuniform float u_resolution;\nuniform mediump int u_hitDetection;\n${this.uniforms_.map((function(t){return"uniform "+t+";"})).join("\n")}\nvarying vec2 v_texCoord;\nvarying vec2 v_quadCoord;\nvarying vec4 v_hitColor;\n${this.varyings_.map((function(t){return"varying "+t.type+" "+t.name+";"})).join("\n")}\n${this.fragmentShaderFunctions_.join("\n")}\nvoid main(void) {\n if (${this.discardExpression_}) { discard; }\n gl_FragColor = ${this.symbolColorExpression_};\n gl_FragColor.rgb *= gl_FragColor.a;\n if (u_hitDetection > 0) {\n if (gl_FragColor.a < 0.1) { discard; };\n gl_FragColor = v_hitColor;\n }\n}`:null}getStrokeVertexShader(){return this.hasStroke_?`#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n${Tf}\n${this.uniforms_.map((function(t){return"uniform "+t+";"})).join("\n")}\nattribute vec2 a_position;\nattribute float a_index;\nattribute vec2 a_segmentStart;\nattribute vec2 a_segmentEnd;\nattribute float a_parameters;\nattribute vec4 a_hitColor;\n${this.attributes_.map((function(t){return"attribute "+t+";"})).join("\n")}\nvarying vec2 v_segmentStart;\nvarying vec2 v_segmentEnd;\nvarying float v_angleStart;\nvarying float v_angleEnd;\nvarying float v_width;\nvarying vec4 v_hitColor;\n${this.varyings_.map((function(t){return"varying "+t.type+" "+t.name+";"})).join("\n")}\n${this.vertexShaderFunctions_.join("\n")}\nvec2 worldToPx(vec2 worldPos) {\n vec4 screenPos = u_projectionMatrix * vec4(worldPos, 0.0, 1.0);\n return (0.5 * screenPos.xy + 0.5) * u_viewportSizePx;\n}\n\nvec4 pxToScreen(vec2 pxPos) {\n vec2 screenPos = pxPos * 4.0 / u_viewportSizePx;\n return vec4(screenPos.xy, 0.0, 0.0);\n}\n\nvec2 getOffsetDirection(vec2 normalPx, vec2 tangentPx, float joinAngle) {\n if (cos(joinAngle) > 0.93) return normalPx - tangentPx;\n float halfAngle = joinAngle / 2.0;\n vec2 angleBisectorNormal = vec2(\n sin(halfAngle) * normalPx.x + cos(halfAngle) * normalPx.y,\n -cos(halfAngle) * normalPx.x + sin(halfAngle) * normalPx.y\n );\n float length = 1.0 / sin(halfAngle);\n return angleBisectorNormal * length;\n}\n\nvoid main(void) {\n float lineWidth = ${this.strokeWidthExpression_};\n float anglePrecision = 1500.0;\n float paramShift = 10000.0;\n v_angleStart = fract(a_parameters / paramShift) * paramShift / anglePrecision;\n v_angleEnd = fract(floor(a_parameters / paramShift + 0.5) / paramShift) * paramShift / anglePrecision;\n float vertexNumber = floor(a_parameters / paramShift / paramShift + 0.0001);\n vec2 tangentPx = worldToPx(a_segmentEnd) - worldToPx(a_segmentStart);\n tangentPx = normalize(tangentPx);\n vec2 normalPx = vec2(-tangentPx.y, tangentPx.x);\n float normalDir = vertexNumber < 0.5 || (vertexNumber > 1.5 && vertexNumber < 2.5) ? 1.0 : -1.0;\n float tangentDir = vertexNumber < 1.5 ? 1.0 : -1.0;\n float angle = vertexNumber < 1.5 ? v_angleStart : v_angleEnd;\n vec2 offsetPx = getOffsetDirection(normalPx * normalDir, tangentDir * tangentPx, angle) * lineWidth * 0.5;\n vec2 position = vertexNumber < 1.5 ? a_segmentStart : a_segmentEnd;\n gl_Position = u_projectionMatrix * vec4(position, 0.0, 1.0) + pxToScreen(offsetPx);\n v_segmentStart = worldToPx(a_segmentStart);\n v_segmentEnd = worldToPx(a_segmentEnd);\n v_width = lineWidth;\n v_hitColor = a_hitColor;\n${this.varyings_.map((function(t){return" "+t.name+" = "+t.expression+";"})).join("\n")}\n}`:null}getStrokeFragmentShader(){return this.hasStroke_?`#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n${Tf}\n${this.uniforms_.map((function(t){return"uniform "+t+";"})).join("\n")}\nvarying vec2 v_segmentStart;\nvarying vec2 v_segmentEnd;\nvarying float v_angleStart;\nvarying float v_angleEnd;\nvarying float v_width;\nvarying vec4 v_hitColor;\n${this.varyings_.map((function(t){return"varying "+t.type+" "+t.name+";"})).join("\n")}\n${this.fragmentShaderFunctions_.join("\n")}\nvec2 pxToWorld(vec2 pxPos) {\n vec2 screenPos = 2.0 * pxPos / u_viewportSizePx - 1.0;\n return (u_screenToWorldMatrix * vec4(screenPos, 0.0, 1.0)).xy;\n}\n\nfloat segmentDistanceField(vec2 point, vec2 start, vec2 end, float radius) {\n vec2 startToPoint = point - start;\n vec2 startToEnd = end - start;\n float ratio = clamp(dot(startToPoint, startToEnd) / dot(startToEnd, startToEnd), 0.0, 1.0);\n float dist = length(startToPoint - ratio * startToEnd);\n return 1.0 - smoothstep(radius - 1.0, radius, dist);\n}\n\nvoid main(void) {\n vec2 v_currentPoint = gl_FragCoord.xy / u_pixelRatio;\n #ifdef GL_FRAGMENT_PRECISION_HIGH\n vec2 v_worldPos = pxToWorld(v_currentPoint);\n if (\n abs(u_renderExtent[0] - u_renderExtent[2]) > 0.0 && (\n v_worldPos[0] < u_renderExtent[0] ||\n v_worldPos[1] < u_renderExtent[1] ||\n v_worldPos[0] > u_renderExtent[2] ||\n v_worldPos[1] > u_renderExtent[3]\n )\n ) {\n discard;\n }\n #endif\n if (${this.discardExpression_}) { discard; }\n gl_FragColor = ${this.strokeColorExpression_} * u_globalAlpha;\n gl_FragColor *= segmentDistanceField(v_currentPoint, v_segmentStart, v_segmentEnd, v_width);\n if (u_hitDetection > 0) {\n if (gl_FragColor.a < 0.1) { discard; };\n gl_FragColor = v_hitColor;\n }\n}`:null}getFillVertexShader(){return this.hasFill_?`#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n${Tf}\n${this.uniforms_.map((function(t){return"uniform "+t+";"})).join("\n")}\nattribute vec2 a_position;\nattribute vec4 a_hitColor;\n${this.attributes_.map((function(t){return"attribute "+t+";"})).join("\n")}\nvarying vec4 v_hitColor;\n${this.varyings_.map((function(t){return"varying "+t.type+" "+t.name+";"})).join("\n")}\n${this.vertexShaderFunctions_.join("\n")}\nvoid main(void) {\n gl_Position = u_projectionMatrix * vec4(a_position, 0.0, 1.0);\n${this.varyings_.map((function(t){return" "+t.name+" = "+t.expression+";"})).join("\n")}\n}`:null}getFillFragmentShader(){return this.hasFill_?`#ifdef GL_FRAGMENT_PRECISION_HIGH\nprecision highp float;\n#else\nprecision mediump float;\n#endif\n${Tf}\n${this.uniforms_.map((function(t){return"uniform "+t+";"})).join("\n")}\nvarying vec4 v_hitColor;\n${this.varyings_.map((function(t){return"varying "+t.type+" "+t.name+";"})).join("\n")}\n${this.fragmentShaderFunctions_.join("\n")}\nvec2 pxToWorld(vec2 pxPos) {\n vec2 screenPos = 2.0 * pxPos / u_viewportSizePx - 1.0;\n return (u_screenToWorldMatrix * vec4(screenPos, 0.0, 1.0)).xy;\n}\n\nvoid main(void) {\n #ifdef GL_FRAGMENT_PRECISION_HIGH\n vec2 v_worldPos = pxToWorld(gl_FragCoord.xy / u_pixelRatio);\n if (\n abs(u_renderExtent[0] - u_renderExtent[2]) > 0.0 && (\n v_worldPos[0] < u_renderExtent[0] ||\n v_worldPos[1] < u_renderExtent[1] ||\n v_worldPos[0] > u_renderExtent[2] ||\n v_worldPos[1] > u_renderExtent[3]\n )\n ) {\n discard;\n }\n #endif\n if (${this.discardExpression_}) { discard; }\n gl_FragColor = ${this.fillColorExpression_} * u_globalAlpha;\n if (u_hitDetection > 0) {\n if (gl_FragColor.a < 0.1) { discard; };\n gl_FragColor = v_hitColor;\n }\n}`:null}}var bf=class{constructor(){this.polygonBatch={entries:{},geometriesCount:0,verticesCount:0,ringsCount:0},this.pointBatch={entries:{},geometriesCount:0},this.lineStringBatch={entries:{},geometriesCount:0,verticesCount:0}}addFeatures(t){for(let e=0;e0?t[i-1]:null,a=o?o[o.length-1]:0,l=s[s.length-1],h=e.slice(a,l);s=a>0?s.map((t=>t-a)):s,this.addCoordinates_("Polygon",h,s,n,r)}break;case"MultiLineString":const o=i;for(let t=0,i=o.length;t0?o[t-1]:0,s=e.slice(i,o[t]);this.addCoordinates_("LinearRing",s,null,n,r)}break;case"MultiPoint":for(let t=0,i=e.length;t0&&wr(e,i,a[t],2))return this.addCoordinates_("Polygon",e.slice(0,i),a.slice(0,t),n,r),void this.addCoordinates_("Polygon",e.slice(i),a.slice(t).map((e=>e-a[t-1])),n,r)}this.polygonBatch.entries[r]||(this.polygonBatch.entries[r]={feature:n,flatCoordss:[],verticesCount:0,ringsCount:0,ringsVerticesCounts:[]}),s=e.length/2;const l=i.length,h=i.map(((t,e,i)=>e>0?(t-i[e-1])/2:t/2));this.polygonBatch.verticesCount+=s,this.polygonBatch.ringsCount+=l,this.polygonBatch.geometriesCount++,this.polygonBatch.entries[r].flatCoordss.push(e),this.polygonBatch.entries[r].ringsVerticesCounts.push(h),this.polygonBatch.entries[r].verticesCount+=s,this.polygonBatch.entries[r].ringsCount+=l;for(let t=0,i=a.length;t0?a[t-1]:0,s=e.slice(i,a[t]);this.addCoordinates_("LinearRing",s,null,n,r)}break;case"Point":this.pointBatch.entries[r]||(this.pointBatch.entries[r]={feature:n,flatCoordss:[]}),this.pointBatch.geometriesCount++,this.pointBatch.entries[r].flatCoordss.push(e);break;case"LineString":case"LinearRing":this.lineStringBatch.entries[r]||(this.lineStringBatch.entries[r]={feature:n,flatCoordss:[],verticesCount:0}),s=e.length/2,this.lineStringBatch.verticesCount+=s,this.lineStringBatch.geometriesCount++,this.lineStringBatch.entries[r].flatCoordss.push(e),this.lineStringBatch.entries[r].verticesCount+=s}}changeFeature(t){this.clearFeatureEntryInPointBatch_(t),this.clearFeatureEntryInPolygonBatch_(t),this.clearFeatureEntryInLineStringBatch_(t);const e=t.getGeometry();e&&this.addGeometry_(e,t)}removeFeature(t){this.clearFeatureEntryInPointBatch_(t),this.clearFeatureEntryInPolygonBatch_(t),this.clearFeatureEntryInLineStringBatch_(t)}clear(){this.polygonBatch.entries={},this.polygonBatch.geometriesCount=0,this.polygonBatch.verticesCount=0,this.polygonBatch.ringsCount=0,this.lineStringBatch.entries={},this.lineStringBatch.geometriesCount=0,this.lineStringBatch.verticesCount=0,this.pointBatch.entries={},this.pointBatch.geometriesCount=0}};var Pf=class extends Od{constructor(t,e){super(t),this.batch_=new bf,this.styleRenderers_=e,this.buffers=[],this.setTile(t.tile)}uploadTile(){this.batch_.clear();const t=this.tile.getSourceTiles(),e=t.reduce(((t,e)=>t.concat(e.getFeatures())),[]);this.batch_.addFeatures(e);const i=Zt([1,0,0,1,0,0],-t[0].extent[0],-t[0].extent[1]),n=this.styleRenderers_.map(((t,e)=>t.generateBuffers(this.batch_,i).then((t=>{this.buffers[e]=t}))));Promise.all(n).then((()=>{this.setReady()}))}};function If(t,e){switch(t){case"square":case"image":return"1.0";case"circle":return`(1.0-smoothstep(1.-4./${e},1.,dot(v_quadCoord-.5,v_quadCoord-.5)*4.))`;case"triangle":const i="(v_quadCoord*2.-1.)",n=`(atan(${i}.x,${i}.y))`;return`(1.0-smoothstep(.5-3./${e},.5,cos(floor(.5+${n}/2.094395102)*2.094395102-${n})*length(${i})))`;default:throw new Error(`Unexpected symbol type: ${t}`)}}function Ff(t){const e=hs(t);return[256*e[0]+e[1],256*e[2]+Math.round(255*e[3])]}function Lf(t){return t===yg.COLOR?2:t===yg.NUMBER_ARRAY?4:1}function Mf(t){const e=Lf(t);return e>1?`vec${e}`:"float"}function Af(t){const e={inFragmentShader:!1,variables:[],attributes:[],stringLiteralsMap:{},functions:{},style:t},i={inFragmentShader:!0,variables:e.variables,attributes:[],stringLiteralsMap:e.stringLiteralsMap,functions:{},style:t},n=new Rf,r={};if(function(t,e,i,n,r){if(!("symbol"in t))return;const s=t.symbol;if("color"in s){const t=s.color,i=void 0!==s.opacity?s.opacity:1,n=Pg(r,t,yg.COLOR),o=Pg(r,i,yg.NUMBER);e.setSymbolColorExpression(`vec4(${n}.rgb, ${n}.a * ${o})`)}if("image"===s.symbolType&&s.src){const t=new Image;t.crossOrigin=void 0===s.crossOrigin?"anonymous":s.crossOrigin,t.src=s.src,e.addUniform("sampler2D u_texture").setSymbolColorExpression(`${e.getSymbolColorExpression()} * texture2D(u_texture, v_texCoord)`),i.u_texture=t}else if("symbolType"in s){let t=e.getSymbolSizeExpression();"size"in s&&(t=Pg(r,s.size,yg.NUMBER_ARRAY|yg.NUMBER));const i=If(s.symbolType,`vec2(${t}).x`);e.setSymbolColorExpression(`${e.getSymbolColorExpression()} * vec4(1.0, 1.0, 1.0, ${i})`)}if("size"in s){const t=Pg(n,s.size,yg.NUMBER_ARRAY|yg.NUMBER);e.setSymbolSizeExpression(`vec2(${t})`)}"textureCoord"in s&&e.setTextureCoordinateExpression(Pg(n,s.textureCoord,yg.NUMBER_ARRAY)),"offset"in s&&e.setSymbolOffsetExpression(Pg(n,s.offset,yg.NUMBER_ARRAY)),"rotation"in s&&e.setSymbolRotationExpression(Pg(n,s.rotation,yg.NUMBER)),"rotateWithView"in s&&e.setSymbolRotateWithView(!!s.rotateWithView)}(t,n,r,e,i),function(t,e,i,n,r){"stroke-color"in t&&e.setStrokeColorExpression(Pg(r,t["stroke-color"],yg.COLOR)),"stroke-width"in t&&e.setStrokeWidthExpression(Pg(n,t["stroke-width"],yg.NUMBER))}(t,n,0,e,i),function(t,e,i,n,r){"fill-color"in t&&e.setFillColorExpression(Pg(r,t["fill-color"],yg.COLOR))}(t,n,0,0,i),t.filter){const e=Pg(i,t.filter,yg.BOOLEAN);n.setFragmentDiscardExpression(`!${e}`)}i.variables.forEach((function(i){const s=Bg(i.name);let o;n.addUniform(`${Mf(i.type)} ${s}`),o=i.type===yg.STRING?()=>Rg(e,t.variables[i.name]):i.type===yg.COLOR?()=>Ff([...hs(t.variables[i.name]||"#eee")]):i.type===yg.BOOLEAN?()=>t.variables[i.name]?1:0:()=>t.variables[i.name],r[s]=o})),i.attributes.forEach((function(t){e.attributes.find((e=>e.name===t.name))||e.attributes.push(t);let i=Mf(t.type),r=`a_${t.name}`;t.type===yg.COLOR&&(i="vec4",r=`unpackColor(${r})`,n.addVertexShaderFunction("vec4 unpackColor(vec2 packedColor) {\n return fract(packedColor[1] / 256.0) * vec4(\n fract(floor(packedColor[0] / 256.0) / 256.0),\n fract(packedColor[0] / 256.0),\n fract(floor(packedColor[1] / 256.0) / 256.0),\n 1.0\n );\n}")),n.addVarying(`v_${t.name}`,i,r)})),e.attributes.forEach((function(t){n.addAttribute(`${Mf(t.type)} a_${t.name}`)}));const s=e.attributes.map((function(t){let i;return i=t.callback?t.callback:t.type===yg.STRING?i=>Rg(e,i.get(t.name)):t.type===yg.COLOR?e=>Ff([...hs(e.get(t.name)||"#eee")]):t.type===yg.BOOLEAN?e=>e.get(t.name)?1:0:e=>e.get(t.name),{name:t.name,size:Lf(t.type),callback:i}}));for(const t in e.functions)n.addVertexShaderFunction(e.functions[t]);for(const t in i.functions)n.addFragmentShaderFunction(i.functions[t]);return{builder:n,attributes:s.reduce(((t,e)=>({...t,[e.name]:{callback:e.callback,size:e.size}})),{}),uniforms:r}}var Of=class{constructor(t){this.first_,this.last_,this.head_,this.circular_=void 0===t||t,this.length_=0}insertItem(t){const e={prev:void 0,next:void 0,data:t},i=this.head_;if(i){const t=i.next;e.prev=i,e.next=t,i.next=e,t&&(t.prev=e),i===this.last_&&(this.last_=e)}else this.first_=e,this.last_=e,this.circular_&&(e.next=e,e.prev=e);this.head_=e,this.length_++}removeItem(){const t=this.head_;if(t){const e=t.next,i=t.prev;e&&(e.prev=i),i&&(i.next=e),this.head_=e||i,this.first_===this.last_?(this.head_=void 0,this.first_=void 0,this.last_=void 0):this.first_===t?this.first_=this.head_:this.last_===t&&(this.last_=i?this.head_.prev:this.head_),this.length_--}}firstItem(){if(this.head_=this.first_,this.head_)return this.head_.data}lastItem(){if(this.head_=this.last_,this.head_)return this.head_.data}nextItem(){if(this.head_&&this.head_.next)return this.head_=this.head_.next,this.head_.data}getNextItem(){if(this.head_&&this.head_.next)return this.head_.next.data}prevItem(){if(this.head_&&this.head_.prev)return this.head_=this.head_.prev,this.head_.data}getPrevItem(){if(this.head_&&this.head_.prev)return this.head_.prev.data}getCurrItem(){if(this.head_)return this.head_.data}setFirstItem(){this.circular_&&this.head_&&(this.first_=this.head_,this.last_=this.head_.prev)}concat(t){if(t.head_){if(this.head_){const e=this.head_.next;this.head_.next=t.first_,t.first_.prev=this.head_,e.prev=t.last_,t.last_.next=e,this.length_+=t.length_}else this.head_=t.head_,this.first_=t.first_,this.last_=t.last_,this.length_=t.length_;t.head_=void 0,t.first_=void 0,t.last_=void 0,t.length_=0}}getLength(){return this.length_}};const Nf="renderOrder";var Df=class extends no{constructor(t){t=t||{};const e=Object.assign({},t);delete e.style,delete e.renderBuffer,delete e.updateWhileAnimating,delete e.updateWhileInteracting,super(e),this.declutter_=void 0!==t.declutter&&t.declutter,this.renderBuffer_=void 0!==t.renderBuffer?t.renderBuffer:100,this.style_=null,this.styleFunction_=void 0,this.setStyle(t.style),this.updateWhileAnimating_=void 0!==t.updateWhileAnimating&&t.updateWhileAnimating,this.updateWhileInteracting_=void 0!==t.updateWhileInteracting&&t.updateWhileInteracting}getDeclutter(){return this.declutter_}getFeatures(t){return super.getFeatures(t)}getRenderBuffer(){return this.renderBuffer_}getRenderOrder(){return this.get(Nf)}getStyle(){return this.style_}getStyleFunction(){return this.styleFunction_}getUpdateWhileAnimating(){return this.updateWhileAnimating_}getUpdateWhileInteracting(){return this.updateWhileInteracting_}renderDeclutter(t){t.declutterTree||(t.declutterTree=new Uh(9)),this.getRenderer().renderDeclutter(t)}setRenderOrder(t){this.set(Nf,t)}setStyle(t){let e;if(void 0===t)e=df;else if(null===t)e=null;else if("function"==typeof t)e=t;else if(t instanceof pf)e=t;else if(Array.isArray(t)){const i=t.length,n=new Array(i);for(let e=0;e80*i){n=s=t[0],r=o=t[1];for(var f=i;fs&&(s=a),l>o&&(o=l);h=0!==(h=Math.max(s-n,o-r))?32767/h:0}return Wf(d,g,i,n,r,h,0),g}function Xf(t,e,i,n,r){var s,o;if(r===gp(t,e,i,n)>0)for(s=e;s=e;s-=n)o=cp(s,t[s],t[s+1],o);return o&&rp(o,o.next)&&(up(o),o=o.next),o}function Vf(t,e){if(!t)return t;e||(e=t);var i,n=t;do{if(i=!1,n.steiner||!rp(n,n.next)&&0!==np(n.prev,n,n.next))n=n.next;else{if(up(n),(n=e=n.prev)===n.next)break;i=!0}}while(i||n!==e);return e}function Wf(t,e,i,n,r,s,o){if(t){!o&&s&&function(t,e,i,n){var r=t;do{0===r.z&&(r.z=Qf(r.x,r.y,e,i,n)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==t);r.prevZ.nextZ=null,r.prevZ=null,function(t){var e,i,n,r,s,o,a,l,h=1;do{for(i=t,t=null,s=null,o=0;i;){for(o++,n=i,a=0,e=0;e0||l>0&&n;)0!==a&&(0===l||!n||i.z<=n.z)?(r=i,i=i.nextZ,a--):(r=n,n=n.nextZ,l--),s?s.nextZ=r:t=r,r.prevZ=s,s=r;i=n}s.nextZ=null,h*=2}while(o>1)}(r)}(t,n,r,s);for(var a,l,h=t;t.prev!==t.next;)if(a=t.prev,l=t.next,s?Yf(t,n,r,s):Zf(t))e.push(a.i/i|0),e.push(t.i/i|0),e.push(l.i/i|0),up(t),t=l.next,h=l.next;else if((t=l)===h){o?1===o?Wf(t=Kf(Vf(t),e,i),e,i,n,r,s,2):2===o&&Hf(t,e,i,n,r,s):Wf(Vf(t),e,i,n,r,s,1);break}}}function Zf(t){var e=t.prev,i=t,n=t.next;if(np(e,i,n)>=0)return!1;for(var r=e.x,s=i.x,o=n.x,a=e.y,l=i.y,h=n.y,c=rs?r>o?r:o:s>o?s:o,g=a>l?a>h?a:h:l>h?l:h,f=n.next;f!==e;){if(f.x>=c&&f.x<=d&&f.y>=u&&f.y<=g&&ep(r,a,s,l,o,h,f.x,f.y)&&np(f.prev,f,f.next)>=0)return!1;f=f.next}return!0}function Yf(t,e,i,n){var r=t.prev,s=t,o=t.next;if(np(r,s,o)>=0)return!1;for(var a=r.x,l=s.x,h=o.x,c=r.y,u=s.y,d=o.y,g=al?a>h?a:h:l>h?l:h,m=c>u?c>d?c:d:u>d?u:d,_=Qf(g,f,e,i,n),y=Qf(p,m,e,i,n),x=t.prevZ,v=t.nextZ;x&&x.z>=_&&v&&v.z<=y;){if(x.x>=g&&x.x<=p&&x.y>=f&&x.y<=m&&x!==r&&x!==o&&ep(a,c,l,u,h,d,x.x,x.y)&&np(x.prev,x,x.next)>=0)return!1;if(x=x.prevZ,v.x>=g&&v.x<=p&&v.y>=f&&v.y<=m&&v!==r&&v!==o&&ep(a,c,l,u,h,d,v.x,v.y)&&np(v.prev,v,v.next)>=0)return!1;v=v.nextZ}for(;x&&x.z>=_;){if(x.x>=g&&x.x<=p&&x.y>=f&&x.y<=m&&x!==r&&x!==o&&ep(a,c,l,u,h,d,x.x,x.y)&&np(x.prev,x,x.next)>=0)return!1;x=x.prevZ}for(;v&&v.z<=y;){if(v.x>=g&&v.x<=p&&v.y>=f&&v.y<=m&&v!==r&&v!==o&&ep(a,c,l,u,h,d,v.x,v.y)&&np(v.prev,v,v.next)>=0)return!1;v=v.nextZ}return!0}function Kf(t,e,i){var n=t;do{var r=n.prev,s=n.next.next;!rp(r,s)&&sp(r,n,n.next,s)&&lp(r,s)&&lp(s,r)&&(e.push(r.i/i|0),e.push(n.i/i|0),e.push(s.i/i|0),up(n),up(n.next),n=t=s),n=n.next}while(n!==t);return Vf(n)}function Hf(t,e,i,n,r,s){var o=t;do{for(var a=o.next.next;a!==o.prev;){if(o.i!==a.i&&ip(o,a)){var l=hp(o,a);return o=Vf(o,o.next),l=Vf(l,l.next),Wf(o,e,i,n,r,s,0),void Wf(l,e,i,n,r,s,0)}a=a.next}o=o.next}while(o!==t)}function qf(t,e){return t.x-e.x}function $f(t,e){var i=function(t,e){var i,n=e,r=t.x,s=t.y,o=-1/0;do{if(s<=n.y&&s>=n.next.y&&n.next.y!==n.y){var a=n.x+(s-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(a<=r&&a>o&&(o=a,i=n.x=n.x&&n.x>=c&&r!==n.x&&ep(si.x||n.x===i.x&&Jf(i,n)))&&(i=n,d=l)),n=n.next}while(n!==h);return i}(t,e);if(!i)return e;var n=hp(i,t);return Vf(n,n.next),Vf(i,i.next)}function Jf(t,e){return np(t.prev,t,e.prev)<0&&np(e.next,t,t.next)<0}function Qf(t,e,i,n,r){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-i)*r|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-n)*r|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function tp(t){var e=t,i=t;do{(e.x=(t-o)*(s-a)&&(t-o)*(n-a)>=(i-o)*(e-a)&&(i-o)*(s-a)>=(r-o)*(n-a)}function ip(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var i=t;do{if(i.i!==t.i&&i.next.i!==t.i&&i.i!==e.i&&i.next.i!==e.i&&sp(i,i.next,t,e))return!0;i=i.next}while(i!==t);return!1}(t,e)&&(lp(t,e)&&lp(e,t)&&function(t,e){var i=t,n=!1,r=(t.x+e.x)/2,s=(t.y+e.y)/2;do{i.y>s!=i.next.y>s&&i.next.y!==i.y&&r<(i.next.x-i.x)*(s-i.y)/(i.next.y-i.y)+i.x&&(n=!n),i=i.next}while(i!==t);return n}(t,e)&&(np(t.prev,t,e.prev)||np(t,e.prev,e))||rp(t,e)&&np(t.prev,t,t.next)>0&&np(e.prev,e,e.next)>0)}function np(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)}function rp(t,e){return t.x===e.x&&t.y===e.y}function sp(t,e,i,n){var r=ap(np(t,e,i)),s=ap(np(t,e,n)),o=ap(np(i,n,t)),a=ap(np(i,n,e));return r!==s&&o!==a||(!(0!==r||!op(t,i,e))||(!(0!==s||!op(t,n,e))||(!(0!==o||!op(i,t,n))||!(0!==a||!op(i,e,n)))))}function op(t,e,i){return e.x<=Math.max(t.x,i.x)&&e.x>=Math.min(t.x,i.x)&&e.y<=Math.max(t.y,i.y)&&e.y>=Math.min(t.y,i.y)}function ap(t){return t>0?1:t<0?-1:0}function lp(t,e){return np(t.prev,t,t.next)<0?np(t,e,t.next)>=0&&np(t,t.prev,e)>=0:np(t,e,t.prev)<0||np(t,t.next,e)<0}function hp(t,e){var i=new dp(t.i,t.x,t.y),n=new dp(e.i,e.x,e.y),r=t.next,s=e.prev;return t.next=e,e.prev=t,i.next=r,r.prev=i,n.next=i,i.prev=n,s.next=n,n.prev=s,n}function cp(t,e,i,n){var r=new dp(t,e,i);return n?(r.next=n.next,r.prev=n,n.next.prev=r,n.next=r):(r.prev=r,r.next=r),r}function up(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function dp(t,e,i){this.i=t,this.x=e,this.y=i,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}function gp(t,e,i,n){for(var r=0,s=e,o=i-n;s0&&(n+=t[r-1].length,i.holes.push(n))}return i};var fp=Bf(Uf.exports);const pp=[],mp={vertexPosition:0,indexPosition:0};function _p(t,e,i,n,r){t[e+0]=i,t[e+1]=n,t[e+2]=r}function yp(t,e){const i=256,n=255;return(e=e||[])[0]=Math.floor(t/i/i/i)/n,e[1]=Math.floor(t/i/i)%i/n,e[2]=Math.floor(t/i)%i/n,e[3]=t%i/n,e}function xp(t){let e=0;const i=256,n=255;return e+=Math.round(t[0]*i*i*i*n),e+=Math.round(t[1]*i*i*n),e+=Math.round(t[2]*i*n),e+=Math.round(t[3]*n),e}function vp(){const t='const e="GENERATE_POLYGON_BUFFERS",t="GENERATE_POINT_BUFFERS",n="GENERATE_LINE_STRING_BUFFERS",r={1:"The view center is not defined",2:"The view resolution is not defined",3:"The view rotation is not defined",4:"`image` and `src` cannot be provided at the same time",5:"`imgSize` must be set when `image` is provided",7:"`format` must be set when `url` is set",8:"Unknown `serverType` configured",9:"`url` must be configured or set using `#setUrl()`",10:"The default `geometryFunction` can only handle `Point` geometries",11:"`options.featureTypes` must be an Array",12:"`options.geometryName` must also be provided when `options.bbox` is set",13:"Invalid corner",14:"Invalid color",15:"Tried to get a value for a key that does not exist in the cache",16:"Tried to set a value for a key that is used already",17:"`resolutions` must be sorted in descending order",18:"Either `origin` or `origins` must be configured, never both",19:"Number of `tileSizes` and `resolutions` must be equal",20:"Number of `origins` and `resolutions` must be equal",22:"Either `tileSize` or `tileSizes` must be configured, never both",24:"Invalid extent or geometry provided as `geometry`",25:"Cannot fit empty extent provided as `geometry`",26:"Features must have an id set",27:"Features must have an id set",28:\'`renderMode` must be `"hybrid"` or `"vector"`\',30:"The passed `feature` was already added to the source",31:"Tried to enqueue an `element` that was already added to the queue",32:"Transformation matrix cannot be inverted",33:"Invalid units",34:"Invalid geometry layout",36:"Unknown SRS type",37:"Unknown geometry type found",38:"`styleMapValue` has an unknown type",39:"Unknown geometry type",40:"Expected `feature` to have a geometry",41:"Expected an `ol/style/Style` or an array of `ol/style/Style.js`",42:"Question unknown, the answer is 42",43:"Expected `layers` to be an array or a `Collection`",47:"Expected `controls` to be an array or an `ol/Collection`",48:"Expected `interactions` to be an array or an `ol/Collection`",49:"Expected `overlays` to be an array or an `ol/Collection`",50:"`options.featureTypes` should be an Array",51:"Either `url` or `tileJSON` options must be provided",52:"Unknown `serverType` configured",53:"Unknown `tierSizeCalculation` configured",55:"The {-y} placeholder requires a tile grid with extent",56:"mapBrowserEvent must originate from a pointer event",57:"At least 2 conditions are required",59:"Invalid command found in the PBF",60:"Missing or invalid `size`",61:"Cannot determine IIIF Image API version from provided image information JSON",62:"A `WebGLArrayBuffer` must either be of type `ELEMENT_ARRAY_BUFFER` or `ARRAY_BUFFER`",64:"Layer opacity must be a number",66:"`forEachFeatureAtCoordinate` cannot be used on a WebGL layer if the hit detection logic has not been enabled. This is done by providing adequate shaders using the `hitVertexShader` and `hitFragmentShader` properties of `WebGLPointsLayerRenderer`",67:"A layer can only be added to the map once. Use either `layer.setMap()` or `map.addLayer()`, not both",68:"A VectorTile source can only be rendered if it has a projection compatible with the view projection",69:"`width` or `height` cannot be provided together with `scale`"};class o extends Error{constructor(e){const t=r[e];super(t),this.code=e,this.name="AssertionError",this.message=t}}var i=o;function a(e,t){const n=t[0],r=t[1];return t[0]=e[0]*n+e[2]*r+e[4],t[1]=e[1]*n+e[3]*r+e[5],t}function s(e,t){const n=(r=t)[0]*r[3]-r[1]*r[2];var r;!function(e,t){if(!e)throw new i(t)}(0!==n,32);const o=t[0],a=t[1],s=t[2],u=t[3],f=t[4],x=t[5];return e[0]=u/n,e[1]=-a/n,e[2]=-s/n,e[3]=o/n,e[4]=(s*x-u*f)/n,e[5]=-(o*x-a*f)/n,e}function u(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}new Array(6);var f={exports:{}};function x(e,t,n){n=n||2;var r,o,i,a,s,u,f,x=t&&t.length,h=x?t[0]*n:e.length,v=l(e,0,h,n,!0),d=[];if(!v||v.next===v.prev)return d;if(x&&(v=function(e,t,n,r){var o,i,a,s=[];for(o=0,i=t.length;o80*n){r=i=e[0],o=a=e[1];for(var y=n;yi&&(i=s),u>a&&(a=u);f=0!==(f=Math.max(i-r,a-o))?32767/f:0}return c(v,d,n,r,o,f,0),d}function l(e,t,n,r,o){var i,a;if(o===P(e,t,n,r)>0)for(i=t;i=t;i-=r)a=k(i,e[i],e[i+1],a);return a&&F(a,a.next)&&(R(a),a=a.next),a}function h(e,t){if(!e)return e;t||(t=e);var n,r=e;do{if(n=!1,r.steiner||!F(r,r.next)&&0!==Z(r.prev,r,r.next))r=r.next;else{if(R(r),(r=t=r.prev)===r.next)break;n=!0}}while(n||r!==t);return t}function c(e,t,n,r,o,i,a){if(e){!a&&i&&function(e,t,n,r){var o=e;do{0===o.z&&(o.z=w(o.x,o.y,t,n,r)),o.prevZ=o.prev,o.nextZ=o.next,o=o.next}while(o!==e);o.prevZ.nextZ=null,o.prevZ=null,function(e){var t,n,r,o,i,a,s,u,f=1;do{for(n=e,e=null,i=null,a=0;n;){for(a++,r=n,s=0,t=0;t0||u>0&&r;)0!==s&&(0===u||!r||n.z<=r.z)?(o=n,n=n.nextZ,s--):(o=r,r=r.nextZ,u--),i?i.nextZ=o:e=o,o.prevZ=i,i=o;n=r}i.nextZ=null,f*=2}while(a>1)}(o)}(e,r,o,i);for(var s,u,f=e;e.prev!==e.next;)if(s=e.prev,u=e.next,i?d(e,r,o,i):v(e))t.push(s.i/n|0),t.push(e.i/n|0),t.push(u.i/n|0),R(e),e=u.next,f=u.next;else if((e=u)===f){a?1===a?c(e=y(h(e),t,n),t,n,r,o,i,2):2===a&&p(e,t,n,r,o,i):c(h(e),t,n,r,o,i,1);break}}}function v(e){var t=e.prev,n=e,r=e.next;if(Z(t,n,r)>=0)return!1;for(var o=t.x,i=n.x,a=r.x,s=t.y,u=n.y,f=r.y,x=oi?o>a?o:a:i>a?i:a,c=s>u?s>f?s:f:u>f?u:f,v=r.next;v!==t;){if(v.x>=x&&v.x<=h&&v.y>=l&&v.y<=c&&E(o,s,i,u,a,f,v.x,v.y)&&Z(v.prev,v,v.next)>=0)return!1;v=v.next}return!0}function d(e,t,n,r){var o=e.prev,i=e,a=e.next;if(Z(o,i,a)>=0)return!1;for(var s=o.x,u=i.x,f=a.x,x=o.y,l=i.y,h=a.y,c=su?s>f?s:f:u>f?u:f,y=x>l?x>h?x:h:l>h?l:h,p=w(c,v,t,n,r),b=w(d,y,t,n,r),g=e.prevZ,m=e.nextZ;g&&g.z>=p&&m&&m.z<=b;){if(g.x>=c&&g.x<=d&&g.y>=v&&g.y<=y&&g!==o&&g!==a&&E(s,x,u,l,f,h,g.x,g.y)&&Z(g.prev,g,g.next)>=0)return!1;if(g=g.prevZ,m.x>=c&&m.x<=d&&m.y>=v&&m.y<=y&&m!==o&&m!==a&&E(s,x,u,l,f,h,m.x,m.y)&&Z(m.prev,m,m.next)>=0)return!1;m=m.nextZ}for(;g&&g.z>=p;){if(g.x>=c&&g.x<=d&&g.y>=v&&g.y<=y&&g!==o&&g!==a&&E(s,x,u,l,f,h,g.x,g.y)&&Z(g.prev,g,g.next)>=0)return!1;g=g.prevZ}for(;m&&m.z<=b;){if(m.x>=c&&m.x<=d&&m.y>=v&&m.y<=y&&m!==o&&m!==a&&E(s,x,u,l,f,h,m.x,m.y)&&Z(m.prev,m,m.next)>=0)return!1;m=m.nextZ}return!0}function y(e,t,n){var r=e;do{var o=r.prev,i=r.next.next;!F(o,i)&&T(o,r,r.next,i)&&z(o,i)&&z(i,o)&&(t.push(o.i/n|0),t.push(r.i/n|0),t.push(i.i/n|0),R(r),R(r.next),r=e=i),r=r.next}while(r!==e);return h(r)}function p(e,t,n,r,o,i){var a=e;do{for(var s=a.next.next;s!==a.prev;){if(a.i!==s.i&&M(a,s)){var u=U(a,s);return a=h(a,a.next),u=h(u,u.next),c(a,t,n,r,o,i,0),void c(u,t,n,r,o,i,0)}s=s.next}a=a.next}while(a!==e)}function b(e,t){return e.x-t.x}function g(e,t){var n=function(e,t){var n,r=t,o=e.x,i=e.y,a=-1/0;do{if(i<=r.y&&i>=r.next.y&&r.next.y!==r.y){var s=r.x+(i-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(s<=o&&s>a&&(a=s,n=r.x=r.x&&r.x>=x&&o!==r.x&&E(in.x||r.x===n.x&&m(n,r)))&&(n=r,h=u)),r=r.next}while(r!==f);return n}(e,t);if(!n)return t;var r=U(n,e);return h(r,r.next),h(n,n.next)}function m(e,t){return Z(e.prev,e,t.prev)<0&&Z(t.next,e,e.next)<0}function w(e,t,n,r,o){return(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-n)*o|0)|e<<8))|e<<4))|e<<2))|e<<1))|(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-r)*o|0)|t<<8))|t<<4))|t<<2))|t<<1))<<1}function A(e){var t=e,n=e;do{(t.x=(e-a)*(i-s)&&(e-a)*(r-s)>=(n-a)*(t-s)&&(n-a)*(i-s)>=(o-a)*(r-s)}function M(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!function(e,t){var n=e;do{if(n.i!==e.i&&n.next.i!==e.i&&n.i!==t.i&&n.next.i!==t.i&&T(n,n.next,e,t))return!0;n=n.next}while(n!==e);return!1}(e,t)&&(z(e,t)&&z(t,e)&&function(e,t){var n=e,r=!1,o=(e.x+t.x)/2,i=(e.y+t.y)/2;do{n.y>i!=n.next.y>i&&n.next.y!==n.y&&o<(n.next.x-n.x)*(i-n.y)/(n.next.y-n.y)+n.x&&(r=!r),n=n.next}while(n!==e);return r}(e,t)&&(Z(e.prev,e,t.prev)||Z(e,t.prev,t))||F(e,t)&&Z(e.prev,e,e.next)>0&&Z(t.prev,t,t.next)>0)}function Z(e,t,n){return(t.y-e.y)*(n.x-t.x)-(t.x-e.x)*(n.y-t.y)}function F(e,t){return e.x===t.x&&e.y===t.y}function T(e,t,n,r){var o=S(Z(e,t,n)),i=S(Z(e,t,r)),a=S(Z(n,r,e)),s=S(Z(n,r,t));return o!==i&&a!==s||(!(0!==o||!I(e,n,t))||(!(0!==i||!I(e,r,t))||(!(0!==a||!I(n,e,r))||!(0!==s||!I(n,t,r)))))}function I(e,t,n){return t.x<=Math.max(e.x,n.x)&&t.x>=Math.min(e.x,n.x)&&t.y<=Math.max(e.y,n.y)&&t.y>=Math.min(e.y,n.y)}function S(e){return e>0?1:e<0?-1:0}function z(e,t){return Z(e.prev,e,e.next)<0?Z(e,t,e.next)>=0&&Z(e,e.prev,t)>=0:Z(e,t,e.prev)<0||Z(e,e.next,t)<0}function U(e,t){var n=new B(e.i,e.x,e.y),r=new B(t.i,t.x,t.y),o=e.next,i=t.prev;return e.next=t,t.prev=e,n.next=o,o.prev=n,r.next=n,n.prev=r,i.next=r,r.prev=i,r}function k(e,t,n,r){var o=new B(e,t,n);return r?(o.next=r.next,o.prev=r,r.next.prev=o,r.next=o):(o.prev=o,o.next=o),o}function R(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function B(e,t,n){this.i=e,this.x=t,this.y=n,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}function P(e,t,n,r){for(var o=0,i=t,a=n-r;i0&&(r+=e[o-1].length,n.holes.push(r))}return n};var N=u(f.exports);const _=[],O={vertexPosition:0,indexPosition:0};function q(e,t,n,r,o){e[t+0]=n,e[t+1]=r,e[t+2]=o}function L(e,t,n,r,o,i){const a=3+o,s=e[t+0],u=e[t+1],f=_;f.length=o;for(let n=0;n0?u:2*Math.PI-u}const g=null!==o;let m=0,w=0;if(null!==r){m=b(d,y,a(x,[...[e[r],e[r+1]]]))}if(g){w=b(y,d,a(x,[...[e[o],e[o+1]]]))}i.push(c[0],c[1],v[0],v[1],p(0,m,w)),i.push(...u),i.push(c[0],c[1],v[0],v[1],p(1,m,w)),i.push(...u),i.push(c[0],c[1],v[0],v[1],p(2,m,w)),i.push(...u),i.push(c[0],c[1],v[0],v[1],p(3,m,w)),i.push(...u),s.push(h,h+1,h+2,h+1,h+3,h+2)}function G(e,t,n,r,o){const i=2+o;let a=t;const s=e.slice(a,a+o);a+=o;const u=e[a++];let f=0;const x=new Array(u-1);for(let t=0;t{const o=r.data;switch(o.type){case t:{const e=3,t=2,n=o.customAttributesSize,r=t+n,i=new Float32Array(o.renderInstructions),a=i.length/r,s=4*a*(n+e),u=new Uint32Array(6*a),f=new Float32Array(s);let x;for(let e=0;e0?a+(n-1)*r:null,n{const e=t.data;if(e.type===Gf){const i=e.projectionTransform;this.verticesBuffer_.fromArrayBuffer(e.vertexBuffer),this.helper.flushBufferData(this.verticesBuffer_),this.indicesBuffer_.fromArrayBuffer(e.indexBuffer),this.helper.flushBufferData(this.indicesBuffer_),this.renderTransform_=i,Kt(this.invertRenderTransform_,this.renderTransform_),this.renderInstructions_=new Float32Array(t.data.renderInstructions),e.id===this.lastSentId&&(this.ready=!0),this.getLayer().changed()}})),this.featureCache_={},this.featureCount_=0;const s=this.getLayer().getSource();this.sourceListenKeys_=[D(s,ic,this.handleSourceFeatureAdded_,this),D(s,nc,this.handleSourceFeatureChanged_,this),D(s,sc,this.handleSourceFeatureDelete_,this),D(s,rc,this.handleSourceFeatureClear_,this)],s.forEachFeature((t=>{this.featureCache_[V(t)]={feature:t,properties:t.getProperties(),geometry:t.getGeometry()},this.featureCount_++}))}afterHelperCreated(){this.program_=this.helper.getProgram(this.fragmentShader_,this.vertexShader_),this.hitDetectionEnabled_&&(this.hitRenderTarget_=new Qd(this.helper))}handleSourceFeatureAdded_(t){const e=t.feature;this.featureCache_[V(e)]={feature:e,properties:e.getProperties(),geometry:e.getGeometry()},this.featureCount_++}handleSourceFeatureChanged_(t){const e=t.feature;this.featureCache_[V(e)]={feature:e,properties:e.getProperties(),geometry:e.getGeometry()}}handleSourceFeatureDelete_(t){const e=t.feature;delete this.featureCache_[V(e)],this.featureCount_--}handleSourceFeatureClear_(){this.featureCache_={},this.featureCount_=0}renderFrame(t){const e=this.helper.getGL();this.preRender(e,t);const[i,n,r]=this.getWorldParameters_(t);this.renderWorlds(t,!1,i,n,r),this.helper.finalizeDraw(t,this.dispatchPreComposeEvent,this.dispatchPostComposeEvent);const s=this.helper.getCanvas();return this.hitDetectionEnabled_&&(this.renderWorlds(t,!0,i,n,r),this.hitRenderTarget_.clearCachedData()),this.postRender(e,t),s}getWorldParameters_(t){const e=t.viewState.projection,i=this.getLayer().getSource().getWrapX()&&e.canWrapX(),n=e.getExtent(),r=t.extent,s=i?Me(n):null,o=i?Math.ceil((r[2]-n[2])/s)+1:1;return[i?Math.floor((r[0]-n[0])/s):0,o,s]}prepareFrameInternal(t){const e=this.getLayer(),i=e.getSource(),n=t.viewState,r=!t.viewHints[As]&&!t.viewHints[Os],s=!de(this.previousExtent_,t.extent),o=this.sourceRevision_e+(t[i].size||1)),0)}function Tp(t,e,i,n){const r=(2+Ep(i))*t.geometriesCount;e&&e.length===r||(e=new Float32Array(r));const s=[];let o=0;for(const r in t.entries){const a=t.entries[r];for(let t=0,r=a.flatCoordss.length;t({name:`a_${t}`,size:this.customAttributes_[t].size||1,type:Vd.FLOAT})));this.polygonAttributesDesc_=[{name:Ip,size:2,type:Vd.FLOAT},...n],this.lineStringAttributesDesc_=[{name:Lp,size:2,type:Vd.FLOAT},{name:Mp,size:2,type:Vd.FLOAT},{name:Ap,size:1,type:Vd.FLOAT},...n],this.pointAttributesDesc_=[{name:Ip,size:2,type:Vd.FLOAT},{name:Fp,size:1,type:Vd.FLOAT},...n]}async generateBuffers(t,e){const i=this.generateRenderInstructions_(t,e),[n,r,s]=await Promise.all([this.generateBuffersForType_(i.polygonInstructions,"Polygon",e),this.generateBuffersForType_(i.lineStringInstructions,"LineString",e),this.generateBuffersForType_(i.pointInstructions,"Point",e)]);return{polygonBuffers:n,lineStringBuffers:r,pointBuffers:s,invertVerticesTransform:Kt([1,0,0,1,0,0],e)}}generateRenderInstructions_(t,e){return{polygonInstructions:this.hasFill_?Rp(t.polygonBatch,new Float32Array(0),this.customAttributes_,e):null,lineStringInstructions:this.hasStroke_?Cp(t.lineStringBatch,new Float32Array(0),this.customAttributes_,e):null,pointInstructions:this.hasSymbol_?Tp(t.pointBatch,new Float32Array(0),this.customAttributes_,e):null}}generateBuffersForType_(t,e,i){if(null===t)return null;const n=Pp++;let r;switch(e){case"Polygon":r=kf;break;case"LineString":r=jf;break;case"Point":r=Gf}const s={id:n,type:r,renderInstructions:t.buffer,renderInstructionsTransform:i,customAttributesSize:Ep(this.customAttributes_)};return bp.postMessage(s,[t.buffer]),t=null,new Promise((t=>{const e=i=>{const r=i.data;if(r.id!==n)return;if(bp.removeEventListener("message",e),!this.helper_.getGL())return;const s=new kd(td,nd).fromArrayBuffer(r.vertexBuffer),o=new kd(ed,nd).fromArrayBuffer(r.indexBuffer);this.helper_.flushBufferData(s),this.helper_.flushBufferData(o),t([o,s])};bp.addEventListener("message",e)}))}render(t,e,i){this.hasFill_&&this.renderInternal_(t.polygonBuffers[0],t.polygonBuffers[1],this.fillProgram_,this.polygonAttributesDesc_,e,i),this.hasStroke_&&this.renderInternal_(t.lineStringBuffers[0],t.lineStringBuffers[1],this.strokeProgram_,this.lineStringAttributesDesc_,e,i),this.hasSymbol_&&this.renderInternal_(t.pointBuffers[0],t.pointBuffers[1],this.symbolProgram_,this.pointAttributesDesc_,e,i)}renderInternal_(t,e,i,n,r,s){this.helper_.useProgram(i,r),this.helper_.bindBuffer(e),this.helper_.bindBuffer(t),this.helper_.enableAttributes(n),s();const o=t.getSize();this.helper_.drawElements(0,o)}};const Np={...Xd,RENDER_EXTENT:"u_renderExtent",GLOBAL_ALPHA:"u_globalAlpha"};var Dp=class extends sg{constructor(t,e){super(t,{uniforms:{[Np.RENDER_EXTENT]:[0,0,0,0],[Np.GLOBAL_ALPHA]:1},postProcesses:e.postProcesses}),this.sourceRevision_=-1,this.previousExtent_=[1/0,1/0,-1/0,-1/0],this.currentTransform_=[1,0,0,1,0,0],this.tmpTransform_=[1,0,0,1,0,0],this.tmpMat4_=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],this.currentFrameStateTransform_=[1,0,0,1,0,0],this.styles_=[],this.styleRenderers_=[],this.buffers_=[],this.applyOptions_(e),this.batch_=new bf;const i=this.getLayer().getSource();this.batch_.addFeatures(i.getFeatures()),this.sourceListenKeys_=[D(i,ic,this.handleSourceFeatureAdded_,this),D(i,nc,this.handleSourceFeatureChanged_,this),D(i,sc,this.handleSourceFeatureDelete_,this),D(i,rc,this.handleSourceFeatureClear_,this)]}applyOptions_(t){this.styles_=Array.isArray(t.style)?t.style:[t.style]}createRenderers_(){this.buffers_=[],this.styleRenderers_=this.styles_.map((t=>new Op(t,this.helper)))}reset(t){this.applyOptions_(t),this.helper&&this.createRenderers_(),super.reset(t)}afterHelperCreated(){this.createRenderers_()}handleSourceFeatureAdded_(t){const e=t.feature;this.batch_.addFeature(e)}handleSourceFeatureChanged_(t){const e=t.feature;this.batch_.changeFeature(e)}handleSourceFeatureDelete_(t){const e=t.feature;this.batch_.removeFeature(e)}handleSourceFeatureClear_(){this.batch_.clear()}applyUniforms_(t){Ut(this.tmpTransform_,this.currentFrameStateTransform_),jt(this.tmpTransform_,t),this.helper.setUniformMatrixValue(Np.PROJECTION_MATRIX,zd(this.tmpMat4_,this.tmpTransform_))}renderFrame(t){const e=this.helper.getGL();this.preRender(e,t),this.helper.prepareDraw(t),this.currentFrameStateTransform_=this.helper.makeProjectionTransform(t,this.currentFrameStateTransform_);const i=this.getLayer().getSource(),n=t.viewState.projection,r=i.getWrapX()&&n.canWrapX(),s=n.getExtent(),o=t.extent,a=r?Me(s):null,l=r?Math.ceil((o[2]-s[2])/a)+1:1;let h=r?Math.floor((o[0]-s[0])/a):0;Zt(this.currentFrameStateTransform_,h*a,0);do{for(let e=0,i=this.styleRenderers_.length;e{this.applyUniforms_(n.invertVerticesTransform)}))}Zt(this.currentFrameStateTransform_,a,0)}while(++ht.generateBuffers(this.batch_,l).then((t=>{this.buffers_[e]=t}))));Promise.all(h).then((()=>{this.ready=!0,this.getLayer().changed()})),this.previousExtent_=t.extent.slice()}return!0}forEachFeatureAtCoordinate(t,e,i,n,r){}disposeInternal(){this.sourceListenKeys_.forEach((function(t){G(t)})),this.sourceListenKeys_=null,super.disposeInternal()}};var kp=class extends gg{constructor(t,e){super(t,e),this.styles_=[],this.styleRenderers_=[],this.currentFrameStateTransform_=[1,0,0,1,0,0],this.tmpTransform_=[1,0,0,1,0,0],this.tmpMat4_=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],this.applyOptions_(e)}reset(t){super.reset(t),this.applyOptions_(t),this.helper&&this.createRenderers_()}applyOptions_(t){this.styles_=Array.isArray(t.style)?t.style:[t.style]}createRenderers_(){this.styleRenderers_=this.styles_.map((t=>new Op(t,this.helper)))}afterHelperCreated(){this.createRenderers_()}createTileRepresentation(t){const e=new Pf(t,this.styleRenderers_),i=()=>{e.ready&&(this.getLayer().changed(),e.removeEventListener(E,i))};return e.addEventListener(E,i),e}beforeTilesRender(t,e){super.beforeTilesRender(t,!0),this.helper.makeProjectionTransform(t,this.currentFrameStateTransform_)}applyUniforms_(t,e,i){Ut(this.tmpTransform_,this.currentFrameStateTransform_),jt(this.tmpTransform_,i),this.helper.setUniformMatrixValue(og.PROJECTION_MATRIX,zd(this.tmpMat4_,this.tmpTransform_)),Kt(this.tmpTransform_,this.currentFrameStateTransform_),this.helper.setUniformMatrixValue(og.SCREEN_TO_WORLD_MATRIX,zd(this.tmpMat4_,this.tmpTransform_)),this.helper.setUniformFloatValue(og.GLOBAL_ALPHA,t),this.helper.setUniformFloatVec4(og.RENDER_EXTENT,e)}renderTile(t,e,i,n,r,s,o,a,l,h,c){const u=Ie(a,n,a);for(let e=0,n=this.styleRenderers_.length;e{this.applyUniforms_(c,u,r.invertVerticesTransform)}))}}renderDeclutter(t){}disposeInternal(){super.disposeInternal()}};const Gp=0,jp=1,Bp=2,Up=3,zp=4,Xp=5,Vp=6,Wp=7,Zp=8,Yp=9,Kp=10,Hp=11,qp=12,$p=[Zp],Jp=[qp],Qp=[jp],tm=[Up];var em=class extends zl{constructor(t,e,i,n){super(),this.tolerance=t,this.maxExtent=e,this.pixelRatio=n,this.maxLineWidth=0,this.resolution=i,this.beginGeometryInstruction1_=null,this.beginGeometryInstruction2_=null,this.bufferedMaxExtent_=null,this.instructions=[],this.coordinates=[],this.tmpCoordinate_=[],this.hitDetectionInstructions=[],this.state={}}applyPixelRatio(t){const e=this.pixelRatio;return 1==e?t:t.map((function(t){return t*e}))}appendFlatPointCoordinates(t,e){const i=this.getBufferedMaxExtent(),n=this.tmpCoordinate_,r=this.coordinates;let s=r.length;for(let o=0,a=t.length;oo&&(this.instructions.push([zp,o,l,t,i,Qn]),this.hitDetectionInstructions.push([zp,o,l,t,n||i,Qn]));break;case"Point":a=t.getFlatCoordinates(),this.coordinates.push(a[0],a[1]),l=this.coordinates.length,this.instructions.push([zp,o,l,t,i]),this.hitDetectionInstructions.push([zp,o,l,t,n||i])}this.endGeometry(e)}beginGeometry(t,e){this.beginGeometryInstruction1_=[Gp,e,0,t],this.instructions.push(this.beginGeometryInstruction1_),this.beginGeometryInstruction2_=[Gp,e,0,t],this.hitDetectionInstructions.push(this.beginGeometryInstruction2_)}finish(){return{instructions:this.instructions,hitDetectionInstructions:this.hitDetectionInstructions,coordinates:this.coordinates}}reverseHitDetectionInstructions(){const t=this.hitDetectionInstructions;let e;t.reverse();const i=t.length;let n,r,s=-1;for(e=0;ethis.maxLineWidth&&(this.maxLineWidth=i.lineWidth,this.bufferedMaxExtent_=null)}else i.strokeStyle=void 0,i.lineCap=void 0,i.lineDash=null,i.lineDashOffset=void 0,i.lineJoin=void 0,i.lineWidth=void 0,i.miterLimit=void 0}createFill(t){const e=t.fillStyle,i=[Kp,e];return"string"!=typeof e&&i.push(!0),i}applyStroke(t){this.instructions.push(this.createStroke(t))}createStroke(t){return[Hp,t.strokeStyle,t.lineWidth*this.pixelRatio,t.lineCap,t.lineJoin,t.miterLimit,this.applyPixelRatio(t.lineDash),t.lineDashOffset*this.pixelRatio]}updateFillStyle(t,e){const i=t.fillStyle;"string"==typeof i&&t.currentFillStyle==i||(void 0!==i&&this.instructions.push(e.call(this,t)),t.currentFillStyle=i)}updateStrokeStyle(t,e){const i=t.strokeStyle,n=t.lineCap,r=t.lineDash,s=t.lineDashOffset,o=t.lineJoin,a=t.lineWidth,l=t.miterLimit;(t.currentStrokeStyle!=i||t.currentLineCap!=n||r!=t.currentLineDash&&!g(t.currentLineDash,r)||t.currentLineDashOffset!=s||t.currentLineJoin!=o||t.currentLineWidth!=a||t.currentMiterLimit!=l)&&(void 0!==i&&e.call(this,t),t.currentStrokeStyle=i,t.currentLineCap=n,t.currentLineDash=r,t.currentLineDashOffset=s,t.currentLineJoin=o,t.currentLineWidth=a,t.currentMiterLimit=l)}endGeometry(t){this.beginGeometryInstruction1_[2]=this.instructions.length,this.beginGeometryInstruction1_=null,this.beginGeometryInstruction2_[2]=this.hitDetectionInstructions.length,this.beginGeometryInstruction2_=null;const e=[Wp,t];this.instructions.push(e),this.hitDetectionInstructions.push(e)}getBufferedMaxExtent(){if(!this.bufferedMaxExtent_&&(this.bufferedMaxExtent_=ee(this.maxExtent),this.maxLineWidth>0)){const t=this.resolution*(this.maxLineWidth+1)/2;te(this.bufferedMaxExtent_,t,this.bufferedMaxExtent_)}return this.bufferedMaxExtent_}};var im=class extends em{constructor(t,e,i,n){super(t,e,i,n),this.hitDetectionImage_=null,this.image_=null,this.imagePixelRatio_=void 0,this.anchorX_=void 0,this.anchorY_=void 0,this.height_=void 0,this.opacity_=void 0,this.originX_=void 0,this.originY_=void 0,this.rotateWithView_=void 0,this.rotation_=void 0,this.scale_=void 0,this.width_=void 0,this.declutterMode_=void 0,this.declutterImageWithText_=void 0}drawPoint(t,e){if(!this.image_)return;this.beginGeometry(t,e);const i=t.getFlatCoordinates(),n=t.getStride(),r=this.coordinates.length,s=this.appendFlatPointCoordinates(i,n);this.instructions.push([Vp,r,s,this.image_,this.anchorX_*this.imagePixelRatio_,this.anchorY_*this.imagePixelRatio_,Math.ceil(this.height_*this.imagePixelRatio_),this.opacity_,this.originX_*this.imagePixelRatio_,this.originY_*this.imagePixelRatio_,this.rotateWithView_,this.rotation_,[this.scale_[0]*this.pixelRatio/this.imagePixelRatio_,this.scale_[1]*this.pixelRatio/this.imagePixelRatio_],Math.ceil(this.width_*this.imagePixelRatio_),this.declutterMode_,this.declutterImageWithText_]),this.hitDetectionInstructions.push([Vp,r,s,this.hitDetectionImage_,this.anchorX_,this.anchorY_,this.height_,1,this.originX_,this.originY_,this.rotateWithView_,this.rotation_,this.scale_,this.width_,this.declutterMode_,this.declutterImageWithText_]),this.endGeometry(e)}drawMultiPoint(t,e){if(!this.image_)return;this.beginGeometry(t,e);const i=t.getFlatCoordinates(),n=t.getStride(),r=this.coordinates.length,s=this.appendFlatPointCoordinates(i,n);this.instructions.push([Vp,r,s,this.image_,this.anchorX_*this.imagePixelRatio_,this.anchorY_*this.imagePixelRatio_,Math.ceil(this.height_*this.imagePixelRatio_),this.opacity_,this.originX_*this.imagePixelRatio_,this.originY_*this.imagePixelRatio_,this.rotateWithView_,this.rotation_,[this.scale_[0]*this.pixelRatio/this.imagePixelRatio_,this.scale_[1]*this.pixelRatio/this.imagePixelRatio_],Math.ceil(this.width_*this.imagePixelRatio_),this.declutterMode_,this.declutterImageWithText_]),this.hitDetectionInstructions.push([Vp,r,s,this.hitDetectionImage_,this.anchorX_,this.anchorY_,this.height_,1,this.originX_,this.originY_,this.rotateWithView_,this.rotation_,this.scale_,this.width_,this.declutterMode_,this.declutterImageWithText_]),this.endGeometry(e)}finish(){return this.reverseHitDetectionInstructions(),this.anchorX_=void 0,this.anchorY_=void 0,this.hitDetectionImage_=null,this.image_=null,this.imagePixelRatio_=void 0,this.height_=void 0,this.scale_=void 0,this.opacity_=void 0,this.originX_=void 0,this.originY_=void 0,this.rotateWithView_=void 0,this.rotation_=void 0,this.width_=void 0,super.finish()}setImageStyle(t,e){const i=t.getAnchor(),n=t.getSize(),r=t.getOrigin();this.imagePixelRatio_=t.getPixelRatio(this.pixelRatio),this.anchorX_=i[0],this.anchorY_=i[1],this.hitDetectionImage_=t.getHitDetectionImage(),this.image_=t.getImage(this.pixelRatio),this.height_=n[1],this.opacity_=t.getOpacity(),this.originX_=r[0],this.originY_=r[1],this.rotateWithView_=t.getRotateWithView(),this.rotation_=t.getRotation(),this.scale_=t.getScaleArray(),this.width_=n[0],this.declutterMode_=t.getDeclutterMode(),this.declutterImageWithText_=e}};var nm=class extends em{constructor(t,e,i,n){super(t,e,i,n)}drawFlatCoordinates_(t,e,i,n){const r=this.coordinates.length,s=this.appendFlatLineCoordinates(t,e,i,n,!1,!1),o=[Yp,r,s];return this.instructions.push(o),this.hitDetectionInstructions.push(o),i}drawLineString(t,e){const i=this.state,n=i.strokeStyle,r=i.lineWidth;if(void 0===n||void 0===r)return;this.updateStrokeStyle(i,this.applyStroke),this.beginGeometry(t,e),this.hitDetectionInstructions.push([Hp,i.strokeStyle,i.lineWidth,i.lineCap,i.lineJoin,i.miterLimit,vo,0],Qp);const s=t.getFlatCoordinates(),o=t.getStride();this.drawFlatCoordinates_(s,0,s.length,o),this.hitDetectionInstructions.push(Jp),this.endGeometry(e)}drawMultiLineString(t,e){const i=this.state,n=i.strokeStyle,r=i.lineWidth;if(void 0===n||void 0===r)return;this.updateStrokeStyle(i,this.applyStroke),this.beginGeometry(t,e),this.hitDetectionInstructions.push([Hp,i.strokeStyle,i.lineWidth,i.lineCap,i.lineJoin,i.miterLimit,vo,0],Qp);const s=t.getEnds(),o=t.getFlatCoordinates(),a=t.getStride();let l=0;for(let t=0,e=s.length;t=t){const e=(t-a+u)/u,d=vi(i,h,e),g=vi(n,c,e);l.push(d,g),s.push(l),l=[d,g],a==t&&(o+=r),a=0}else if(a0&&s.push(l),s}function om(t,e,i,n,r){let s,o,a,l,h,c,u,d,g,f,p=i,m=i,_=0,y=0,x=i;for(o=i;ot&&(y>_&&(_=y,p=x,m=o),y=0,x=o-r)),a=l,u=g,d=f),h=i,c=n}return y+=l,y>_?[x,o]:[p,m]}const am={left:0,center:.5,right:1,top:0,middle:.5,hanging:.2,alphabetic:.8,ideographic:.8,bottom:1};var lm=class extends em{constructor(t,e,i,n){super(t,e,i,n),this.labels_=null,this.text_="",this.textOffsetX_=0,this.textOffsetY_=0,this.textRotateWithView_=void 0,this.textRotation_=0,this.textFillState_=null,this.fillStates={},this.fillStates[yo]={fillStyle:yo},this.textStrokeState_=null,this.strokeStates={},this.textState_={},this.textStates={},this.textKey_="",this.fillKey_="",this.strokeKey_="",this.declutterImageWithText_=void 0}finish(){const t=super.finish();return t.textStates=this.textStates,t.fillStates=this.fillStates,t.strokeStates=this.strokeStates,t}drawText(t,e){const i=this.textFillState_,n=this.textStrokeState_,r=this.textState_;if(""===this.text_||!r||!i&&!n)return;const s=this.coordinates;let o=s.length;const a=t.getType();let l=null,h=t.getStride();if("line"!==r.placement||"LineString"!=a&&"MultiLineString"!=a&&"Polygon"!=a&&"MultiPolygon"!=a){let i=r.overflow?null:[];switch(a){case"Point":case"MultiPoint":l=t.getFlatCoordinates();break;case"LineString":l=t.getFlatMidpoint();break;case"Circle":l=t.getCenter();break;case"MultiLineString":l=t.getFlatMidpoints(),h=2;break;case"Polygon":l=t.getFlatInteriorPoint(),r.overflow||i.push(l[2]/this.resolution),h=3;break;case"MultiPolygon":const e=t.getFlatInteriorPoints();l=[];for(let t=0,n=e.length;t{const n=s[2*(t+i)]===l[i*h]&&s[2*(t+i)+1]===l[i*h+1];return n||--t,n}))}this.saveTextStates_(),(r.backgroundFill||r.backgroundStroke)&&(this.setFillStrokeStyle(r.backgroundFill,r.backgroundStroke),r.backgroundFill&&this.updateFillStyle(this.state,this.createFill),r.backgroundStroke&&(this.updateStrokeStyle(this.state,this.applyStroke),this.hitDetectionInstructions.push(this.createStroke(this.state)))),this.beginGeometry(t,e);let c=r.padding;if(c!=Ro&&(r.scale[0]<0||r.scale[1]<0)){let t=r.padding[0],e=r.padding[1],i=r.padding[2],n=r.padding[3];r.scale[0]<0&&(e=-e,n=-n),r.scale[1]<0&&(t=-t,i=-i),c=[t,e,i,n]}const u=this.pixelRatio;this.instructions.push([Vp,o,n,null,NaN,NaN,NaN,1,0,0,this.textRotateWithView_,this.textRotation_,[1,1],NaN,void 0,this.declutterImageWithText_,c==Ro?Ro:c.map((function(t){return t*u})),!!r.backgroundFill,!!r.backgroundStroke,this.text_,this.textKey_,this.strokeKey_,this.fillKey_,this.textOffsetX_,this.textOffsetY_,i]);const d=1/u,g=this.state.fillStyle;r.backgroundFill&&(this.state.fillStyle=yo,this.hitDetectionInstructions.push(this.createFill(this.state))),this.hitDetectionInstructions.push([Vp,o,n,null,NaN,NaN,NaN,1,0,0,this.textRotateWithView_,this.textRotation_,[d,d],NaN,void 0,this.declutterImageWithText_,c,!!r.backgroundFill,!!r.backgroundStroke,this.text_,this.textKey_,this.strokeKey_,this.fillKey_?yo:this.fillKey_,this.textOffsetX_,this.textOffsetY_,i]),r.backgroundFill&&(this.state.fillStyle=g,this.hitDetectionInstructions.push(this.createFill(this.state))),this.endGeometry(e)}else{if(!Ae(this.getBufferedMaxExtent(),t.getExtent()))return;let i;if(l=t.getFlatCoordinates(),"LineString"==a)i=[l.length];else if("MultiLineString"==a)i=t.getEnds();else if("Polygon"==a)i=t.getEnds().slice(0,1);else if("MultiPolygon"==a){const e=t.getEndss();i=[];for(let t=0,n=e.length;tt[2]}else b=v>C;const P=Math.PI,I=[],F=w+n===e;let L;if(m=0,_=E,d=t[e=w],g=t[e+1],F){y(),L=Math.atan2(g-p,d-f),b&&(L+=L>0?-P:P);const t=(C+v)/2,e=(R+S)/2;return I[0]=[t,e,(T-s)/2,L,r],I}for(let t=0,u=(r=r.replace(/\n/g," ")).length;t0?-P:P),void 0!==L){let t=v-L;if(t+=t>P?-2*P:t<-P?2*P:0,Math.abs(t)>o)return null}L=v;const S=t;let w=0;for(;t0&&t.push("\n",""),t.push(e,""),t}var wm=class{constructor(t,e,i,n){this.overlaps=i,this.pixelRatio=e,this.resolution=t,this.alignFill_,this.instructions=n.instructions,this.coordinates=n.coordinates,this.coordinateCache_={},this.renderedTransform_=[1,0,0,1,0,0],this.hitDetectionInstructions=n.hitDetectionInstructions,this.pixelCoordinates_=null,this.viewRotation_=0,this.fillStates=n.fillStates||{},this.strokeStates=n.strokeStates||{},this.textStates=n.textStates||{},this.widths_={},this.labels_={}}createLabel(t,e,i,n){const r=t+e+i+n;if(this.labels_[r])return this.labels_[r];const s=n?this.strokeStates[n]:null,o=i?this.fillStates[i]:null,a=this.textStates[e],l=this.pixelRatio,h=[a.scale[0]*l,a.scale[1]*l],c=Array.isArray(t),u=a.justify?am[a.justify]:vm(Array.isArray(t)?t[0]:t,a.textAlign||To),d=n&&s.lineWidth?s.lineWidth:0,g=c?t:t.split("\n").reduce(Sm,[]),{width:f,height:p,widths:m,heights:_,lineWidths:y}=Do(a,g),x=f+d,v=[],S=(x+2)*h[0],w=(p+d)*h[1],E={width:S<0?Math.floor(S):Math.ceil(S),height:w<0?Math.floor(w):Math.ceil(w),contextInstructions:v};1==h[0]&&1==h[1]||v.push("scale",h),n&&(v.push("strokeStyle",s.strokeStyle),v.push("lineWidth",d),v.push("lineCap",s.lineCap),v.push("lineJoin",s.lineJoin),v.push("miterLimit",s.miterLimit),v.push("setLineDash",[s.lineDash]),v.push("lineDashOffset",s.lineDashOffset)),i&&v.push("fillStyle",o.fillStyle),v.push("textBaseline","middle"),v.push("textAlign","center");const T=.5-u;let C=u*x+T*d;const R=[],b=[];let P,I=0,F=0,L=0,M=0;for(let t=0,e=g.length;tt?t-l:r,x=s+h>e?e-h:s,v=g[3]+y*u[0]+g[1],S=g[0]+x*u[1]+g[2],w=m-g[3],E=_-g[0];let T;return(f||0!==c)&&(fm[0]=w,_m[0]=w,fm[1]=E,pm[1]=E,pm[0]=w+v,mm[0]=pm[0],mm[1]=E+S,_m[1]=mm[1]),0!==c?(T=Yt([1,0,0,1,0,0],i,n,1,1,c,-i,-n),zt(T,fm),zt(T,pm),zt(T,mm),zt(T,_m),le(Math.min(fm[0],pm[0],mm[0],_m[0]),Math.min(fm[1],pm[1],mm[1],_m[1]),Math.max(fm[0],pm[0],mm[0],_m[0]),Math.max(fm[1],pm[1],mm[1],_m[1]),gm)):le(Math.min(w,w+v),Math.min(E,E+S),Math.max(w,w+v),Math.max(E,E+S),gm),d&&(m=Math.round(m),_=Math.round(_)),{drawImageX:m,drawImageY:_,drawImageW:y,drawImageH:x,originX:l,originY:h,declutterBox:{minX:gm[0],minY:gm[1],maxX:gm[2],maxY:gm[3],value:p},canvasTransform:T,scale:u}}replayImageOrLabel_(t,e,i,n,r,s,o){const a=!(!s&&!o),l=n.declutterBox,h=t.canvas,c=o?o[2]*n.scale[0]/2:0;return l.minX-c<=h.width/e&&l.maxX+c>=0&&l.minY-c<=h.height/e&&l.maxY+c>=0&&(a&&this.replayTextBackground_(t,fm,pm,mm,_m,s,o),ko(t,n.canvasTransform,r,i,n.originX,n.originY,n.drawImageW,n.drawImageH,n.drawImageX,n.drawImageY,n.scale)),!0}fill_(t){if(this.alignFill_){const e=zt(this.renderedTransform_,[0,0]),i=512*this.pixelRatio;t.save(),t.translate(e[0]%i,e[1]%i),t.rotate(this.viewRotation_)}t.fill(),this.alignFill_&&t.restore()}setStrokeStyle_(t,e){t.strokeStyle=e[1],t.lineWidth=e[2],t.lineCap=e[3],t.lineJoin=e[4],t.miterLimit=e[5],t.lineDashOffset=e[7],t.setLineDash(e[6])}drawLabelWithPointPlacement_(t,e,i,n){const r=this.textStates[e],s=this.createLabel(t,e,n,i),o=this.strokeStates[i],a=this.pixelRatio,l=vm(Array.isArray(t)?t[0]:t,r.textAlign||To),h=am[r.textBaseline||Co],c=o&&o.lineWidth?o.lineWidth:0;return{label:s,anchorX:l*(s.width/a-2*r.scale[0])+2*(.5-l)*c,anchorY:h*s.height/a+2*(.5-h)*c}}execute_(t,e,i,n,r,s,o,a){let l;this.pixelCoordinates_&&g(i,this.renderedTransform_)?l=this.pixelCoordinates_:(this.pixelCoordinates_||(this.pixelCoordinates_=[]),l=Rn(this.coordinates,0,this.coordinates.length,2,i,this.pixelCoordinates_),Ut(this.renderedTransform_,i));let h=0;const c=n.length;let u,d,f,p,m,_,y,x,v,S,w,E,T=0,C=0,R=0,b=null,P=null;const I=this.coordinateCache_,F=this.viewRotation_,L=Math.round(1e12*Math.atan2(-i[1],i[0]))/1e12,M={context:t,pixelRatio:this.pixelRatio,resolution:this.resolution,rotation:F},A=this.instructions!=n||this.overlaps?0:200;let O,N,D,k;for(;hA&&(this.fill_(t),C=0),R>A&&(t.stroke(),R=0),C||R||(t.beginPath(),p=NaN,m=NaN),++h;break;case Bp:T=i[1];const n=l[T],c=l[T+1],g=l[T+2]-n,G=l[T+3]-c,j=Math.sqrt(g*g+G*G);t.moveTo(n+j,c),t.arc(n,c,j,0,2*Math.PI,!0),++h;break;case Up:t.closePath(),++h;break;case zp:T=i[1],u=i[2];const B=i[3],U=i[4],z=6==i.length?i[5]:void 0;M.geometry=B,M.feature=O,h in I||(I[h]=[]);const X=I[h];z?z(l,T,u,2,X):(X[0]=l[T],X[1]=l[T+1],X.length=2),U(X,M),++h;break;case Vp:T=i[1],u=i[2],x=i[3],d=i[4],f=i[5];let V=i[6];const W=i[7],Z=i[8],Y=i[9],K=i[10];let H=i[11];const q=i[12];let $=i[13];const J=i[14],Q=i[15];if(!x&&i.length>=20){v=i[19],S=i[20],w=i[21],E=i[22];const t=this.drawLabelWithPointPlacement_(v,S,w,E);x=t.label,i[3]=x;const e=i[23];d=(t.anchorX-e)*this.pixelRatio,i[4]=d;const n=i[24];f=(t.anchorY-n)*this.pixelRatio,i[5]=f,V=x.height,i[6]=V,$=x.width,i[13]=$}let tt,et,it,nt;i.length>25&&(tt=i[25]),i.length>17?(et=i[16],it=i[17],nt=i[18]):(et=Ro,it=!1,nt=!1),K&&L?H+=F:K||L||(H-=F);let rt=0;for(;Ti)break;let a=n[o];a||(a=[],n[o]=a),a.push(4*((t+r)*e+(t+s))+3),r>0&&a.push(4*((t-r)*e+(t+s))+3),s>0&&(a.push(4*((t+r)*e+(t-s))+3),r>0&&a.push(4*((t-r)*e+(t-s))+3))}const r=[];for(let t=0,e=n.length;t0){if(!s||"Image"!==g&&"Text"!==g||s.includes(t)){const i=(d[a]-3)/4,s=n-i%o,l=n-(i/o|0),h=r(t,e,s*s+l*l);if(h)return h}c.clearRect(0,0,o,o);break}}const p=Object.keys(this.executorsByZIndex_).map(Number);let m,_,y,x,v;for(p.sort(l),m=p.length-1;m>=0;--m){const t=p[m].toString();for(y=this.executorsByZIndex_[t],_=Em.length-1;_>=0;--_)if(g=Em[_],x=y[g],void 0!==x&&(v=x.executeHitDetection(c,a,i,f,u),v))return v}}getClipCoords(t){const e=this.maxExtent_;if(!e)return null;const i=e[0],n=e[1],r=e[2],s=e[3],o=[i,n,i,s,r,s,r,n];return Rn(o,0,8,2,t,o),o}isEmpty(){return S(this.executorsByZIndex_)}execute(t,e,i,n,r,s,o){const a=Object.keys(this.executorsByZIndex_).map(Number);let h,c,u,d,g,f;for(a.sort(l),this.maxExtent_&&(t.save(),this.clip(t,i)),s=s||Em,o&&a.reverse(),h=0,c=a.length;h{if(!this.hitDetectionImageData_&&!this.animatingOrInteracting_){const t=[this.context.canvas.width,this.context.canvas.height];zt(this.pixelTransform,t);const e=this.renderedCenter_,i=this.renderedResolution_,n=this.renderedRotation_,r=this.renderedProjection_,s=this.wrappedRenderedExtent_,o=this.getLayer(),a=[],l=t[0]*bm,h=t[1]*bm;a.push(this.getRenderTransform(e,i,n,bm,l,h,0).slice());const c=o.getSource(),u=r.getExtent();if(c.getWrapX()&&r.canWrapX()&&!re(u,s)){let t=s[0];const r=Me(u);let o,c=0;for(;tu[2];)++c,o=r*c,a.push(this.getRenderTransform(e,i,n,bm,l,h,o).slice()),t-=r}this.hitDetectionImageData_=Pm(t,a,this.renderedFeatures_,o.getStyleFunction(),s,i,n)}e(Im(t,this.renderedFeatures_,this.hitDetectionImageData_))}))}forEachFeatureAtCoordinate(t,e,i,n,r){if(!this.replayGroup_)return;const s=e.viewState.resolution,o=e.viewState.rotation,a=this.getLayer(),l={},h=function(t,e,i){const s=V(t),o=l[s];if(o){if(!0!==o&&ic=n.forEachFeatureAtCoordinate(t,s,o,i,h,n===this.declutterExecutorGroup&&e.declutterTree?e.declutterTree.all().map((t=>t.value)):null))),c}handleFontsChanged(){const t=this.getLayer();t.getVisible()&&this.replayGroup_&&t.changed()}handleStyleImageChange_(t){this.renderIfReadyAndVisible()}prepareFrame(t){const e=this.getLayer(),i=e.getSource();if(!i)return!1;const n=t.viewHints[As],r=t.viewHints[Os],s=e.getUpdateWhileAnimating(),o=e.getUpdateWhileInteracting();if(this.ready&&!s&&n||!o&&r)return this.animatingOrInteracting_=!0,!0;this.animatingOrInteracting_=!1;const a=t.extent,l=t.viewState,h=l.projection,c=l.resolution,u=t.pixelRatio,d=e.getRevision(),f=e.getRenderBuffer();let p=e.getRenderOrder();void 0===p&&(p=Zl);const m=l.center.slice(),_=te(a,f*c),y=_.slice(),x=[_.slice()],v=h.getExtent();if(i.getWrapX()&&h.canWrapX()&&!re(v,t.extent)){const t=Me(v),e=Math.max(Me(_)/2,t);_[0]=v[0]-e,_[2]=v[2]+e,ji(m,h);const i=je(x[0],h);i[0]v[0]&&i[2]>v[2]&&x.push([i[0]-t,i[1],i[2]-t,i[3]])}if(this.ready&&this.renderedResolution_==c&&this.renderedRevision_==d&&this.renderedRenderOrder_==p&&re(this.wrappedRenderedExtent_,_))return g(this.renderedExtent_,y)||(this.hitDetectionImageData_=null,this.renderedExtent_=y),this.renderedCenter_=m,this.replayGroupChanged=!1,!0;this.replayGroup_=null;const S=new cm(Kl(c,u),_,c,u);let w;this.getLayer().getDeclutter()&&(w=new cm(Kl(c,u),_,c,u));const E=_n();let T;if(E){for(let t=0,e=x.length;t{let i;const n=t.getStyleFunction()||e.getStyleFunction();if(n&&(i=n(t,c)),i){const e=this.renderFeature(t,C,i,S,T,w);R=R&&!e}},P=vn(_,h),I=i.getFeaturesInExtent(P);p&&I.sort(p);for(let t=0,e=I.length;t{if(g.getState()!==qr)return;this.image_=d?null:g;const t=g.getResolution(),n=g.getPixelRatio(),r=t*e/n;this.renderedResolution=r,this.coordinateToVectorPixelTransform_=Yt(this.coordinateToVectorPixelTransform_,a/2,l/2,1/r,-1/r,0,-i.center[0],-i.center[1])})),g.load()}return this.image_&&(this.renderedPixelToCoordinateTransform_=t.pixelToCoordinateTransform.slice()),!!this.image_}preRender(){}postRender(){}renderDeclutter(){}forEachFeatureAtCoordinate(t,e,i,n,r){return this.vectorRenderer_?this.vectorRenderer_.forEachFeatureAtCoordinate(t,e,i,n,r):super.forEachFeatureAtCoordinate(t,e,i,n,r)}};const Mm={image:["Polygon","Circle","LineString","Image","Text"],hybrid:["Polygon","LineString"],vector:[]},Am={hybrid:["Image","Text","Default"],vector:["Polygon","Circle","LineString","Image","Text","Default"]};var Om=class extends Tu{constructor(t){super(t),this.boundHandleStyleImageChange_=this.handleStyleImageChange_.bind(this),this.renderedLayerRevision_,this.renderedPixelToCoordinateTransform_=null,this.renderedRotation_,this.tmpTransform_=[1,0,0,1,0,0]}prepareTile(t,e,i){let n;const r=t.getState();return r!==tt&&r!==et||(this.updateExecutorGroup_(t,e,i),this.tileImageNeedsRender_(t)&&(n=!0)),n}getTile(t,e,i,n){const r=n.pixelRatio,s=n.viewState,o=s.resolution,a=s.projection,l=this.getLayer(),h=l.getSource().getTile(t,e,i,r,a),c=n.viewHints,u=!(c[As]||c[Os]);!u&&h.wantedResolution||(h.wantedResolution=o);return this.prepareTile(h,r,a)&&(u||Date.now()-n.time<8)&&"vector"!==l.getRenderMode()&&this.renderTileImage_(h,n),super.getTile(t,e,i,n)}isDrawableTile(t){const e=this.getLayer();return super.isDrawableTile(t)&&("vector"===e.getRenderMode()?V(e)in t.executorGroups:t.hasContext(e))}getTileImage(t){return t.getImage(this.getLayer())}prepareFrame(t){const e=this.getLayer().getRevision();return this.renderedLayerRevision_!==e&&(this.renderedLayerRevision_=e,this.renderedTiles.length=0),super.prepareFrame(t)}updateExecutorGroup_(t,e,i){const n=this.getLayer(),r=n.getRevision(),s=n.getRenderOrder()||null,o=t.wantedResolution,a=t.getReplayState(n);if(!a.dirty&&a.renderedResolution===o&&a.renderedRevision==r&&a.renderedRenderOrder==s)return;const l=n.getSource(),h=n.getDeclutter(),c=l.getTileGrid(),u=l.getTileGridForProjection(i).getTileCoordExtent(t.wrappedTileCoord),d=l.getSourceTiles(e,i,t),g=V(n);delete t.hitDetectionImageData[g],t.executorGroups[g]=[],h&&(t.declutterExecutorGroups[g]=[]),a.dirty=!1;for(let i=0,r=d.length;i{const r=n===p?e.declutterTree.all().map((t=>t.value)):null;for(let e=0,a=n.length;e{const n=this.getLayer(),r=V(n),s=n.getSource(),o=this.renderedProjection,a=o.getExtent(),l=this.renderedResolution,h=s.getTileGridForProjection(o),c=zt(this.renderedPixelToCoordinateTransform_,t.slice()),u=h.getTileCoordForCoordAndResolution(c,l);let d;for(let t=0,e=this.renderedTiles.length;t0)return void e([]);const g=Fe(h.getTileCoordExtent(d.wrappedTileCoord)),f=[(c[0]-g[0])/l,(g[1]-c[1])/l],p=d.getSourceTiles().reduce((function(t,e){return t.concat(e.getFeatures())}),[]);let m=d.hitDetectionImageData[r];if(!m){const t=ol(h.getTileSize(h.getZForResolution(l,s.zDirection))),e=this.renderedRotation_;m=Pm(t,[this.getRenderTransform(h.getTileCoordCenter(d.wrappedTileCoord),l,0,bm,t[0]*bm,t[1]*bm,0)],p,n.getStyleFunction(),h.getTileCoordExtent(d.wrappedTileCoord),d.getReplayState(n).renderedResolution,e),d.hitDetectionImageData[r]=m}e(Im(f,p,m))}))}handleFontsChanged(){const t=this.getLayer();t.getVisible()&&void 0!==this.renderedLayerRevision_&&t.changed()}handleStyleImageChange_(t){this.renderIfReadyAndVisible()}renderDeclutter(t){const e=this.context,i=e.globalAlpha;e.globalAlpha=this.getLayer().getOpacity();const n=t.viewHints,r=!(n[As]||n[Os]),s=this.renderedTiles;for(let e=0,i=s.length;e=0;--e)n[e].execute(this.context,1,this.getTileRenderTransform(i,t),t.viewState.rotation,r,void 0,t.declutterTree)}e.globalAlpha=i}getTileRenderTransform(t,e){const i=e.pixelRatio,n=e.viewState,r=n.center,s=n.resolution,o=n.rotation,a=e.size,l=Math.round(a[0]*i),h=Math.round(a[1]*i),c=this.getLayer().getSource().getTileGridForProjection(e.viewState.projection),u=t.tileCoord,d=c.getTileCoordExtent(t.wrappedTileCoord),g=c.getTileCoordExtent(u,this.tmpExtent)[0]-d[0];return jt(Vt(this.inversePixelTransform.slice(),1/i,1/i),this.getRenderTransform(r,s,o,i,l,h,g))}postRender(t,e){const i=e.viewHints,n=!(i[As]||i[Os]);this.renderedPixelToCoordinateTransform_=e.pixelToCoordinateTransform.slice(),this.renderedRotation_=e.viewState.rotation;const r=this.getLayer(),s=r.getRenderMode(),o=t.globalAlpha;t.globalAlpha=r.getOpacity();const a=Am[s],l=e.viewState,h=l.rotation,c=r.getSource(),u=c.getTileGridForProjection(l.projection).getZForResolution(l.resolution,c.zDirection),d=this.renderedTiles,g=[],f=[];let p=!0;for(let i=d.length-1;i>=0;--i){const s=d[i];p=p&&!s.getReplayState(r).dirty;const o=s.executorGroups[V(r)].filter((t=>t.hasExecutors(a)));if(0===o.length)continue;const l=this.getTileRenderTransform(s,e),c=s.tileCoord[0];let m=!1;const _=o[0].getClipCoords(l);if(_){for(let e=0,i=g.length;e=e[0]||(t[1]<=e[1]&&t[3]>=e[1]||ve(t,this.intersectsCoordinate.bind(this)))}return!1}setCenter(t){const e=this.stride,i=this.flatCoordinates[e]-this.flatCoordinates[0],n=t.slice();n[e]=n[0]+i;for(let i=1;i1?o:2,s=s||new Array(o);for(let e=0;e>1;r1?new $m(i,"XY",r):new Ir(i,"XY",n);default:throw new Error("Invalid geometry type:"+e)}}Qm.prototype.getEndss=Qm.prototype.getEnds,Qm.prototype.getFlatCoordinates=Qm.prototype.getOrientedFlatCoordinates;var e_=Qm;let i_=null;function n_(t){i_=t;const e=Object.keys(t.defs),i=e.length;let n,r;for(n=0;n0&&c.length>0;)f=c.pop(),r=l.pop(),o=h.pop(),_=f.toString(),_ in u||(n.push(o[0],o[1]),u[_]=!0),p=c.pop(),s=l.pop(),a=h.pop(),m=(f+p)/2,d=t(m),g=e(d),fi(g[0],g[1],o[0],o[1],a[0],a[1]){const e=t.get("graticule_label");return this.lonLabelStyleBase_.getText().setText(e),this.lonLabelStyleBase_},this.latLabelStyleBase_=new pf({text:void 0!==t.latLabelStyle?t.latLabelStyle.clone():new _f({font:"12px Calibri,sans-serif",textAlign:"right",fill:new Jg({color:"rgba(0,0,0,1)"}),stroke:new lf({color:"rgba(255,255,255,1)",width:3})})}),this.latLabelStyle_=t=>{const e=t.get("graticule_label");return this.latLabelStyleBase_.getText().setText(e),this.latLabelStyleBase_},this.meridiansLabels_=[],this.parallelsLabels_=[],this.addEventListener(Is,this.drawLabels_.bind(this))),this.intervals_=void 0!==t.intervals?t.intervals:c_,this.setSource(new cc({loader:this.loaderFunction.bind(this),strategy:this.strategyFunction.bind(this),features:new $,overlaps:!1,useSpatialIndex:!1,wrapX:t.wrapX})),this.featurePool_=[],this.lineStyle_=new pf({stroke:this.strokeStyle_}),this.loadedExtent_=null,this.renderedExtent_=null,this.renderedResolution_=null,this.setRenderOrder(null)}strategyFunction(t,e){let i=t.slice();return this.projection_&&this.getSource().getWrapX()&&je(i,this.projection_),this.loadedExtent_&&(ge(this.loadedExtent_,i,e)?i=this.loadedExtent_.slice():this.getSource().removeLoadedExtent(this.loadedExtent_)),[i]}loaderFunction(t,e,i){this.loadedExtent_=t;const n=this.getSource(),r=Ie(this.getExtent()||[-1/0,-1/0,1/0,1/0],t);if(this.renderedExtent_&&de(this.renderedExtent_,r)&&this.renderedResolution_===e)return;if(this.renderedExtent_=r,this.renderedResolution_=e,Oe(r))return;const s=Te(r),o=e*e/4;(!this.projection_||!cn(this.projection_,i))&&this.updateProjectionInfo_(i),this.createGraticule_(r,s,e,o);let a,l=this.meridians_.length+this.parallels_.length;for(this.meridiansLabels_&&(l+=this.meridians_.length),this.parallelsLabels_&&(l+=this.parallels_.length);l>this.featurePool_.length;)a=new Nt,this.featurePool_.push(a);const h=n.getFeaturesCollection();h.clear();let c,u,d=0;for(c=0,u=this.meridians_.length;cMath.PI/2}const d=$l(t);for(let t=a;t<=l;++t){let i,n,c,g,f=this.meridians_.length+this.parallels_.length;if(this.meridiansLabels_)for(n=0,c=this.meridiansLabels_.length;n=a?(t[0]=o[0],t[2]=o[2]):s=!0);const l=[gi(e[0],this.minX_,this.maxX_),gi(e[1],this.minY_,this.maxY_)],h=this.toLonLatTransform_(l);isNaN(h[1])&&(h[1]=Math.abs(this.maxLat_)>=Math.abs(this.minLat_)?this.maxLat_:this.minLat_);let c=gi(h[0],this.minLon_,this.maxLon_),u=gi(h[1],this.minLat_,this.maxLat_);const d=this.maxLines_;let g,f,p,m,_=t;s||(_=[gi(t[0],this.minX_,this.maxX_),gi(t[1],this.minY_,this.maxY_),gi(t[2],this.minX_,this.maxX_),gi(t[3],this.minY_,this.maxY_)]);const y=Ge(_,this.toLonLatTransform_,void 0,8);let x=y[3],v=y[2],S=y[1],w=y[0];if(s||(ne(_,this.bottomLeft_)&&(w=this.minLon_,S=this.minLat_),ne(_,this.bottomRight_)&&(v=this.maxLon_,S=this.minLat_),ne(_,this.topLeft_)&&(w=this.minLon_,x=this.maxLat_),ne(_,this.topRight_)&&(v=this.maxLon_,x=this.maxLat_),x=gi(x,u,this.maxLat_),v=gi(v,c,this.maxLon_),S=gi(S,this.minLat_,u),w=gi(w,this.minLon_,c)),c=Math.floor(c/r)*r,m=gi(c,this.minLon_,this.maxLon_),f=this.addMeridian_(m,S,x,n,t,0),g=0,s)for(;(m-=r)>=w&&g++n[s]&&(r=s,s=1);const o=Math.max(e[1],n[r]),a=Math.min(e[3],n[s]),l=gi(e[1]+Math.abs(e[1]-e[3])*this.lonLabelPosition_,o,a),h=[n[r-1]+(n[s-1]-n[r-1])*(l-n[r])/(n[s]-n[r]),l],c=this.meridiansLabels_[i].geom;return c.setCoordinates(h),c}getMeridians(){return this.meridians_}getParallel_(t,e,i,n,r){const s=l_(t,e,i,this.projection_,n);let o=this.parallels_[r];return o?(o.setFlatCoordinates("XY",s),o.changed()):o=new Vm(s,"XY"),o}getParallelPoint_(t,e,i){const n=t.getFlatCoordinates();let r=0,s=n.length-2;n[r]>n[s]&&(r=s,s=0);const o=Math.max(e[0],n[r]),a=Math.min(e[2],n[s]),l=gi(e[0]+Math.abs(e[0]-e[2])*this.latLabelPosition_,o,a),h=[l,n[r+1]+(n[s+1]-n[r+1])*(l-n[r])/(n[s]-n[r])],c=this.parallelsLabels_[i].geom;return c.setCoordinates(h),c}getParallels(){return this.parallels_}updateProjectionInfo_(t){const e=nn("EPSG:4326"),i=t.getWorldExtent();this.maxLat_=i[3],this.maxLon_=i[2],this.minLat_=i[1],this.minLon_=i[0];const n=dn(t,e);if(this.minLon_=Math.abs(this.minLat_)?this.maxLat_:this.minLat_),this.projection_=t}};const d_="blur",g_="gradient",f_="radius",p_=["#00f","#0ff","#0f0","#ff0","#f00"];var m_=class extends Df{constructor(t){t=t||{};const e=Object.assign({},t);delete e.gradient,delete e.radius,delete e.blur,delete e.weight,super(e),this.gradient_=null,this.addChangeListener(g_,this.handleGradientChanged_),this.setGradient(t.gradient?t.gradient:p_),this.setBlur(void 0!==t.blur?t.blur:15),this.setRadius(void 0!==t.radius?t.radius:8);const i=t.weight?t.weight:"weight";this.weightFunction_="string"==typeof i?function(t){return t.get(i)}:i,this.setRenderOrder(null)}getBlur(){return this.get(d_)}getGradient(){return this.get(g_)}getRadius(){return this.get(f_)}handleGradientChanged_(){this.gradient_=function(t){const e=1,i=256,n=yt(e,i),r=n.createLinearGradient(0,0,e,i),s=1/(t.length-1);for(let e=0,i=t.length;e{const e=this.weightFunction_(t);return void 0!==e?gi(e,0,1):1}}],hitDetectionEnabled:!0,vertexShader:"\n precision mediump float;\n uniform mat4 u_projectionMatrix;\n uniform mat4 u_offsetScaleMatrix;\n uniform float u_size;\n attribute vec2 a_position;\n attribute float a_index;\n attribute float a_weight;\n attribute vec4 a_hitColor;\n\n varying vec2 v_texCoord;\n varying float v_weight;\n varying vec4 v_hitColor;\n\n void main(void) {\n mat4 offsetMatrix = u_offsetScaleMatrix;\n float offsetX = a_index == 0.0 || a_index == 3.0 ? -u_size / 2.0 : u_size / 2.0;\n float offsetY = a_index == 0.0 || a_index == 1.0 ? -u_size / 2.0 : u_size / 2.0;\n vec4 offsets = offsetMatrix * vec4(offsetX, offsetY, 0.0, 0.0);\n gl_Position = u_projectionMatrix * vec4(a_position, 0.0, 1.0) + offsets;\n float u = a_index == 0.0 || a_index == 3.0 ? 0.0 : 1.0;\n float v = a_index == 0.0 || a_index == 1.0 ? 0.0 : 1.0;\n v_texCoord = vec2(u, v);\n v_hitColor = a_hitColor;\n v_weight = a_weight;\n }",fragmentShader:"\n precision mediump float;\n uniform float u_blurSlope;\n uniform mediump int u_hitDetection;\n\n varying vec2 v_texCoord;\n varying float v_weight;\n varying vec4 v_hitColor;\n\n void main(void) {\n vec2 texCoord = v_texCoord * 2.0 - vec2(1.0, 1.0);\n float sqRadius = texCoord.x * texCoord.x + texCoord.y * texCoord.y;\n float value = (1.0 - sqrt(sqRadius)) * u_blurSlope;\n float alpha = smoothstep(0.0, 1.0, value) * v_weight;\n gl_FragColor = vec4(alpha, alpha, alpha, alpha);\n if (u_hitDetection > 0) {\n if (alpha < 0.05) {\n discard;\n }\n gl_FragColor = v_hitColor;\n }\n }",uniforms:{u_size:()=>2*(this.get(f_)+this.get(d_)),u_blurSlope:()=>this.get(f_)/Math.max(1,this.get(d_))},postProcesses:[{fragmentShader:"\n precision mediump float;\n\n uniform sampler2D u_image;\n uniform sampler2D u_gradientTexture;\n uniform float u_opacity;\n\n varying vec2 v_texCoord;\n\n void main() {\n vec4 color = texture2D(u_image, v_texCoord);\n gl_FragColor.a = color.a * u_opacity;\n gl_FragColor.rgb = texture2D(u_gradientTexture, vec2(0.5, color.a)).rgb;\n gl_FragColor.rgb *= gl_FragColor.a;\n }",uniforms:{u_gradientTexture:()=>this.gradient_,u_opacity:()=>this.getOpacity()}}]})}renderDeclutter(){}};var __=class{constructor(){this.dataProjection=void 0,this.defaultFeatureProjection=void 0,this.supportedMediaTypes=null}getReadOptions(t,e){if(e){let i=e.dataProjection?nn(e.dataProjection):this.readProjection(t);e.extent&&i&&"tile-pixels"===i.getUnits()&&(i=nn(i),i.setWorldExtent(e.extent)),e={dataProjection:i,featureProjection:e.featureProjection}}return this.adaptOptions(e)}adaptOptions(t){return Object.assign({dataProjection:this.dataProjection,featureProjection:this.defaultFeatureProjection},t)}getType(){return z()}readFeature(t,e){return z()}readFeatures(t,e){return z()}readGeometry(t,e){return z()}readProjection(t){return z()}writeFeature(t,e){return z()}writeFeatures(t,e){return z()}writeGeometry(t,e){return z()}};function y_(t,e,i){const n=i?nn(i.featureProjection):null,r=i?nn(i.dataProjection):null;let s;if(s=n&&r&&!cn(n,r)?(e?t.clone():t).transform(e?n:r,e?r:n):t,e&&i&&void 0!==i.decimals){const e=Math.pow(10,i.decimals),n=function(t){for(let i=0,n=t.length;i */ +read:function(t,e,i,n,r){var s,o,a=8*r-n-1,l=(1<>1,c=-7,u=i?r-1:0,d=i?-1:1,g=t[e+u];for(u+=d,s=g&(1<<-c)-1,g>>=-c,c+=a;c>0;s=256*s+t[e+u],u+=d,c-=8);for(o=s&(1<<-c)-1,s>>=-c,c+=n;c>0;o=256*o+t[e+u],u+=d,c-=8);if(0===s)s=1-h;else{if(s===l)return o?NaN:1/0*(g?-1:1);o+=Math.pow(2,n),s-=h}return(g?-1:1)*o*Math.pow(2,s-n)},write:function(t,e,i,n,r,s){var o,a,l,h=8*s-r-1,c=(1<>1,d=23===r?Math.pow(2,-24)-Math.pow(2,-77):0,g=n?0:s-1,f=n?1:-1,p=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=c):(o=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-o))<1&&(o--,l*=2),(e+=o+u>=1?d/l:d*Math.pow(2,1-u))*l>=2&&(o++,l/=2),o+u>=c?(a=0,o=c):o+u>=1?(a=(e*l-1)*Math.pow(2,r),o+=u):(a=e*Math.pow(2,u-1)*Math.pow(2,r),o=0));r>=8;t[i+g]=255&a,g+=f,a/=256,r-=8);for(o=o<0;t[i+g]=255&o,g+=f,o/=256,h-=8);t[i+g-f]|=128*p}},S_=E_,w_=v_;function E_(t){this.buf=ArrayBuffer.isView&&ArrayBuffer.isView(t)?t:new Uint8Array(t||0),this.pos=0,this.type=0,this.length=this.buf.length}E_.Varint=0,E_.Fixed64=1,E_.Bytes=2,E_.Fixed32=5;var T_=4294967296,C_=1/T_,R_="undefined"==typeof TextDecoder?null:new TextDecoder("utf8");function b_(t){return t.type===E_.Bytes?t.readVarint()+t.pos:t.pos+1}function P_(t,e,i){return i?4294967296*e+(t>>>0):4294967296*(e>>>0)+(t>>>0)}function I_(t,e,i){var n=e<=16383?1:e<=2097151?2:e<=268435455?3:Math.floor(Math.log(e)/(7*Math.LN2));i.realloc(n);for(var r=i.pos-1;r>=t;r--)i.buf[r+n]=i.buf[r]}function F_(t,e){for(var i=0;i>>8,t[i+2]=e>>>16,t[i+3]=e>>>24}function U_(t,e){return(t[e]|t[e+1]<<8|t[e+2]<<16)+(t[e+3]<<24)}E_.prototype={destroy:function(){this.buf=null},readFields:function(t,e,i){for(i=i||this.length;this.pos>3,s=this.pos;this.type=7&n,t(r,e,this),this.pos===s&&this.skip(n)}return e},readMessage:function(t,e){return this.readFields(t,e,this.readVarint()+this.pos)},readFixed32:function(){var t=j_(this.buf,this.pos);return this.pos+=4,t},readSFixed32:function(){var t=U_(this.buf,this.pos);return this.pos+=4,t},readFixed64:function(){var t=j_(this.buf,this.pos)+j_(this.buf,this.pos+4)*T_;return this.pos+=8,t},readSFixed64:function(){var t=j_(this.buf,this.pos)+U_(this.buf,this.pos+4)*T_;return this.pos+=8,t},readFloat:function(){var t=w_.read(this.buf,this.pos,!0,23,4);return this.pos+=4,t},readDouble:function(){var t=w_.read(this.buf,this.pos,!0,52,8);return this.pos+=8,t},readVarint:function(t){var e,i,n=this.buf;return e=127&(i=n[this.pos++]),i<128?e:(e|=(127&(i=n[this.pos++]))<<7,i<128?e:(e|=(127&(i=n[this.pos++]))<<14,i<128?e:(e|=(127&(i=n[this.pos++]))<<21,i<128?e:function(t,e,i){var n,r,s=i.buf;if(r=s[i.pos++],n=(112&r)>>4,r<128)return P_(t,n,e);if(r=s[i.pos++],n|=(127&r)<<3,r<128)return P_(t,n,e);if(r=s[i.pos++],n|=(127&r)<<10,r<128)return P_(t,n,e);if(r=s[i.pos++],n|=(127&r)<<17,r<128)return P_(t,n,e);if(r=s[i.pos++],n|=(127&r)<<24,r<128)return P_(t,n,e);if(r=s[i.pos++],n|=(1&r)<<31,r<128)return P_(t,n,e);throw new Error("Expected varint not more than 10 bytes")}(e|=(15&(i=n[this.pos]))<<28,t,this))))},readVarint64:function(){return this.readVarint(!0)},readSVarint:function(){var t=this.readVarint();return t%2==1?(t+1)/-2:t/2},readBoolean:function(){return Boolean(this.readVarint())},readString:function(){var t=this.readVarint()+this.pos,e=this.pos;return this.pos=t,t-e>=12&&R_?function(t,e,i){return R_.decode(t.subarray(e,i))}(this.buf,e,t):function(t,e,i){var n="",r=e;for(;r239?4:l>223?3:l>191?2:1;if(r+c>i)break;1===c?l<128&&(h=l):2===c?128==(192&(s=t[r+1]))&&(h=(31&l)<<6|63&s)<=127&&(h=null):3===c?(s=t[r+1],o=t[r+2],128==(192&s)&&128==(192&o)&&((h=(15&l)<<12|(63&s)<<6|63&o)<=2047||h>=55296&&h<=57343)&&(h=null)):4===c&&(s=t[r+1],o=t[r+2],a=t[r+3],128==(192&s)&&128==(192&o)&&128==(192&a)&&((h=(15&l)<<18|(63&s)<<12|(63&o)<<6|63&a)<=65535||h>=1114112)&&(h=null)),null===h?(h=65533,c=1):h>65535&&(h-=65536,n+=String.fromCharCode(h>>>10&1023|55296),h=56320|1023&h),n+=String.fromCharCode(h),r+=c}return n}(this.buf,e,t)},readBytes:function(){var t=this.readVarint()+this.pos,e=this.buf.subarray(this.pos,t);return this.pos=t,e},readPackedVarint:function(t,e){if(this.type!==E_.Bytes)return t.push(this.readVarint(e));var i=b_(this);for(t=t||[];this.pos127;);else if(e===E_.Bytes)this.pos=this.readVarint()+this.pos;else if(e===E_.Fixed32)this.pos+=4;else{if(e!==E_.Fixed64)throw new Error("Unimplemented type: "+e);this.pos+=8}},writeTag:function(t,e){this.writeVarint(t<<3|e)},realloc:function(t){for(var e=this.length||16;e268435455||t<0?function(t,e){var i,n;t>=0?(i=t%4294967296|0,n=t/4294967296|0):(n=~(-t/4294967296),4294967295^(i=~(-t%4294967296))?i=i+1|0:(i=0,n=n+1|0));if(t>=0x10000000000000000||t<-0x10000000000000000)throw new Error("Given varint doesn't fit into 10 bytes");e.realloc(10),function(t,e,i){i.buf[i.pos++]=127&t|128,t>>>=7,i.buf[i.pos++]=127&t|128,t>>>=7,i.buf[i.pos++]=127&t|128,t>>>=7,i.buf[i.pos++]=127&t|128,t>>>=7,i.buf[i.pos]=127&t}(i,0,e),function(t,e){var i=(7&t)<<4;if(e.buf[e.pos++]|=i|((t>>>=3)?128:0),!t)return;if(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),!t)return;if(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),!t)return;if(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),!t)return;if(e.buf[e.pos++]=127&t|((t>>>=7)?128:0),!t)return;e.buf[e.pos++]=127&t}(n,e)}(t,this):(this.realloc(4),this.buf[this.pos++]=127&t|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=127&(t>>>=7)|(t>127?128:0),t<=127||(this.buf[this.pos++]=t>>>7&127))))},writeSVarint:function(t){this.writeVarint(t<0?2*-t-1:2*t)},writeBoolean:function(t){this.writeVarint(Boolean(t))},writeString:function(t){t=String(t),this.realloc(4*t.length),this.pos++;var e=this.pos;this.pos=function(t,e,i){for(var n,r,s=0;s55295&&n<57344){if(!r){n>56319||s+1===e.length?(t[i++]=239,t[i++]=191,t[i++]=189):r=n;continue}if(n<56320){t[i++]=239,t[i++]=191,t[i++]=189,r=n;continue}n=r-55296<<10|n-56320|65536,r=null}else r&&(t[i++]=239,t[i++]=191,t[i++]=189,r=null);n<128?t[i++]=n:(n<2048?t[i++]=n>>6|192:(n<65536?t[i++]=n>>12|224:(t[i++]=n>>18|240,t[i++]=n>>12&63|128),t[i++]=n>>6&63|128),t[i++]=63&n|128)}return i}(this.buf,t,this.pos);var i=this.pos-e;i>=128&&I_(e,i,this),this.pos=e-1,this.writeVarint(i),this.pos+=i},writeFloat:function(t){this.realloc(4),w_.write(this.buf,t,this.pos,!0,23,4),this.pos+=4},writeDouble:function(t){this.realloc(8),w_.write(this.buf,t,this.pos,!0,52,8),this.pos+=8},writeBytes:function(t){var e=t.length;this.writeVarint(e),this.realloc(e);for(var i=0;i=128&&I_(i,n,this),this.pos=i-1,this.writeVarint(n),this.pos+=n},writeMessage:function(t,e,i){this.writeTag(t,E_.Bytes),this.writeRawMessage(e,i)},writePackedVarint:function(t,e){e.length&&this.writeMessage(t,F_,e)},writePackedSVarint:function(t,e){e.length&&this.writeMessage(t,L_,e)},writePackedBoolean:function(t,e){e.length&&this.writeMessage(t,O_,e)},writePackedFloat:function(t,e){e.length&&this.writeMessage(t,M_,e)},writePackedDouble:function(t,e){e.length&&this.writeMessage(t,A_,e)},writePackedFixed32:function(t,e){e.length&&this.writeMessage(t,N_,e)},writePackedSFixed32:function(t,e){e.length&&this.writeMessage(t,D_,e)},writePackedFixed64:function(t,e){e.length&&this.writeMessage(t,k_,e)},writePackedSFixed64:function(t,e){e.length&&this.writeMessage(t,G_,e)},writeBytesField:function(t,e){this.writeTag(t,E_.Bytes),this.writeBytes(e)},writeFixed32Field:function(t,e){this.writeTag(t,E_.Fixed32),this.writeFixed32(e)},writeSFixed32Field:function(t,e){this.writeTag(t,E_.Fixed32),this.writeSFixed32(e)},writeFixed64Field:function(t,e){this.writeTag(t,E_.Fixed64),this.writeFixed64(e)},writeSFixed64Field:function(t,e){this.writeTag(t,E_.Fixed64),this.writeSFixed64(e)},writeVarintField:function(t,e){this.writeTag(t,E_.Varint),this.writeVarint(e)},writeSVarintField:function(t,e){this.writeTag(t,E_.Varint),this.writeSVarint(e)},writeStringField:function(t,e){this.writeTag(t,E_.Bytes),this.writeString(e)},writeFloatField:function(t,e){this.writeTag(t,E_.Fixed32),this.writeFloat(e)},writeDoubleField:function(t,e){this.writeTag(t,E_.Fixed64),this.writeDouble(e)},writeBooleanField:function(t,e){this.writeVarintField(t,Boolean(e))}};var z_=Bf(S_);function X_(t,e,i){if(3===t){const t={keys:[],values:[],features:[]},n=i.readVarint()+i.pos;i.readFields(V_,t,n),t.length=t.features.length,t.length&&(e[t.name]=t)}}function V_(t,e,i){if(15===t)e.version=i.readVarint();else if(1===t)e.name=i.readString();else if(5===t)e.extent=i.readVarint();else if(2===t)e.features.push(i.pos);else if(3===t)e.keys.push(i.readString());else if(4===t){let n=null;const r=i.readVarint()+i.pos;for(;i.pos>3)?i.readString():2===t?i.readFloat():3===t?i.readDouble():4===t?i.readVarint64():5===t?i.readVarint():6===t?i.readSVarint():7===t?i.readBoolean():null;e.values.push(n)}}function W_(t,e,i){if(1==t)e.id=i.readVarint();else if(2==t){const t=i.readVarint()+i.pos;for(;i.pos>3}o--,1===s||2===s?(a+=t.readSVarint(),l+=t.readSVarint(),1===s&&h>c&&(n.push(h),c=h),i.push(a,l),h+=2):7===s?h>c&&(i.push(i[c],i[c+1]),h+=2):Mt(!1,59)}h>c&&(n.push(h),c=h)}createFeature_(t,e,i){const n=e.type;if(0===n)return null;let r;const s=e.properties;let o;this.idProperty_?(o=s[this.idProperty_],delete s[this.idProperty_]):o=e.id,s[this.layerName_]=e.layer.name;const a=[],l=[];this.readRawGeometry_(t,e,a,l);const h=function(t,e){let i;1===t?i=1===e?"Point":"MultiPoint":2===t?i=1===e?"LineString":"MultiLineString":3===t&&(i="Polygon");return i}(n,l.length);if(this.featureClass_===e_)r=new this.featureClass_(h,a,l,s,o),r.transform(i.dataProjection);else{let t;if("Polygon"==h){const e=br(a,l);t=e.length>1?new $m(a,"XY",e):new Ir(a,"XY",l)}else t="Point"===h?new lr(a,"XY"):"LineString"===h?new Vm(a,"XY"):"MultiPoint"===h?new Km(a,"XY"):"MultiLineString"===h?new Zm(a,"XY",l):null;r=new(0,this.featureClass_),this.geometryName_&&r.setGeometryName(this.geometryName_);const e=y_(t,!1,i);r.setGeometry(e),void 0!==o&&r.setId(o),r.setProperties(s,!0)}return r}getType(){return"arraybuffer"}readFeatures(t,e){const i=this.layers_,n=nn((e=this.adaptOptions(e)).dataProjection);n.setWorldExtent(e.extent),e.dataProjection=n;const r=new z_(t),s=r.readFields(X_,{}),o=[];for(const t in s){if(i&&!i.includes(t))continue;const a=s[t],l=a?[0,0,a.extent,a.extent]:null;n.setExtent(l);for(let t=0,i=a.length;t{i.setState("ready")})).catch((t=>{this.dispatchEvent(new H_(t));this.getSource().setState("error")})),void 0===this.getBackground()&&olms.applyBackground(this,t.styleUrl,{accessToken:this.accessToken})}};var $_=class extends Df{constructor(t){t=t||{};const e=Object.assign({},t);delete e.imageRatio,super(e),this.imageRatio_=void 0!==t.imageRatio?t.imageRatio:1}getImageRatio(){return this.imageRatio_}createRenderer(){return new Lm(this)}};var J_=class extends no{constructor(t){super(Object.assign({},t)),this.parseResult_=Af(t.style),this.styleVariables_=t.style.variables||{},this.hitDetectionDisabled_=!!t.disableHitDetection}createRenderer(){const t=Object.keys(this.parseResult_.attributes).map((t=>({name:t,...this.parseResult_.attributes[t]})));return new Sp(this,{vertexShader:this.parseResult_.builder.getSymbolVertexShader(),fragmentShader:this.parseResult_.builder.getSymbolFragmentShader(),hitDetectionEnabled:!this.hitDetectionDisabled_,uniforms:this.parseResult_.uniforms,attributes:t})}updateStyleVariables(t){Object.assign(this.styleVariables_,t),this.changed()}};function Q_(t,e){const i=`\n attribute vec2 ${pg.TEXTURE_COORD};\n uniform mat4 ${fg.TILE_TRANSFORM};\n uniform float ${fg.TEXTURE_PIXEL_WIDTH};\n uniform float ${fg.TEXTURE_PIXEL_HEIGHT};\n uniform float ${fg.TEXTURE_RESOLUTION};\n uniform float ${fg.TEXTURE_ORIGIN_X};\n uniform float ${fg.TEXTURE_ORIGIN_Y};\n uniform float ${fg.DEPTH};\n\n varying vec2 v_textureCoord;\n varying vec2 v_mapCoord;\n\n void main() {\n v_textureCoord = ${pg.TEXTURE_COORD};\n v_mapCoord = vec2(\n ${fg.TEXTURE_ORIGIN_X} + ${fg.TEXTURE_RESOLUTION} * ${fg.TEXTURE_PIXEL_WIDTH} * v_textureCoord[0],\n ${fg.TEXTURE_ORIGIN_Y} - ${fg.TEXTURE_RESOLUTION} * ${fg.TEXTURE_PIXEL_HEIGHT} * v_textureCoord[1]\n );\n gl_Position = ${fg.TILE_TRANSFORM} * vec4(${pg.TEXTURE_COORD}, ${fg.DEPTH}, 1.0);\n }\n `,n={inFragmentShader:!0,variables:[],attributes:[],stringLiteralsMap:{},functions:{},bandCount:e,style:t},r=[];if(void 0!==t.color){const e=Pg(n,t.color,yg.COLOR);r.push(`color = ${e};`)}if(void 0!==t.contrast){const e=Pg(n,t.contrast,yg.NUMBER);r.push(`color.rgb = clamp((${e} + 1.0) * color.rgb - (${e} / 2.0), vec3(0.0, 0.0, 0.0), vec3(1.0, 1.0, 1.0));`)}if(void 0!==t.exposure){const e=Pg(n,t.exposure,yg.NUMBER);r.push(`color.rgb = clamp((${e} + 1.0) * color.rgb, vec3(0.0, 0.0, 0.0), vec3(1.0, 1.0, 1.0));`)}if(void 0!==t.saturation){const e=Pg(n,t.saturation,yg.NUMBER);r.push(`\n float saturation = ${e} + 1.0;\n float sr = (1.0 - saturation) * 0.2126;\n float sg = (1.0 - saturation) * 0.7152;\n float sb = (1.0 - saturation) * 0.0722;\n mat3 saturationMatrix = mat3(\n sr + saturation, sr, sr,\n sg, sg + saturation, sg,\n sb, sb, sb + saturation\n );\n color.rgb = clamp(saturationMatrix * color.rgb, vec3(0.0, 0.0, 0.0), vec3(1.0, 1.0, 1.0));\n `)}if(void 0!==t.gamma){const e=Pg(n,t.gamma,yg.NUMBER);r.push(`color.rgb = pow(color.rgb, vec3(1.0 / ${e}));`)}if(void 0!==t.brightness){const e=Pg(n,t.brightness,yg.NUMBER);r.push(`color.rgb = clamp(color.rgb + ${e}, vec3(0.0, 0.0, 0.0), vec3(1.0, 1.0, 1.0));`)}const s={},o=n.variables.length;if(o>1&&!t.variables)throw new Error(`Missing variables in style (expected ${n.variables})`);for(let e=0;e ${fg.RENDER_EXTENT}[2] ||\n v_mapCoord[1] > ${fg.RENDER_EXTENT}[3]\n ) {\n discard;\n }\n\n vec4 color = texture2D(${fg.TILE_TEXTURE_ARRAY}[0], v_textureCoord);\n\n ${r.join("\n")}\n\n gl_FragColor = color;\n gl_FragColor.rgb *= gl_FragColor.a;\n gl_FragColor *= ${fg.TRANSITION_ALPHA};\n }`,uniforms:s,paletteTextures:n.paletteTextures}}class ty extends Eu{constructor(t){const e=(t=t?Object.assign({},t):{}).style||{};delete t.style;const i=t.cacheSize;delete t.cacheSize,super(t),this.sources_=t.sources,this.renderedSource_=null,this.renderedResolution_=NaN,this.style_=e,this.cacheSize_=i,this.styleVariables_=this.style_.variables||{},this.addChangeListener(Cs,this.handleSourceUpdate_)}getSources(t,e){const i=this.getSource();return this.sources_?"function"==typeof this.sources_?this.sources_(t,e):this.sources_:i?[i]:[]}getRenderSource(){return this.renderedSource_||this.getSource()}getSourceState(){const t=this.getRenderSource();return t?t.getState():"undefined"}handleSourceUpdate_(){this.hasRenderer()&&this.getRenderer().clearCache(),this.getSource()&&this.setStyle(this.style_)}getSourceBandCount_(){const t=Number.MAX_SAFE_INTEGER,e=this.getSources([-t,-t,t,t],t);return e&&e.length&&"bandCount"in e[0]?e[0].bandCount:4}createRenderer(){const t=Q_(this.style_,this.getSourceBandCount_());return new _g(this,{vertexShader:t.vertexShader,fragmentShader:t.fragmentShader,uniforms:t.uniforms,cacheSize:this.cacheSize_,paletteTextures:t.paletteTextures})}renderSources(t,e){const i=this.getRenderer();let n;for(let r=0,s=e.length;r{"ready"==e.getState()&&(e.removeEventListener("change",t),this.changed())};e.addEventListener("change",t)}r=r&&"ready"==i}const s=this.renderSources(t,n);if(this.getRenderer().renderComplete&&r)return this.renderedResolution_=i.resolution,s;if(this.renderedResolution_>.5*i.resolution){const e=this.getSources(t.extent,this.renderedResolution_).filter((t=>!n.includes(t)));if(e.length>0)return this.renderSources(t,e)}return s}setStyle(t){this.styleVariables_=t.variables||{},this.style_=t;const e=Q_(this.style_,this.getSourceBandCount_());this.getRenderer().reset({vertexShader:e.vertexShader,fragmentShader:e.fragmentShader,uniforms:e.uniforms}),this.changed()}updateStyleVariables(t){Object.assign(this.styleVariables_,t),this.changed()}}ty.prototype.dispose;var ey=ty;var iy=class extends ya{constructor(t){const e=t||{};super(e),e.stopDown&&(this.stopDown=e.stopDown),this.scaleDeltaByPixel_=e.delta?e.delta:.01,this.duration_=void 0!==e.duration?e.duration:250,this.handlingDownUpSequence_=!1,this.handlingDoubleDownSequence_=!1,this.doubleTapTimeoutId_=void 0,this.trackedPointers_={},this.targetPointers=[]}handleEvent(t){if(!t.originalEvent)return!0;let e=!1;if(this.updateTrackedPointers_(t),this.handlingDownUpSequence_){if(t.type==Wo.POINTERDRAG)this.handleDragEvent(t),t.originalEvent.preventDefault();else if(t.type==Wo.POINTERUP){const e=this.handleUpEvent(t);this.handlingDownUpSequence_=e}}else if(t.type==Wo.POINTERDOWN)if(this.handlingDoubleDownSequence_){this.handlingDoubleDownSequence_=!1;const i=this.handleDownEvent(t);this.handlingDownUpSequence_=i,e=this.stopDown(i)}else e=this.stopDown(!1),this.waitForDblTap_();return!e}handleDragEvent(t){let e=1;const i=this.targetPointers[0],n=this.down_.originalEvent,r=i.clientY-n.clientY;void 0!==this.lastDistance_&&(e=1-(this.lastDistance_-r)*this.scaleDeltaByPixel_),this.lastDistance_=r,1!=e&&(this.lastScaleDelta_=e);const s=t.map,o=s.getView();s.render(),o.adjustResolutionInternal(e)}handleDownEvent(t){if(1==this.targetPointers.length){const e=t.map;return this.anchor_=null,this.lastDistance_=void 0,this.lastScaleDelta_=1,this.down_=t,this.handlingDownUpSequence_||e.getView().beginInteraction(),!0}return!1}handleUpEvent(t){if(0==this.targetPointers.length){const e=t.map.getView(),i=this.lastScaleDelta_>1?1:-1;return e.endInteraction(this.duration_,i),this.handlingDownUpSequence_=!1,this.handlingDoubleDownSequence_=!1,!1}return!0}stopDown(t){return t}updateTrackedPointers_(t){if(function(t){const e=t.type;return e===Wo.POINTERDOWN||e===Wo.POINTERDRAG||e===Wo.POINTERUP}(t)){const e=t.originalEvent,i=e.pointerId.toString();t.type==Wo.POINTERUP?delete this.trackedPointers_[i]:(t.type==Wo.POINTERDOWN||i in this.trackedPointers_)&&(this.trackedPointers_[i]=e),this.targetPointers=Object.values(this.trackedPointers_)}}waitForDblTap_(){void 0!==this.doubleTapTimeoutId_?(clearTimeout(this.doubleTapTimeoutId_),this.doubleTapTimeoutId_=void 0):(this.handlingDoubleDownSequence_=!0,this.doubleTapTimeoutId_=setTimeout(this.endInteraction_.bind(this),250))}endInteraction_(){this.handlingDoubleDownSequence_=!1,this.doubleTapTimeoutId_=void 0}};const ny="addfeatures";class ry extends r{constructor(t,e,i,n){super(t),this.features=i,this.file=e,this.projection=n}}var sy=class extends ya{constructor(t){t=t||{},super({handleEvent:p}),this.on,this.once,this.un,this.readAsBuffer_=!1,this.formats_=[];const e=t.formatConstructors?t.formatConstructors:[];for(let t=0,i=e.length;t0){this.source_&&(this.source_.clear(),this.source_.addFeatures(l)),this.dispatchEvent(new ry(ny,t,l,s));break}}}registerListeners_(){const t=this.getMap();if(t){const e=this.target?this.target:t.getViewport();this.dropListenKeys_=[D(e,F,this.handleDrop,this),D(e,P,this.handleStop,this),D(e,I,this.handleStop,this),D(e,F,this.handleStop,this)]}}setActive(t){!this.getActive()&&t&&this.registerListeners_(),this.getActive()&&!t&&this.unregisterListeners_(),super.setActive(t)}setMap(t){this.unregisterListeners_(),super.setMap(t),this.getActive()&&this.registerListeners_()}tryReadFeatures_(t,e,i){try{return t.readFeatures(e,i)}catch(t){return null}}unregisterListeners_(){this.dropListenKeys_&&(this.dropListenKeys_.forEach(G),this.dropListenKeys_=null)}handleDrop(t){const e=t.dataTransfer.files;for(let t=0,i=e.length;t1?1:-1;return e.endInteraction(this.duration_,i),this.lastScaleDelta_=0,!1}handleDownEvent(t){return!!Na(t)&&(!!this.condition_(t)&&(t.map.getView().beginInteraction(),this.lastAngle_=void 0,this.lastMagnitude_=void 0,!0))}};const ay="drawstart",ly="drawend",hy="drawabort";class cy extends r{constructor(t,e){super(t),this.feature=e}}function uy(t,e){return pi(t[0],t[1],e[0],e[1])}function dy(t,e){const i=t.length;return e<0?t[e+i]:e>=i?t[e-i]:t[e]}function gy(t,e,i){let n,r;eo){return uy(xy(t,n),xy(t,r))}let a=0;if(n=i?n-=i:n<0&&(n+=i);let s=n+1;s>=i&&(s-=i);const o=t[n],a=o[0],l=o[1],h=t[s];return[a+(h[0]-a)*r,l+(h[1]-l)*r]}function vy(){const t=gf();return function(e,i){return t[e.getGeometry().getType()]}}var Sy=class extends Sa{constructor(t){const e=t;e.stopDown||(e.stopDown=m),super(e),this.on,this.once,this.un,this.shouldHandle_=!1,this.downPx_=null,this.downTimeout_,this.lastDragTime_,this.pointerType_,this.freehand_=!1,this.source_=t.source?t.source:null,this.features_=t.features?t.features:null,this.snapTolerance_=t.snapTolerance?t.snapTolerance:12,this.type_=t.type,this.mode_=function(t){switch(t){case"Point":case"MultiPoint":return"Point";case"LineString":case"MultiLineString":return"LineString";case"Polygon":case"MultiPolygon":return"Polygon";case"Circle":return"Circle";default:throw new Error("Invalid type: "+t)}}(this.type_),this.stopClick_=!!t.stopClick,this.minPoints_=t.minPoints?t.minPoints:"Polygon"===this.mode_?3:2,this.maxPoints_="Circle"===this.mode_?2:t.maxPoints?t.maxPoints:1/0,this.finishCondition_=t.finishCondition?t.finishCondition:p,this.geometryLayout_=t.geometryLayout?t.geometryLayout:"XY";let i=t.geometryFunction;if(!i){const t=this.mode_;if("Circle"===t)i=function(t,e,i){const n=e||new Dm([NaN,NaN]),r=xn(t[0],i),s=Ni(r,xn(t[t.length-1],i));n.setCenterAndRadius(r,Math.sqrt(s),this.geometryLayout_);const o=_n();return o&&n.transform(i,o),n};else{let e;"Point"===t?e=lr:"LineString"===t?e=Vm:"Polygon"===t&&(e=Ir),i=function(i,n,r){return n?"Polygon"===t?i[0].length?n.setCoordinates([i[0].concat([i[0][0]])],this.geometryLayout_):n.setCoordinates([],this.geometryLayout_):n.setCoordinates(i,this.geometryLayout_):n=new e(i,this.geometryLayout_),n}}}this.geometryFunction_=i,this.dragVertexDelay_=void 0!==t.dragVertexDelay?t.dragVertexDelay:500,this.finishCoordinate_=null,this.sketchFeature_=null,this.sketchPoint_=null,this.sketchCoords_=null,this.sketchLine_=null,this.sketchLineCoords_=null,this.squaredClickTolerance_=t.clickTolerance?t.clickTolerance*t.clickTolerance:36,this.overlay_=new s_({source:new cc({useSpatialIndex:!1,wrapX:!!t.wrapX&&t.wrapX}),style:t.style?t.style:vy(),updateWhileInteracting:!0}),this.geometryName_=t.geometryName,this.condition_=t.condition?t.condition:La,this.freehandCondition_,t.freehand?this.freehandCondition_=ba:this.freehandCondition_=t.freehandCondition?t.freehandCondition:Aa,this.traceCondition_,this.setTrace(t.trace||!1),this.traceState_={active:!1},this.traceSource_=t.traceSource||t.source||null,this.addChangeListener(pa,this.updateState_)}setTrace(t){let e;e=t?!0===t?ba:t:Ia,this.traceCondition_=e}setMap(t){super.setMap(t),this.updateState_()}getOverlay(){return this.overlay_}handleEvent(t){t.originalEvent.type===C&&t.originalEvent.preventDefault(),this.freehand_="Point"!==this.mode_&&this.freehandCondition_(t);let e=t.type===Wo.POINTERMOVE,i=!0;if(!this.freehand_&&this.lastDragTime_&&t.type===Wo.POINTERDRAG){Date.now()-this.lastDragTime_>=this.dragVertexDelay_?(this.downPx_=t.pixel,this.shouldHandle_=!this.freehand_,e=!0):this.lastDragTime_=void 0,this.shouldHandle_&&void 0!==this.downTimeout_&&(clearTimeout(this.downTimeout_),this.downTimeout_=void 0)}return this.freehand_&&t.type===Wo.POINTERDRAG&&null!==this.sketchFeature_?(this.addToDrawing_(t.coordinate),i=!1):this.freehand_&&t.type===Wo.POINTERDOWN?i=!1:e&&this.getPointerCount()<2?(i=t.type===Wo.POINTERMOVE,i&&this.freehand_?(this.handlePointerMove_(t),this.shouldHandle_&&t.originalEvent.preventDefault()):("mouse"===t.originalEvent.pointerType||t.type===Wo.POINTERDRAG&&void 0===this.downTimeout_)&&this.handlePointerMove_(t)):t.type===Wo.DBLCLICK&&(i=!1),super.handleEvent(t)&&i}handleDownEvent(t){return this.shouldHandle_=!this.freehand_,this.freehand_?(this.downPx_=t.pixel,this.finishCoordinate_||this.startDrawing_(t.coordinate),!0):this.condition_(t)?(this.lastDragTime_=Date.now(),this.downTimeout_=setTimeout((()=>{this.handlePointerMove_(new Vo(Wo.POINTERMOVE,t.map,t.originalEvent,!1,t.frameState))}),this.dragVertexDelay_),this.downPx_=t.pixel,!0):(this.lastDragTime_=void 0,!1)}deactivateTrace_(){this.traceState_={active:!1}}toggleTraceState_(t){if(!this.traceSource_||!this.traceCondition_(t))return;if(this.traceState_.active)return void this.deactivateTrace_();const e=this.getMap(),i=Qt([e.getCoordinateFromPixel([t.pixel[0]-this.snapTolerance_,t.pixel[1]+this.snapTolerance_]),e.getCoordinateFromPixel([t.pixel[0]+this.snapTolerance_,t.pixel[1]-this.snapTolerance_])]),n=this.traceSource_.getFeaturesInExtent(i);if(0===n.length)return;const r=function(t,e){const i=[];for(let n=0;nt.endIndex||!i&&et.endIndex)&&this.removeTracedCoordinates_(e,t.endIndex):(this.removeTracedCoordinates_(t.startIndex,t.endIndex),this.addTracedCoordinates_(t,t.startIndex,e))}removeTracedCoordinates_(t,e){if(t===e)return;let i=0;if(t0&&this.removeLastPoints_(i)}addTracedCoordinates_(t,e,i){if(e===i)return;const n=[];if(e=s;--e)n.push(dy(t.coordinates,e))}n.length&&this.appendCoordinates(n)}updateTrace_(t){const e=this.traceState_;if(!e.active)return;if(-1===e.targetIndex&&Di(e.startPx,t.pixel)i.startIndex?hi.startIndex&&(h-=n.length)),l=h,a=t)}const h=e.targets[a];let c=h.ring;if(e.targetIndex===a&&c){const t=xy(h.coordinates,l);Di(i.getPixelFromCoordinate(t),e.startPx)>n&&(c=!1)}if(c){const t=h.coordinates,e=t.length,i=h.startIndex,n=l;if(ithis.squaredClickTolerance_:s<=this.squaredClickTolerance_,!this.shouldHandle_)return}this.finishCoordinate_?(this.updateTrace_(t),this.modifyDrawing_(t.coordinate)):this.createOrUpdateSketchPoint_(t.coordinate.slice())}atFinish_(t,e){let i=!1;if(this.sketchFeature_){let n=!1,r=[this.finishCoordinate_];const s=this.mode_;if("Point"===s)i=!0;else if("Circle"===s)i=2===this.sketchCoords_.length;else if("LineString"===s)n=!e&&this.sketchCoords_.length>this.minPoints_;else if("Polygon"===s){const t=this.sketchCoords_;n=t[0].length>this.minPoints_,r=[t[0][0],t[0][t[0].length-2]],r=e?[t[0][0]]:[t[0][0],t[0][t[0].length-2]]}if(n){const e=this.getMap();for(let n=0,s=r.length;n=this.maxPoints_&&(this.freehand_?r.pop():n=!0),r.push(t.slice()),this.geometryFunction_(r,e,i)):"Polygon"===s&&(r=this.sketchCoords_[0],r.length>=this.maxPoints_&&(this.freehand_?r.pop():n=!0),r.push(t.slice()),n&&(this.finishCoordinate_=r[0]),this.geometryFunction_(this.sketchCoords_,e,i)),this.createOrUpdateSketchPoint_(t.slice()),this.updateSketchFeatures_(),n&&this.finishDrawing()}removeLastPoints_(t){if(!this.sketchFeature_)return;const e=this.sketchFeature_.getGeometry(),i=this.getMap().getView().getProjection(),n=this.mode_;for(let r=0;r=2){this.finishCoordinate_=t[t.length-2].slice();const e=this.finishCoordinate_.slice();t[t.length-1]=e,this.createOrUpdateSketchPoint_(e)}this.geometryFunction_(t,e,i),"Polygon"===e.getType()&&this.sketchLine_&&this.createOrUpdateCustomSketchLine_(e)}else if("Polygon"===n){t=this.sketchCoords_[0],t.splice(-2,1);const n=this.sketchLine_.getGeometry();if(t.length>=2){const e=t[t.length-2].slice();t[t.length-1]=e,this.createOrUpdateSketchPoint_(e)}n.setCoordinates(t),this.geometryFunction_(this.sketchCoords_,e,i)}if(1===t.length){this.abortDrawing();break}}this.updateSketchFeatures_()}removeLastPoint(){this.removeLastPoints_(1)}finishDrawing(){const t=this.abortDrawing_();if(!t)return;let e=this.sketchCoords_;const i=t.getGeometry(),n=this.getMap().getView().getProjection();"LineString"===this.mode_?(e.pop(),this.geometryFunction_(e,i,n)):"Polygon"===this.mode_&&(e[0].pop(),this.geometryFunction_(e,i,n),e=i.getCoordinates()),"MultiPoint"===this.type_?t.setGeometry(new Km([e])):"MultiLineString"===this.type_?t.setGeometry(new Zm([e])):"MultiPolygon"===this.type_&&t.setGeometry(new $m([e])),this.dispatchEvent(new cy(ly,t)),this.features_&&this.features_.push(t),this.source_&&this.source_.addFeature(t)}abortDrawing_(){this.finishCoordinate_=null;const t=this.sketchFeature_;return this.sketchFeature_=null,this.sketchPoint_=null,this.sketchLine_=null,this.overlay_.getSource().clear(!0),this.deactivateTrace_(),t}abortDrawing(){const t=this.abortDrawing_();t&&this.dispatchEvent(new cy(hy,t))}appendCoordinates(t){const e=this.mode_,i=!this.sketchFeature_;let n;if(i&&this.startDrawing_(t[0]),"LineString"===e||"Circle"===e)n=this.sketchCoords_;else{if("Polygon"!==e)return;n=this.sketchCoords_&&this.sketchCoords_.length?this.sketchCoords_[0]:[]}i&&n.shift(),n.pop();for(let e=0;er?o[1]:o[0]),a}}return null}handlePointerMove_(t){const e=t.pixel,i=t.map;let n=this.snapToVertex_(e,i);n||(n=i.getCoordinateFromPixelInternal(e)),this.createOrUpdatePointerFeature_(n)}createOrUpdateExtentFeature_(t){let e=this.extentFeature_;return e?t?e.setGeometry(Lr(t)):e.setGeometry(void 0):(e=new Nt(t?Lr(t):{}),this.extentFeature_=e,this.extentOverlay_.getSource().addFeature(e)),e}createOrUpdatePointerFeature_(t){let e=this.vertexFeature_;if(e){e.getGeometry().setCoordinates(t)}else e=new Nt(new lr(t)),this.vertexFeature_=e,this.vertexOverlay_.getSource().addFeature(e);return e}handleEvent(t){return!t.originalEvent||!this.condition_(t)||(t.type!=Wo.POINTERMOVE||this.handlingDownUpSequence||this.handlePointerMove_(t),super.handleEvent(t),!1)}handleDownEvent(t){const e=t.pixel,i=t.map,n=this.getExtentInternal();let r=this.snapToVertex_(e,i);const s=function(t){let e=null,i=null;return t[0]==n[0]?e=n[2]:t[0]==n[2]&&(e=n[0]),t[1]==n[1]?i=n[3]:t[1]==n[3]&&(i=n[1]),null!==e&&null!==i?[e,i]:null};if(r&&n){const t=r[0]==n[0]||r[0]==n[2]?r[0]:null,e=r[1]==n[1]||r[1]==n[3]?r[1]:null;null!==t&&null!==e?this.pointerHandler_=Ry(s(r)):null!==t?this.pointerHandler_=by(s([t,n[1]]),s([t,n[3]])):null!==e&&(this.pointerHandler_=by(s([n[0],e]),s([n[2],e])))}else r=i.getCoordinateFromPixelInternal(e),this.setExtent([r[0],r[1],r[0],r[1]]),this.pointerHandler_=Ry(r);return!0}handleDragEvent(t){if(this.pointerHandler_){const e=t.coordinate;this.setExtent(this.pointerHandler_(e)),this.createOrUpdatePointerFeature_(e)}}handleUpEvent(t){this.pointerHandler_=null;const e=this.getExtentInternal();return e&&0!==Se(e)||this.setExtent(null),!1}setMap(t){this.extentOverlay_.setMap(t),this.vertexOverlay_.setMap(t),super.setMap(t)}getExtent(){return vn(this.getExtentInternal(),this.getMap().getView().getProjection())}getExtentInternal(){return this.extent_}setExtent(t){this.extent_=t||null,this.createOrUpdateExtentFeature_(t),this.dispatchEvent(new Ey(this.extent_))}};function Iy(t){return parseFloat(t)}function Fy(t){return function(t){return Si(t,5)}(t).toString()}function Ly(t,e){return!isNaN(t)&&t!==Iy(Fy(e))}var My=class extends ya{constructor(t){let e;super(),e=!0===(t=Object.assign({animate:!0,params:["x","y","z","r","l"],replace:!1,prefix:""},t||{})).animate?{duration:250}:t.animate?t.animate:null,this.animationOptions_=e,this.params_=t.params.reduce(((t,e)=>(t[e]=!0,t)),{}),this.replace_=t.replace,this.prefix_=t.prefix,this.listenerKeys_=[],this.initial_=!0,this.updateState_=this.updateState_.bind(this)}getParamName_(t){return this.prefix_?this.prefix_+t:t}get_(t,e){return t.get(this.getParamName_(e))}set_(t,e,i){e in this.params_&&t.set(this.getParamName_(e),i)}delete_(t,e){e in this.params_&&t.delete(this.getParamName_(e))}setMap(t){const e=this.getMap();super.setMap(t),t!==e&&(e&&this.unregisterListeners_(e),t&&(this.initial_=!0,this.updateState_(),this.registerListeners_(t)))}registerListeners_(t){this.listenerKeys_.push(D(t,Qo,this.updateUrl_,this),D(t.getLayerGroup(),E,this.updateUrl_,this),D(t,"change:layergroup",this.handleChangeLayerGroup_,this)),this.replace_||addEventListener("popstate",this.updateState_)}unregisterListeners_(t){for(let t=0,e=this.listenerKeys_.length;t=0;--t){const n=i[t];for(let t=this.dragSegments_.length-1;t>=0;--t)this.dragSegments_[t][0]===n&&this.dragSegments_.splice(t,1);e.remove(n)}}setActive(t){this.vertexFeature_&&!t&&(this.overlay_.getSource().removeFeature(this.vertexFeature_),this.vertexFeature_=null),super.setActive(t)}setMap(t){this.overlay_.setMap(t),super.setMap(t)}getOverlay(){return this.overlay_}handleSourceAdd_(t){t.feature&&this.features_.push(t.feature)}handleSourceRemove_(t){t.feature&&this.features_.remove(t.feature)}handleFeatureAdd_(t){this.addFeature_(t.element)}handleFeatureChange_(t){if(!this.changingFeature_){const e=t.target;this.removeFeature_(e),this.addFeature_(e)}}handleFeatureRemove_(t){this.removeFeature_(t.element)}writePointGeometry_(t,e){const i=e.getCoordinates(),n={feature:t,geometry:e,segment:[i,i]};this.rBush_.insert(e.getExtent(),n)}writeMultiPointGeometry_(t,e){const i=e.getCoordinates();for(let n=0,r=i.length;n=0;--t)this.insertVertex_(r[t],s)}return!!this.vertexFeature_}handleUpEvent(t){for(let e=this.dragSegments_.length-1;e>=0;--e){const i=this.dragSegments_[e][0],n=i.geometry;if("Circle"===n.getType()){const e=n.getCenter(),r=i.featureSegments[0],s=i.featureSegments[1];r.segment[0]=e,r.segment[1]=e,s.segment[0]=e,s.segment[1]=e,this.rBush_.update(ce(e),r);let o=n;const a=_n();if(a){const e=t.map.getView().getProjection();o=o.clone().transform(a,e),o=Mr(o).transform(e,a)}this.rBush_.update(o.getExtent(),s)}else this.rBush_.update(Qt(i.segment),i)}return this.featuresBeingModified_&&(this.dispatchEvent(new ky(Dy,this.featuresBeingModified_,t)),this.featuresBeingModified_=null),!1}handlePointerMove_(t){this.lastPixel_=t.pixel,this.handlePointerAtPixel_(t.pixel,t.map,t.coordinate)}handlePointerAtPixel_(t,e,i){const n=i||e.getCoordinateFromPixel(t),r=e.getView().getProjection(),s=function(t,e){return jy(n,t,r)-jy(n,e,r)};let o,a;if(this.hitDetection_){const i="object"==typeof this.hitDetection_?t=>t===this.hitDetection_:void 0;e.forEachFeatureAtPixel(t,((t,e,i)=>{i&&(i=new lr(yn(i.getCoordinates(),r)));const n=i||t.getGeometry();if("Point"===n.getType()&&t instanceof Nt&&this.features_.getArray().includes(t)){a=n;const e=t.getGeometry().getFlatCoordinates().slice(0,2);o=[{feature:t,geometry:a,segment:[e,e]}]}return!0}),{layerFilter:i})}if(!o){const t=vn(te(Sn(ce(n,Ay),r),e.getView().getResolution()*this.pixelTolerance_,Ay),r);o=this.rBush_.getInExtent(t)}if(o&&o.length>0){const i=o.sort(s)[0],l=i.segment;let h=By(n,i,r);const c=e.getPixelFromCoordinate(h);let u=Di(t,c);if(a||u<=this.pixelTolerance_){const t={};if(t[V(l)]=!0,this.snapToPointer_||(this.delta_[0]=h[0]-n[0],this.delta_[1]=h[1]-n[1]),"Circle"===i.geometry.getType()&&1===i.index)this.snappedToVertex_=!0,this.createOrUpdateVertexFeature_(h,[i.feature],[i.geometry]);else{const n=e.getPixelFromCoordinate(l[0]),r=e.getPixelFromCoordinate(l[1]),s=Ni(c,n),a=Ni(c,r);u=Math.sqrt(Math.min(s,a)),this.snappedToVertex_=u<=this.pixelTolerance_,this.snappedToVertex_&&(h=s>a?l[1]:l[0]),this.createOrUpdateVertexFeature_(h,[i.feature],[i.geometry]);const d={};d[V(i.geometry)]=!0;for(let e=1,i=o.length;e=0;--o)r=t[o],u=r[0],d=V(u.feature),u.depth&&(d+="-"+u.depth.join("-")),d in e||(e[d]={}),0===r[1]?(e[d].right=u,e[d].index=u.index):1==r[1]&&(e[d].left=u,e[d].index=u.index+1);for(d in e){switch(c=e[d].right,l=e[d].left,a=e[d].index,h=a-1,u=void 0!==l?l:c,h<0&&(h=0),s=u.geometry,n=s.getCoordinates(),i=n,g=!1,s.getType()){case"MultiLineString":n[u.depth[0]].length>2&&(n[u.depth[0]].splice(a,1),g=!0);break;case"LineString":n.length>2&&(n.splice(a,1),g=!0);break;case"MultiPolygon":i=i[u.depth[1]];case"Polygon":i=i[u.depth[0]],i.length>4&&(a==i.length-1&&(a=0),i.splice(a,1),g=!0,0===a&&(i.pop(),i.push(i[0]),h=i.length-1))}if(g){this.setGeometryCoordinates_(s,n);const e=[];if(void 0!==l&&(this.rBush_.remove(l),e.push(l.segment[0])),void 0!==c&&(this.rBush_.remove(c),e.push(c.segment[1])),void 0!==l&&void 0!==c){const t={depth:u.depth,feature:u.feature,geometry:u.geometry,index:h,segment:e};this.rBush_.insert(Qt(t.segment),t)}this.updateSegmentIndices_(s,a,u.depth,-1),this.vertexFeature_&&(this.overlay_.getSource().removeFeature(this.vertexFeature_),this.vertexFeature_=null),t.length=0}}return g}setGeometryCoordinates_(t,e){this.changingFeature_=!0,t.setCoordinates(e),this.changingFeature_=!1}updateSegmentIndices_(t,e,i,n){this.rBush_.forEachInExtent(t.getExtent(),(function(r){r.geometry===t&&(void 0===i||void 0===r.depth||g(r.depth,i))&&r.index>e&&(r.index+=n)}))}};const Xy="select";class Vy extends r{constructor(t,e,i,n){super(t),this.selected=e,this.deselected=i,this.mapBrowserEvent=n}}const Wy={};class Zy extends ya{constructor(t){let e;if(super(),this.on,this.once,this.un,t=t||{},this.boundAddFeature_=this.addFeature_.bind(this),this.boundRemoveFeature_=this.removeFeature_.bind(this),this.condition_=t.condition?t.condition:Fa,this.addCondition_=t.addCondition?t.addCondition:Ia,this.removeCondition_=t.removeCondition?t.removeCondition:Ia,this.toggleCondition_=t.toggleCondition?t.toggleCondition:Aa,this.multi_=!!t.multi&&t.multi,this.filter_=t.filter?t.filter:p,this.hitTolerance_=t.hitTolerance?t.hitTolerance:0,this.style_=void 0!==t.style?t.style:function(){const t=gf();return d(t.Polygon,t.LineString),d(t.GeometryCollection,t.LineString),function(e){return e.getGeometry()?t[e.getGeometry().getType()]:null}}(),this.features_=t.features||new $,t.layers)if("function"==typeof t.layers)e=t.layers;else{const i=t.layers;e=function(t){return i.includes(t)}}else e=p;this.layerFilter_=e,this.featureLayerAssociation_={}}addFeatureLayerAssociation_(t,e){this.featureLayerAssociation_[V(t)]=e}getFeatures(){return this.features_}getHitTolerance(){return this.hitTolerance_}getLayer(t){return this.featureLayerAssociation_[V(t)]}setHitTolerance(t){this.hitTolerance_=t}setMap(t){this.getMap()&&this.style_&&this.features_.forEach(this.restorePreviousStyle_.bind(this)),super.setMap(t),t?(this.features_.addEventListener(Y,this.boundAddFeature_),this.features_.addEventListener(K,this.boundRemoveFeature_),this.style_&&this.features_.forEach(this.applySelectedStyle_.bind(this))):(this.features_.removeEventListener(Y,this.boundAddFeature_),this.features_.removeEventListener(K,this.boundRemoveFeature_))}addFeature_(t){const e=t.element;if(this.style_&&this.applySelectedStyle_(e),!this.getLayer(e)){const t=this.getMap().getAllLayers().find((function(t){if(t instanceof s_&&t.getSource()&&t.getSource().hasFeature(e))return t}));t&&this.addFeatureLayerAssociation_(e,t)}}removeFeature_(t){this.style_&&this.restorePreviousStyle_(t.element)}getStyle(){return this.style_}applySelectedStyle_(t){const e=V(t);e in Wy||(Wy[e]=t.getStyle()),t.setStyle(this.style_)}restorePreviousStyle_(t){const e=this.getMap().getInteractions().getArray();for(let i=e.length-1;i>=0;--i){const n=e[i];if(n!==this&&n instanceof Zy&&n.getStyle()&&-1!==n.getFeatures().getArray().lastIndexOf(t))return void t.setStyle(n.getStyle())}const i=V(t);t.setStyle(Wy[i]),delete Wy[i]}removeFeatureLayerAssociation_(t){delete this.featureLayerAssociation_[V(t)]}handleEvent(t){if(!this.condition_(t))return!0;const e=this.addCondition_(t),i=this.removeCondition_(t),n=this.toggleCondition_(t),r=!e&&!i&&!n,s=t.map,o=this.getFeatures(),a=[],l=[];if(r){v(this.featureLayerAssociation_),s.forEachFeatureAtPixel(t.pixel,((t,e)=>{if(t instanceof Nt&&this.filter_(t,e))return this.addFeatureLayerAssociation_(t,e),l.push(t),!this.multi_}),{layerFilter:this.layerFilter_,hitTolerance:this.hitTolerance_});for(let t=o.getLength()-1;t>=0;--t){const e=o.item(t),i=l.indexOf(e);i>-1?l.splice(i,1):(o.remove(e),a.push(e))}0!==l.length&&o.extend(l)}else{s.forEachFeatureAtPixel(t.pixel,((t,r)=>{if(t instanceof Nt&&this.filter_(t,r))return!e&&!n||o.getArray().includes(t)?(i||n)&&o.getArray().includes(t)&&(a.push(t),this.removeFeatureLayerAssociation_(t)):(this.addFeatureLayerAssociation_(t,r),l.push(t)),!this.multi_}),{layerFilter:this.layerFilter_,hitTolerance:this.hitTolerance_});for(let t=a.length-1;t>=0;--t)o.remove(a[t]);o.extend(l)}return(l.length>0||a.length>0)&&this.dispatchEvent(new Vy(Xy,l,a,t)),!0}}var Yy=Zy;const Ky="snap";class Hy extends r{constructor(t,e){super(t),this.vertex=e.vertex,this.vertexPixel=e.vertexPixel,this.feature=e.feature}}function qy(t){return t.feature?t.feature:t.element?t.element:null}const $y=[];var Jy=class extends Sa{constructor(t){const e=t=t||{};e.handleDownEvent||(e.handleDownEvent=p),e.stopDown||(e.stopDown=m),super(e),this.on,this.once,this.un,this.source_=t.source?t.source:null,this.vertex_=void 0===t.vertex||t.vertex,this.edge_=void 0===t.edge||t.edge,this.features_=t.features?t.features:null,this.featuresListenerKeys_=[],this.featureChangeListenerKeys_={},this.indexedFeaturesExtents_={},this.pendingFeatures_={},this.pixelTolerance_=void 0!==t.pixelTolerance?t.pixelTolerance:10,this.rBush_=new ec,this.GEOMETRY_SEGMENTERS_={Point:this.segmentPointGeometry_.bind(this),LineString:this.segmentLineStringGeometry_.bind(this),LinearRing:this.segmentLineStringGeometry_.bind(this),Polygon:this.segmentPolygonGeometry_.bind(this),MultiPoint:this.segmentMultiPointGeometry_.bind(this),MultiLineString:this.segmentMultiLineStringGeometry_.bind(this),MultiPolygon:this.segmentMultiPolygonGeometry_.bind(this),GeometryCollection:this.segmentGeometryCollectionGeometry_.bind(this),Circle:this.segmentCircleGeometry_.bind(this)}}addFeature(t,e){e=void 0===e||e;const i=V(t),n=t.getGeometry();if(n){const e=this.GEOMETRY_SEGMENTERS_[n.getType()];if(e){this.indexedFeaturesExtents_[i]=n.getExtent([1/0,1/0,-1/0,-1/0]);const r=[];if(e(r,n),1===r.length)this.rBush_.insert(Qt(r[0]),{feature:t,segment:r[0]});else if(r.length>1){const e=r.map((t=>Qt(t))),i=r.map((e=>({feature:t,segment:e})));this.rBush_.load(e,i)}}}e&&(this.featureChangeListenerKeys_[i]=D(t,E,this.handleFeatureChange_,this))}getFeatures_(){let t;return this.features_?t=this.features_:this.source_&&(t=this.source_.getFeatures()),t}handleEvent(t){const e=this.snapTo(t.pixel,t.coordinate,t.map);return e&&(t.coordinate=e.vertex.slice(0,2),t.pixel=e.vertexPixel,this.dispatchEvent(new Hy(Ky,{vertex:t.coordinate,vertexPixel:t.pixel,feature:e.feature}))),super.handleEvent(t)}handleFeatureAdd_(t){const e=qy(t);e&&this.addFeature(e)}handleFeatureRemove_(t){const e=qy(t);e&&this.removeFeature(e)}handleFeatureChange_(t){const e=t.target;if(this.handlingDownUpSequence){const t=V(e);t in this.pendingFeatures_||(this.pendingFeatures_[t]=e)}else this.updateFeature_(e)}handleUpEvent(t){const e=Object.values(this.pendingFeatures_);return e.length&&(e.forEach(this.updateFeature_.bind(this)),this.pendingFeatures_={}),!1}removeFeature(t,e){const i=void 0===e||e,n=V(t),r=this.indexedFeaturesExtents_[n];if(r){const e=this.rBush_,i=[];e.forEachInExtent(r,(function(e){t===e.feature&&i.push(e)}));for(let t=i.length-1;t>=0;--t)e.remove(i[t])}i&&(G(this.featureChangeListenerKeys_[n]),delete this.featureChangeListenerKeys_[n])}setMap(t){const e=this.getMap(),i=this.featuresListenerKeys_,n=this.getFeatures_();e&&(i.forEach(G),i.length=0,this.rBush_.clear(),Object.values(this.featureChangeListenerKeys_).forEach(G),this.featureChangeListenerKeys_={}),super.setMap(t),t&&(this.features_?i.push(D(this.features_,Y,this.handleFeatureAdd_,this),D(this.features_,K,this.handleFeatureRemove_,this)):this.source_&&i.push(D(this.source_,ic,this.handleFeatureAdd_,this),D(this.source_,sc,this.handleFeatureRemove_,this)),n.forEach((t=>this.addFeature(t))))}snapTo(t,e,i){const n=i.getView().getProjection(),r=xn(e,n),s=vn(te(Qt([r]),i.getView().getResolution()*this.pixelTolerance_),n),o=this.rBush_.getInExtent(s),a=o.length;if(0===a)return null;let l,h,c=1/0;const u=this.pixelTolerance_*this.pixelTolerance_,d=()=>{if(l){const e=i.getPixelFromCoordinate(l);if(Ni(t,e)<=u)return{vertex:l,vertexPixel:[Math.round(e[0]),Math.round(e[1])],feature:h}}return null};if(this.vertex_){for(let t=0;t{const i=xn(t,n),s=Ni(r,i);s{t.push([e])}))}segmentMultiPolygonGeometry_(t,e){const i=e.getCoordinates();for(let e=0,n=i.length;e{if(t instanceof Nt&&this.filter_(t,e)&&(!this.features_||this.features_.getArray().includes(t)))return t}),{layerFilter:this.layerFilter_,hitTolerance:this.hitTolerance_})}getHitTolerance(){return this.hitTolerance_}setHitTolerance(t){this.hitTolerance_=t}setMap(t){const e=this.getMap();super.setMap(t),this.updateState_(e)}handleActiveChanged_(){this.updateState_(null)}updateState_(t){let e=this.getMap();const i=this.getActive();if((!e||!i)&&(e=e||t,e)){e.getViewport().classList.remove("ol-grab","ol-grabbing")}}};function rx(t,e,i,n,r,s){void 0!==r?s=void 0!==s?s:0:(r=[],s=0);let o=e;for(;o=0;e--)r.push(n[t][e]);return{hasZ:i.hasZ,hasM:i.hasM,rings:r}}};function hx(t,e){if(!t)return null;let i;if("number"==typeof t.x&&"number"==typeof t.y)i="Point";else if(t.points)i="MultiPoint";else if(t.paths){i=1===t.paths.length?"LineString":"MultiLineString"}else if(t.rings){const e=t,n=cx(e),r=function(t,e){const i=[],n=[],r=[];let s,o;for(s=0,o=t.length;s=0;s--){const i=n[s][0];if(re(new or(i).getExtent(),new or(t).getExtent())){n[s].push(t),e=!0;break}}e||n.push([t.reverse()])}return n}(e.rings,n);1===r.length?(i="Polygon",t=Object.assign({},t,{rings:r[0]})):(i="MultiPolygon",t=Object.assign({},t,{rings:r}))}return y_((0,ax[i])(t),!1,e)}function cx(t){let e="XY";return!0===t.hasZ&&!0===t.hasM?e="XYZM":!0===t.hasZ?e="XYZ":!0===t.hasM&&(e="XYM"),e}function ux(t){const e=t.getLayout();return{hasZ:"XYZ"===e||"XYZM"===e,hasM:"XYM"===e||"XYZM"===e}}function dx(t,e){return(0,lx[t.getType()])(y_(t,!0,e),e)}var gx=class extends ox{constructor(t){t=t||{},super(),this.geometryName_=t.geometryName}readFeatureFromObject(t,e,i){const n=t,r=hx(n.geometry,e),s=new Nt;if(this.geometryName_&&s.setGeometryName(this.geometryName_),s.setGeometry(r),n.attributes){s.setProperties(n.attributes,!0);const t=n.attributes[i];void 0!==t&&s.setId(t)}return s}readFeaturesFromObject(t,e){if(e=e||{},t.features){const i=[],n=t.features;for(let r=0,s=n.length;r0?i[0]:null}readFeatureFromNode(t,e){return null}readFeatures(t,e){if(!t)return[];if("string"==typeof t){const i=fd(t);return this.readFeaturesFromDocument(i,e)}return dd(t)?this.readFeaturesFromDocument(t,e):this.readFeaturesFromNode(t,e)}readFeaturesFromDocument(t,e){const i=[];for(let n=t.firstChild;n;n=n.nextSibling)n.nodeType==Node.ELEMENT_NODE&&d(i,this.readFeaturesFromNode(n,e));return i}readFeaturesFromNode(t,e){return z()}readGeometry(t,e){if(!t)return null;if("string"==typeof t){const i=fd(t);return this.readGeometryFromDocument(i,e)}return dd(t)?this.readGeometryFromDocument(t,e):this.readGeometryFromNode(t,e)}readGeometryFromDocument(t,e){return null}readGeometryFromNode(t,e){return null}readProjection(t){if(!t)return null;if("string"==typeof t){const e=fd(t);return this.readProjectionFromDocument(e)}return dd(t)?this.readProjectionFromDocument(t):this.readProjectionFromNode(t)}readProjectionFromDocument(t){return this.dataProjection}readProjectionFromNode(t){return this.dataProjection}writeFeature(t,e){const i=this.writeFeatureNode(t,e);return this.xmlSerializer_.serializeToString(i)}writeFeatureNode(t,e){return null}writeFeatures(t,e){const i=this.writeFeaturesNode(t,e);return this.xmlSerializer_.serializeToString(i)}writeFeaturesNode(t,e){return null}writeGeometry(t,e){const i=this.writeGeometryNode(t,e);return this.xmlSerializer_.serializeToString(i)}writeGeometryNode(t,e){return null}};const px="http://www.opengis.net/gml",mx=/^\s*$/;class _x extends fx{constructor(t){super(),t=t||{},this.featureType=t.featureType,this.featureNS=t.featureNS,this.srsName=t.srsName,this.schemaLocation="",this.FEATURE_COLLECTION_PARSERS={},this.FEATURE_COLLECTION_PARSERS[this.namespace]={featureMember:md(this.readFeaturesInternal),featureMembers:_d(this.readFeaturesInternal)},this.supportedMediaTypes=["application/gml+xml"]}readFeaturesInternal(t,e){const i=t.localName;let n=null;if("FeatureCollection"==i)n=bd([],this.FEATURE_COLLECTION_PARSERS,t,e,this);else if("featureMembers"==i||"featureMember"==i||"member"==i){const r=e[0];let s=r.featureType,o=r.featureNS;const a="p",l="p0";if(!s&&t.childNodes){s=[],o={};for(let e=0,i=t.childNodes.length;e0&&!(t instanceof Ln)){t={_content_:t};for(let e=0;e0){e[e.length-1].push(...i)}},outerBoundaryIs:function(t,e){const i=bd(void 0,KS,t,e);if(i){e[e.length-1][0]=i}}});function NS(t,e){const i=bd({},PS,t,e),n=bd([null],OS,t,e);if(n&&n[0]){const t=n[0],e=[t.length];for(let i=1,r=n.length;i0;let o;const a=r.href;let l,h,c;a?o=a:s&&(o=qv);let u="bottom-left";const d=i.hotSpot;let g;d?(l=[d.x,d.y],h=d.xunits,c=d.yunits,u=d.origin):/^https?:\/\/maps\.(?:google|gstatic)\.com\//.test(o)&&(o.includes("pushpin")?(l=Zv,h=Yv,c=Kv):o.includes("arrow-reverse")?(l=[54,42],h=Yv,c=Kv):o.includes("paddle")&&(l=[32,1],h=Yv,c=Kv));const f=r.x,p=r.y;let m;void 0!==f&&void 0!==p&&(g=[f,p]);const _=r.w,y=r.h;let x;void 0!==_&&void 0!==y&&(m=[_,y]);const v=i.heading;void 0!==v&&(x=yi(v));const S=i.scale,w=i.color;if(s){o==qv&&(m=Hv);const t=new of({anchor:l,anchorOrigin:u,anchorXUnits:h,anchorYUnits:c,crossOrigin:this.crossOrigin_,offset:g,offsetOrigin:"bottom-left",rotation:x,scale:S,size:m,src:this.iconUrlFunction_(o),color:w}),e=t.getScaleArray()[0],i=t.getSize();if(null===i){const i=t.getImageState();if(i===Kr||i===Hr){const n=function(){const i=t.getImageState();if(i!==Kr&&i!==Hr){const i=t.getSize();if(i&&2==i.length){const n=oS(i);t.setScale(e*n)}t.unlistenImageChange(n)}};t.listenImageChange(n),i===Kr&&t.load()}}else if(2==i.length){const n=oS(i);t.setScale(e*n)}n.imageStyle=t}else n.imageStyle=Jv},LabelStyle:function(t,e){const i=bd({},_S,t,e);if(!i)return;const n=e[e.length-1],r=new _f({fill:new Jg({color:"color"in i?i.color:Wv}),scale:i.scale});n.textStyle=r},LineStyle:function(t,e){const i=bd({},yS,t,e);if(!i)return;const n=e[e.length-1],r=new lf({color:"color"in i?i.color:Wv,width:"width"in i?i.width:1});n.strokeStyle=r},PolyStyle:function(t,e){const i=bd({},xS,t,e);if(!i)return;const n=e[e.length-1],r=new Jg({color:"color"in i?i.color:Wv});n.fillStyle=r;const s=i.fill;void 0!==s&&(n.fill=s);const o=i.outline;void 0!==o&&(n.outline=o)}});function kS(t,e){const i=bd({},DS,t,e,this);if(!i)return null;let n="fillStyle"in i?i.fillStyle:$v;const r=i.fill;let s;void 0===r||r||(n=null),"imageStyle"in i?i.imageStyle!=Jv&&(s=i.imageStyle):s=Qv;const o="textStyle"in i?i.textStyle:iS,a="strokeStyle"in i?i.strokeStyle:eS,l=i.outline;return void 0===l||l?[new pf({fill:n,image:s,stroke:a,text:o,zIndex:void 0})]:[new pf({geometry:function(t){const e=t.getGeometry(),i=e.getType();if("GeometryCollection"===i){return new jm(e.getGeometriesArrayRecursive().filter((function(t){const e=t.getType();return"Polygon"!==e&&"MultiPolygon"!==e})))}if("Polygon"!==i&&"MultiPolygon"!==i)return e},fill:n,image:s,stroke:a,text:o,zIndex:void 0}),new pf({geometry:function(t){const e=t.getGeometry(),i=e.getType();if("GeometryCollection"===i){return new jm(e.getGeometriesArrayRecursive().filter((function(t){const e=t.getType();return"Polygon"===e||"MultiPolygon"===e})))}if("Polygon"===i||"MultiPolygon"===i)return e},fill:n,stroke:null,zIndex:void 0})]}function GS(t,e){const i=e.length,n=new Array(e.length),r=new Array(e.length),s=new Array(e.length);let o,a,l;o=!1,a=!1,l=!1;for(let t=0;t0){const t=Td(r,o);Id(n,xw,Sw,[{names:o,values:t}],i)}const u=i[0];let d=e.getGeometry();d&&(d=y_(d,!0,u)),Id(n,xw,cw,[d],i)}const Ew=Cd(Dv,["extrude","tessellate","altitudeMode","coordinates"]),Tw=Cd(Dv,{extrude:vd(bx),tessellate:vd(bx),altitudeMode:vd(Mx),coordinates:vd((function(t,e,i){const n=i[i.length-1],r=n.layout,s=n.stride;let o;"XY"==r||"XYM"==r?o=2:"XYZ"==r||"XYZM"==r?o=3:Mt(!1,34);const a=e.length;let l="";if(a>0){l+=e[0];for(let t=1;t0;else{const e=t.getType();a="Point"===e||"MultiPoint"===e}}a&&(l=s.get("name"),a=a&&!!l,a&&/&[^&]+;/.test(l)&&(rS||(rS=document.createElement("textarea")),rS.innerHTML=l,l=rS.value));let c=i;if(t?c=t:e&&(c=lS(e,i,n)),a){const t=function(t,e){const i=[0,0];let n="start";const r=t.getImage();if(r){const t=r.getSize();if(t&&2==t.length){const e=r.getScaleArray(),s=r.getAnchor();i[0]=e[0]*(t[0]-s[0]),i[1]=e[1]*(t[1]/2-s[1]),n="left"}}let s=t.getText();s?(s=s.clone(),s.setFont(s.getFont()||iS.getFont()),s.setScale(s.getScale()||iS.getScale()),s.setFill(s.getFill()||iS.getFill()),s.setStroke(s.getStroke()||tS)):s=iS.clone();s.setText(e),s.setOffsetX(i[0]),s.setOffsetY(i[1]),s.setTextAlign(n);const o=new pf({image:r,text:s});return o}(c[0],l);if(h.length>0){t.setGeometry(new jm(h));return[t,new pf({geometry:c[0].getGeometry(),image:null,fill:c[0].getFill(),stroke:c[0].getStroke(),text:null})].concat(c.slice(1))}return t}return c}}(i.Style,i.styleUrl,this.defaultStyle_,this.sharedStyles_,this.showPointNames_);n.setStyle(t)}return delete i.Style,n.setProperties(i,!0),n}readSharedStyle_(t,e){const i=t.getAttribute("id");if(null!==i){const n=kS.call(this,t,e);if(n){let e,r=t.baseURI;if(r&&"about:blank"!=r||(r=window.location.href),r){e=new URL("#"+i,r).href}else e="#"+i;this.sharedStyles_[e]=n}}}readSharedStyleMap_(t,e){const i=t.getAttribute("id");if(null===i)return;const n=pS.call(this,t,e);if(!n)return;let r,s=t.baseURI;if(s&&"about:blank"!=s||(s=window.location.href),s){r=new URL("#"+i,s).href}else r="#"+i;this.sharedStyles_[r]=n}readFeatureFromNode(t,e){if(!Dv.includes(t.namespaceURI))return null;const i=this.readPlacemark_(t,[this.getReadOptions(t,e)]);return i||null}readFeaturesFromNode(t,e){if(!Dv.includes(t.namespaceURI))return[];let i;const n=t.localName;if("Document"==n||"Folder"==n)return i=this.readDocumentOrFolder_(t,[this.getReadOptions(t,e)]),i||[];if("Placemark"==n){const i=this.readPlacemark_(t,[this.getReadOptions(t,e)]);return i?[i]:[]}if("kml"==n){i=[];for(let n=t.firstElementChild;n;n=n.nextElementSibling){const t=this.readFeaturesFromNode(n,e);t&&d(i,t)}return i}return[]}readName(t){if(t){if("string"==typeof t){const e=fd(t);return this.readNameFromDocument(e)}return dd(t)?this.readNameFromDocument(t):this.readNameFromNode(t)}}readNameFromDocument(t){for(let e=t.firstChild;e;e=e.nextSibling)if(e.nodeType==Node.ELEMENT_NODE){const t=this.readNameFromNode(e);if(t)return t}}readNameFromNode(t){for(let e=t.firstElementChild;e;e=e.nextElementSibling)if(Dv.includes(e.namespaceURI)&&"name"==e.localName)return Rx(e);for(let e=t.firstElementChild;e;e=e.nextElementSibling){const t=e.localName;if(Dv.includes(e.namespaceURI)&&("Document"==t||"Folder"==t||"Placemark"==t||"kml"==t)){const t=this.readNameFromNode(e);if(t)return t}}}readNetworkLinks(t){const e=[];if("string"==typeof t){const i=fd(t);d(e,this.readNetworkLinksFromDocument(i))}else dd(t)?d(e,this.readNetworkLinksFromDocument(t)):d(e,this.readNetworkLinksFromNode(t));return e}readNetworkLinksFromDocument(t){const e=[];for(let i=t.firstChild;i;i=i.nextSibling)i.nodeType==Node.ELEMENT_NODE&&d(e,this.readNetworkLinksFromNode(i));return e}readNetworkLinksFromNode(t){const e=[];for(let i=t.firstElementChild;i;i=i.nextElementSibling)if(Dv.includes(i.namespaceURI)&&"NetworkLink"==i.localName){const t=bd({},jv,i,[]);e.push(t)}for(let i=t.firstElementChild;i;i=i.nextElementSibling){const t=i.localName;!Dv.includes(i.namespaceURI)||"Document"!=t&&"Folder"!=t&&"kml"!=t||d(e,this.readNetworkLinksFromNode(i))}return e}readRegion(t){const e=[];if("string"==typeof t){const i=fd(t);d(e,this.readRegionFromDocument(i))}else dd(t)?d(e,this.readRegionFromDocument(t)):d(e,this.readRegionFromNode(t));return e}readRegionFromDocument(t){const e=[];for(let i=t.firstChild;i;i=i.nextSibling)i.nodeType==Node.ELEMENT_NODE&&d(e,this.readRegionFromNode(i));return e}readRegionFromNode(t){const e=[];for(let i=t.firstElementChild;i;i=i.nextElementSibling)if(Dv.includes(i.namespaceURI)&&"Region"==i.localName){const t=bd({},zv,i,[]);e.push(t)}for(let i=t.firstElementChild;i;i=i.nextElementSibling){const t=i.localName;!Dv.includes(i.namespaceURI)||"Document"!=t&&"Folder"!=t&&"kml"!=t||d(e,this.readRegionFromNode(i))}return e}readCamera(t){const e=[];if("string"==typeof t){const i=fd(t);d(e,this.readCameraFromDocument(i))}else dd(t)?d(e,this.readCameraFromDocument(t)):d(e,this.readCameraFromNode(t));return e}readCameraFromDocument(t){const e=[];for(let i=t.firstChild;i;i=i.nextSibling)i.nodeType===Node.ELEMENT_NODE&&d(e,this.readCameraFromNode(i));return e}readCameraFromNode(t){const e=[];for(let i=t.firstElementChild;i;i=i.nextElementSibling)if(Dv.includes(i.namespaceURI)&&"Camera"===i.localName){const t=bd({},Uv,i,[]);e.push(t)}for(let i=t.firstElementChild;i;i=i.nextElementSibling){const t=i.localName;!Dv.includes(i.namespaceURI)||"Document"!==t&&"Folder"!==t&&"Placemark"!==t&&"kml"!==t||d(e,this.readCameraFromNode(i))}return e}writeFeaturesNode(t,e){e=this.adaptOptions(e);const i=hd(Dv[4],"kml"),n="http://www.w3.org/2000/xmlns/";i.setAttributeNS(n,"xmlns:gx",Nv[0]),i.setAttributeNS(n,"xmlns:xsi",ld),i.setAttributeNS(ld,"xsi:schemaLocation","http://www.opengis.net/kml/2.2 https://developers.google.com/kml/schema/kml22gx.xsd");const r={node:i},s={};t.length>1?s.Document=t:1==t.length&&(s.Placemark=t[0]);const o=Xv[i.namespaceURI],a=Td(s,o);return Id(r,Vv,Ed,a,[e],o,this),i}};const Dw=[null],kw=Cd(Dw,{nd:function(t,e){const i=e[e.length-1];i.ndrefs.push(t.getAttribute("ref")),t.hasAttribute("lon")&&t.hasAttribute("lat")&&(i.flatCoordinates.push(parseFloat(t.getAttribute("lon"))),i.flatCoordinates.push(parseFloat(t.getAttribute("lat"))))},tag:Bw}),Gw=Cd(Dw,{node:function(t,e){const i=e[0],n=e[e.length-1],r=t.getAttribute("id"),s=[parseFloat(t.getAttribute("lon")),parseFloat(t.getAttribute("lat"))];n.nodes[r]=s;const o=bd({tags:{}},jw,t,e);if(!S(o.tags)){const t=new lr(s);y_(t,!1,i);const e=new Nt(t);void 0!==r&&e.setId(r),e.setProperties(o.tags,!0),n.features.push(e)}},way:function(t,e){const i=bd({id:t.getAttribute("id"),ndrefs:[],flatCoordinates:[],tags:{}},kw,t,e);e[e.length-1].ways.push(i)}});const jw=Cd(Dw,{tag:Bw});function Bw(t,e){e[e.length-1].tags[t.getAttribute("k")]=t.getAttribute("v")}var Uw=class extends fx{constructor(){super(),this.dataProjection=nn("EPSG:4326")}readFeaturesFromNode(t,e){if(e=this.getReadOptions(t,e),"osm"==t.localName){const i=bd({nodes:{},ways:[],features:[]},Gw,t,[e]);for(let t=0;t>1):i>>1}return e}function gE(t){let e="";for(let i=0,n=t.length;i=32;)e=63+(32|31&t),i+=String.fromCharCode(e),t>>=5;return e=t+63,i+=String.fromCharCode(e),i}var mE=class extends Iv{constructor(t){super(),t=t||{},this.dataProjection=nn("EPSG:4326"),this.factor_=t.factor?t.factor:1e5,this.geometryLayout_=t.geometryLayout?t.geometryLayout:"XY"}readFeatureFromText(t,e){const i=this.readGeometryFromText(t,e);return new Nt(i)}readFeaturesFromText(t,e){return[this.readFeatureFromText(t,e)]}readGeometryFromText(t,e){const i=Mn(this.geometryLayout_),n=lE(t,i,this.factor_);rx(n,0,n.length,i,n);const r=Qn(n,0,n.length,i);return y_(new Vm(r,this.geometryLayout_),!1,this.adaptOptions(e))}writeFeatureText(t,e){const i=t.getGeometry();return i?this.writeGeometryText(i,e):(Mt(!1,40),"")}writeFeaturesText(t,e){return this.writeFeatureText(t[0],e)}writeGeometryText(t,e){const i=(t=y_(t,!0,this.adaptOptions(e))).getFlatCoordinates(),n=t.getStride();return rx(i,0,i.length,n,i),aE(i,n,this.factor_)}};const _E={Point:function(t,e,i){const n=t.coordinates;e&&i&&wE(n,e,i);return new lr(n)},LineString:function(t,e){const i=yE(t.arcs,e);return new Vm(i)},Polygon:function(t,e){const i=[];for(let n=0,r=t.arcs.length;n0&&i.pop(),n>=0){const t=e[n];for(let e=0,n=t.length;e=0;--e)i.push(t[e].slice(0))}return i}function xE(t,e,i,n,r,s,o){const a=t.geometries,l=[];for(let t=0,h=a.length;t=2,57)}};var RE=class extends CE{constructor(t){super("And",Array.prototype.slice.call(arguments))}};var bE=class extends TE{constructor(t,e,i){if(super("BBOX"),this.geometryName=t,this.extent=e,4!==e.length)throw new Error("Expected an extent with four values ([minX, minY, maxX, maxY])");this.srsName=i}};var PE=class extends TE{constructor(t,e,i,n){super(t),this.geometryName=e||"the_geom",this.geometry=i,this.srsName=n}};var IE=class extends PE{constructor(t,e,i){super("Contains",t,e,i)}};var FE=class extends PE{constructor(t,e,i,n,r){super("DWithin",t,e,r),this.distance=i,this.unit=n}};var LE=class extends PE{constructor(t,e,i){super("Disjoint",t,e,i)}};var ME=class extends TE{constructor(t,e){super(t),this.propertyName=e}};var AE=class extends ME{constructor(t,e,i){super("During",t),this.begin=e,this.end=i}};var OE=class extends ME{constructor(t,e,i,n){super(t,e),this.expression=i,this.matchCase=n}};var NE=class extends OE{constructor(t,e,i){super("PropertyIsEqualTo",t,e,i)}};var DE=class extends OE{constructor(t,e){super("PropertyIsGreaterThan",t,e)}};var kE=class extends OE{constructor(t,e){super("PropertyIsGreaterThanOrEqualTo",t,e)}};var GE=class extends PE{constructor(t,e,i){super("Intersects",t,e,i)}};var jE=class extends ME{constructor(t,e,i){super("PropertyIsBetween",t),this.lowerBoundary=e,this.upperBoundary=i}};var BE=class extends ME{constructor(t,e,i,n,r,s){super("PropertyIsLike",t),this.pattern=e,this.wildCard=void 0!==i?i:"*",this.singleChar=void 0!==n?n:".",this.escapeChar=void 0!==r?r:"!",this.matchCase=s}};var UE=class extends ME{constructor(t){super("PropertyIsNull",t)}};var zE=class extends OE{constructor(t,e){super("PropertyIsLessThan",t,e)}};var XE=class extends OE{constructor(t,e){super("PropertyIsLessThanOrEqualTo",t,e)}};var VE=class extends TE{constructor(t){super("Not"),this.condition=t}};var WE=class extends OE{constructor(t,e,i){super("PropertyIsNotEqualTo",t,e,i)}};var ZE=class extends CE{constructor(t){super("Or",Array.prototype.slice.call(arguments))}};var YE=class extends TE{constructor(t){super("ResourceId"),this.rid=t}};var KE=class extends PE{constructor(t,e,i){super("Within",t,e,i)}};function HE(t){const e=[null].concat(Array.prototype.slice.call(arguments));return new(Function.prototype.bind.apply(RE,e))}function qE(t,e,i){return new bE(t,e,i)}const $E={"http://www.opengis.net/gml":{boundedBy:xd(yx.prototype.readExtentElement,"bounds")},"http://www.opengis.net/wfs/2.0":{member:md(yx.prototype.readFeaturesInternal)}},JE={"http://www.opengis.net/wfs":{totalInserted:xd(Tx),totalUpdated:xd(Tx),totalDeleted:xd(Tx)},"http://www.opengis.net/wfs/2.0":{totalInserted:xd(Tx),totalUpdated:xd(Tx),totalDeleted:xd(Tx)}},QE={"http://www.opengis.net/wfs":{TransactionSummary:xd(cT,"transactionSummary"),InsertResults:xd(fT,"insertIds")},"http://www.opengis.net/wfs/2.0":{TransactionSummary:xd(cT,"transactionSummary"),InsertResults:xd(fT,"insertIds")}},tT={"http://www.opengis.net/wfs":{PropertyName:vd(Mx)},"http://www.opengis.net/wfs/2.0":{PropertyName:vd(Mx)}},eT={"http://www.opengis.net/wfs":{Insert:vd(pT),Update:vd(xT),Delete:vd(yT),Property:vd(vT),Native:vd(ST)},"http://www.opengis.net/wfs/2.0":{Insert:vd(pT),Update:vd(xT),Delete:vd(yT),Property:vd(vT),Native:vd(ST)}},iT="feature",nT="http://www.w3.org/2000/xmlns/",rT={"2.0.0":"http://www.opengis.net/ogc/1.1","1.1.0":"http://www.opengis.net/ogc","1.0.0":"http://www.opengis.net/ogc"},sT={"2.0.0":"http://www.opengis.net/wfs/2.0","1.1.0":"http://www.opengis.net/wfs","1.0.0":"http://www.opengis.net/wfs"},oT={"2.0.0":"http://www.opengis.net/fes/2.0","1.1.0":"http://www.opengis.net/fes","1.0.0":"http://www.opengis.net/fes"},aT={"2.0.0":"http://www.opengis.net/wfs/2.0 http://schemas.opengis.net/wfs/2.0/wfs.xsd","1.1.0":"http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.1.0/wfs.xsd","1.0.0":"http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.0.0/wfs.xsd"},lT={"2.0.0":Vx,"1.1.0":Bx,"1.0.0":Dx};function hT(t,e,i,n){Id(n,eT,wd(t),e,i)}function cT(t,e){return bd({},JE,t,e)}const uT={"http://www.opengis.net/ogc":{FeatureId:md((function(t,e){return t.getAttribute("fid")}))},"http://www.opengis.net/ogc/1.1":{FeatureId:md((function(t,e){return t.getAttribute("fid")}))}};function dT(t,e){Rd(uT,t,e)}const gT={"http://www.opengis.net/wfs":{Feature:dT},"http://www.opengis.net/wfs/2.0":{Feature:dT}};function fT(t,e){return bd([],gT,t,e)}function pT(t,e,i){const n=i[i.length-1],r=n.featureType,s=n.featureNS,o=n.gmlVersion,a=hd(s,r);t.appendChild(a),2===o?Dx.prototype.writeFeatureElement(a,e,i):3===o?Bx.prototype.writeFeatureElement(a,e,i):Vx.prototype.writeFeatureElement(a,e,i)}function mT(t,e,i){const n=i[i.length-1].version,r=rT[n],s=hd(r,"Filter"),o=hd(r,"FeatureId");s.appendChild(o),o.setAttribute("fid",e),t.appendChild(s)}function _T(t,e){const i=(t=t||iT)+":";return e.startsWith(i)?e:i+e}function yT(t,e,i){const n=i[i.length-1];Mt(void 0!==e.getId(),26);const r=n.featureType,s=n.featurePrefix,o=n.featureNS,a=_T(s,r);t.setAttribute("typeName",a),t.setAttributeNS(nT,"xmlns:"+s,o);const l=e.getId();void 0!==l&&mT(t,l,i)}function xT(t,e,i){const n=i[i.length-1];Mt(void 0!==e.getId(),27);const r=n.version,s=n.featureType,o=n.featurePrefix,a=n.featureNS,l=_T(o,s),h=e.getGeometryName();t.setAttribute("typeName",l),t.setAttributeNS(nT,"xmlns:"+o,a);const c=e.getId();if(void 0!==c){const s=e.getKeys(),o=[];for(let t=0,i=s.length;t{const r=this.combineBboxAndFilter(n.geometryName,n.bbox,t.srsName,t.filter);Object.assign(i,{geometryName:n.geometryName,filter:r}),jT(e,[n.name],[i])}));return e}combineBboxAndFilter(t,e,i,n){const r=qE(t,e,i);return n?HE(n,r):r}writeTransaction(t,e,i,n){const r=[],s=n.version?n.version:this.version_,o=hd(sT[s],"Transaction");let a;o.setAttribute("service","WFS"),o.setAttribute("version",s),n&&(a=n.gmlOptions?n.gmlOptions:{},n.handle&&o.setAttribute("handle",n.handle)),o.setAttributeNS(ld,"xsi:schemaLocation",aT[s]);const l=function(t,e,i,n){const r=n.featurePrefix?n.featurePrefix:iT;let s;"1.0.0"===i?s=2:"1.1.0"===i?s=3:"2.0.0"===i&&(s=3.2);const o=Object.assign({node:t},{version:i,featureNS:n.featureNS,featureType:n.featureType,featurePrefix:r,gmlVersion:s,hasZ:n.hasZ,srsName:n.srsName},e);return o}(o,a,s,n);return t&&hT("Insert",t,r,l),e&&hT("Update",e,r,l),i&&hT("Delete",i,r,l),n.nativeElements&&hT("Native",n.nativeElements,r,l),o}readProjectionFromDocument(t){for(let e=t.firstChild;e;e=e.nextSibling)if(e.nodeType==Node.ELEMENT_NODE)return this.readProjectionFromNode(e);return null}readProjectionFromNode(t){if(t.firstElementChild&&t.firstElementChild.firstElementChild)for(let e=(t=t.firstElementChild.firstElementChild).firstElementChild;e;e=e.nextElementSibling)if(0!==e.childNodes.length&&(1!==e.childNodes.length||3!==e.firstChild.nodeType)){const t=[{}];return this.gmlFormat_.readGeometryElement(e,t),nn(t.pop().srsName)}return null}};const zT=1,XT=2,VT=3,WT=4,ZT=5,YT=6,KT=7,HT=15,qT=16,$T=17;class JT{constructor(t){this.view_=t,this.pos_=0,this.initialized_=!1,this.isLittleEndian_=!1,this.hasZ_=!1,this.hasM_=!1,this.srid_=null,this.layout_="XY"}readUint8(){return this.view_.getUint8(this.pos_++)}readUint32(t){return this.view_.getUint32((this.pos_+=4)-4,void 0!==t?t:this.isLittleEndian_)}readDouble(t){return this.view_.getFloat64((this.pos_+=8)-8,void 0!==t?t:this.isLittleEndian_)}readPoint(){const t=[];return t.push(this.readDouble()),t.push(this.readDouble()),this.hasZ_&&t.push(this.readDouble()),this.hasM_&&t.push(this.readDouble()),t}readLineString(){const t=this.readUint32(),e=[];for(let i=0;i0,i=this.readUint32(e),n=Math.floor((268435455&i)/1e3),r=Boolean(2147483648&i)||1===n||3===n,s=Boolean(1073741824&i)||2===n||3===n,o=Boolean(536870912&i),a=(268435455&i)%1e3,l=["XY",r?"Z":"",s?"M":""].join(""),h=o?this.readUint32(e):null;if(void 0!==t&&t!==a)throw new Error("Unexpected WKB geometry type "+a);if(this.initialized_){if(this.isLittleEndian_!==e)throw new Error("Inconsistent endian");if(this.layout_!==l)throw new Error("Inconsistent geometry layout");if(h&&this.srid_!==h)throw new Error("Inconsistent coordinate system (SRID)")}else this.isLittleEndian_=e,this.hasZ_=r,this.hasM_=s,this.layout_=l,this.srid_=h,this.initialized_=!0;return a}readWkbPayload(t){switch(t){case zT:return this.readPoint();case XT:return this.readLineString();case VT:case $T:return this.readPolygon();case WT:return this.readMultiPoint();case ZT:return this.readMultiLineString();case YT:case HT:case qT:return this.readMultiPolygon();case KT:return this.readGeometryCollection();default:throw new Error("Unsupported WKB geometry type "+t+" is found")}}readWkbBlock(t){return this.readWkbPayload(this.readWkbHeader(t))}readWkbCollection(t,e){const i=this.readUint32(),n=[];for(let r=0;r({[e]:t[i]}))));for(const t of this.layout_)this.writeDouble(t in i?i[t]:this.nodata_[t])}writeLineString(t,e){this.writeUint32(t.length);for(let i=0;it+e[0]),0),e=new ArrayBuffer(t),i=new DataView(e);let n=0;return this.writeQueue_.forEach((t=>{switch(t[0]){case 1:i.setUint8(n,t[1]);break;case 4:i.setUint32(n,t[1],this.isLittleEndian_);break;case 8:i.setFloat64(n,t[1],this.isLittleEndian_)}n+=t[0]})),e}}function tC(t){return"string"==typeof t?function(t){const e=new Uint8Array(t.length/2);for(let i=0;inew Nt({geometry:t})))}readGeometry(t,e){const i=tC(t);if(!i)return null;const n=new JT(i).readGeometry();return this.viewCache_=i,e=this.getReadOptions(t,e),this.viewCache_=null,y_(n,!1,e)}readProjection(t){const e=this.viewCache_||tC(t);if(!e)return;const i=new JT(e);return i.readWkbHeader(),i.getSrid()&&nn("EPSG:"+i.getSrid())||void 0}writeFeature(t,e){return this.writeGeometry(t.getGeometry(),e)}writeFeatures(t,e){return this.writeGeometry(new jm(t.map((t=>t.getGeometry()))),e)}writeGeometry(t,e){e=this.adaptOptions(e);const i=new QT({layout:this.layout_,littleEndian:this.littleEndian_,ewkb:this.ewkb_,nodata:{Z:this.nodataZ_,M:this.nodataM_}});let n=Number.isInteger(this.srid_)?Number(this.srid_):null;if(!1!==this.srid_&&!Number.isInteger(this.srid_)){const t=e.dataProjection&&nn(e.dataProjection);if(t){const e=t.getCode();e.startsWith("EPSG:")&&(n=Number(e.substring(5)))}}i.writeGeometry(y_(t,!0,e),n);const r=i.getBuffer();return this.hex_?function(t){const e=new Uint8Array(t);return Array.from(e.values()).map((t=>(t<16?"0":"")+Number(t).toString(16).toUpperCase())).join("")}(r):r}};const iC={POINT:lr,LINESTRING:Vm,POLYGON:Ir,MULTIPOINT:Km,MULTILINESTRING:Zm,MULTIPOLYGON:$m},nC="EMPTY",rC="Z",sC="M",oC=0,aC=1,lC=2,hC=3,cC=4,uC=5,dC=6,gC={Point:"POINT",LineString:"LINESTRING",Polygon:"POLYGON",MultiPoint:"MULTIPOINT",MultiLineString:"MULTILINESTRING",MultiPolygon:"MULTIPOLYGON",GeometryCollection:"GEOMETRYCOLLECTION",Circle:"CIRCLE"};class fC{constructor(t){this.wkt=t,this.index_=-1}isAlpha_(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"}isNumeric_(t,e){return e=void 0!==e&&e,t>="0"&&t<="9"||"."==t&&!e}isWhiteSpace_(t){return" "==t||"\t"==t||"\r"==t||"\n"==t}nextChar_(){return this.wkt.charAt(++this.index_)}nextToken(){const t=this.nextChar_(),e=this.index_;let i,n=t;if("("==t)i=lC;else if(","==t)i=uC;else if(")"==t)i=hC;else if(this.isNumeric_(t)||"-"==t)i=cC,n=this.readNumber_();else if(this.isAlpha_(t))i=aC,n=this.readText_();else{if(this.isWhiteSpace_(t))return this.nextToken();if(""!==t)throw new Error("Unexpected character: "+t);i=dC}return{position:e,value:n,type:i}}readNumber_(){let t;const e=this.index_;let i=!1,n=!1;do{"."==t?i=!0:"e"!=t&&"E"!=t||(n=!0),t=this.nextChar_()}while(this.isNumeric_(t,i)||!n&&("e"==t||"E"==t)||n&&("-"==t||"+"==t));return parseFloat(this.wkt.substring(e,this.index_--))}readText_(){let t;const e=this.index_;do{t=this.nextChar_()}while(this.isAlpha_(t));return this.wkt.substring(e,this.index_--).toUpperCase()}}class pC{constructor(t){this.lexer_=t,this.token_={position:0,type:oC},this.layout_="XY"}consume_(){this.token_=this.lexer_.nextToken()}isTokenType(t){return this.token_.type==t}match(t){const e=this.isTokenType(t);return e&&this.consume_(),e}parse(){return this.consume_(),this.parseGeometry_()}parseGeometryLayout_(){let t="XY";const e=this.token_;if(this.isTokenType(aC)){const i=e.value;i===rC?t="XYZ":i===sC?t="XYM":"ZM"===i&&(t="XYZM"),"XY"!==t&&this.consume_()}return t}parseGeometryCollectionText_(){if(this.match(lC)){const t=[];do{t.push(this.parseGeometry_())}while(this.match(uC));if(this.match(hC))return t}throw new Error(this.formatErrorMessage_())}parsePointText_(){if(this.match(lC)){const t=this.parsePoint_();if(this.match(hC))return t}throw new Error(this.formatErrorMessage_())}parseLineStringText_(){if(this.match(lC)){const t=this.parsePointList_();if(this.match(hC))return t}throw new Error(this.formatErrorMessage_())}parsePolygonText_(){if(this.match(lC)){const t=this.parseLineStringTextList_();if(this.match(hC))return t}throw new Error(this.formatErrorMessage_())}parseMultiPointText_(){if(this.match(lC)){let t;if(t=this.token_.type==lC?this.parsePointTextList_():this.parsePointList_(),this.match(hC))return t}throw new Error(this.formatErrorMessage_())}parseMultiLineStringText_(){if(this.match(lC)){const t=this.parseLineStringTextList_();if(this.match(hC))return t}throw new Error(this.formatErrorMessage_())}parseMultiPolygonText_(){if(this.match(lC)){const t=this.parsePolygonTextList_();if(this.match(hC))return t}throw new Error(this.formatErrorMessage_())}parsePoint_(){const t=[],e=this.layout_.length;for(let i=0;i0&&(n+=" "+e)}return 0===i.length?n+" "+nC:n+"("+i+")"}var SC=class extends Iv{constructor(t){super(),t=t||{},this.splitCollection_=void 0!==t.splitCollection&&t.splitCollection}parse_(t){const e=new fC(t);return new pC(e).parse()}readFeatureFromText(t,e){const i=this.readGeometryFromText(t,e),n=new Nt;return n.setGeometry(i),n}readFeaturesFromText(t,e){let i=[];const n=this.readGeometryFromText(t,e);i=this.splitCollection_&&"GeometryCollection"==n.getType()?n.getGeometriesArray():[n];const r=[];for(let t=0,e=i.length;tc*xR||h>u*xR?this.resetExtent_():re(s,n)||this.recenter_()}resetExtent_(){const t=this.getMap(),e=this.ovmap_,i=t.getSize(),n=t.getView().calculateExtentInternal(i),r=e.getView(),s=Math.log(7.5)/Math.LN2;De(n,1/(Math.pow(2,s/2)*vR)),r.fitInternal(Lr(n))}recenter_(){const t=this.getMap(),e=this.ovmap_,i=t.getView();e.getView().setCenterInternal(i.getCenterInternal())}updateBox_(){const t=this.getMap(),e=this.ovmap_;if(!t.isRendered()||!e.isRendered())return;const i=t.getSize(),n=t.getView(),r=e.getView(),s=this.rotateWithView_?0:-n.getRotation(),o=this.boxOverlay_,a=this.boxOverlay_.getElement(),l=n.getCenterInternal(),h=n.getResolution(),c=r.getResolution(),u=i[0]*h/c,d=i[1]*h/c;if(o.setPosition(l),a){a.style.width=u+"px",a.style.height=d+"px";const t="rotate("+s+"rad)";a.style.transform=t}}updateBoxAfterOvmapIsRendered_(){this.ovmapPostrenderKey_||(this.ovmapPostrenderKey_=k(this.ovmap_,$o,(function(t){delete this.ovmapPostrenderKey_,this.updateBox_()}),this))}handleClick_(t){t.preventDefault(),this.handleToggle_()}handleToggle_(){this.element.classList.toggle(go),this.collapsed_?wt(this.collapseLabel_,this.label_):wt(this.label_,this.collapseLabel_),this.collapsed_=!this.collapsed_;const t=this.ovmap_;if(!this.collapsed_){if(t.isRendered())return this.viewExtent_=void 0,void t.render();t.updateSize(),this.resetExtent_(),this.updateBoxAfterOvmapIsRendered_()}}getCollapsible(){return this.collapsible_}setCollapsible(t){this.collapsible_!==t&&(this.collapsible_=t,this.element.classList.toggle("ol-uncollapsible"),!t&&this.collapsed_&&this.handleToggle_())}setCollapsed(t){this.collapsible_&&this.collapsed_!==t&&this.handleToggle_()}getCollapsed(){return this.collapsed_}getRotateWithView(){return this.rotateWithView_}setRotateWithView(t){this.rotateWithView_!==t&&(this.rotateWithView_=t,0!==this.getMap().getView().getRotation()&&(this.rotateWithView_?this.handleRotationChanged_():this.ovmap_.getView().setRotation(0),this.viewExtent_=void 0,this.validateExtent_(),this.updateBox_()))}getOverviewMap(){return this.ovmap_}render(t){this.validateExtent_(),this.updateBox_()}};const wR="units",ER=[1,2,5],TR=25.4/.28;var CR=class extends ca{constructor(t){t=t||{};const e=document.createElement("div");e.style.pointerEvents="none",super({element:e,render:t.render,target:t.target}),this.on,this.once,this.un;const i=void 0!==t.className?t.className:t.bar?"ol-scale-bar":"ol-scale-line";this.innerElement_=document.createElement("div"),this.innerElement_.className=i+"-inner",this.element.className=i+" "+ho,this.element.appendChild(this.innerElement_),this.viewState_=null,this.minWidth_=void 0!==t.minWidth?t.minWidth:64,this.maxWidth_=t.maxWidth,this.renderedVisible_=!1,this.renderedWidth_=void 0,this.renderedHTML_="",this.addChangeListener(wR,this.handleUnitsChanged_),this.setUnits(t.units||"metric"),this.scaleBar_=t.bar||!1,this.scaleBarSteps_=t.steps||4,this.scaleBarText_=t.text||!1,this.dpi_=t.dpi||void 0}getUnits(){return this.get(wR)}handleUnitsChanged_(){this.updateElement_()}setUnits(t){this.set(wR,t)}setDpi(t){this.dpi_=t}updateElement_(){const t=this.viewState_;if(!t)return void(this.renderedVisible_&&(this.element.style.display="none",this.renderedVisible_=!1));const e=t.center,i=t.projection,n=this.getUnits(),r="degrees"==n?"degrees":"m";let s=rn(i,t.resolution,e,r);const o=this.minWidth_*(this.dpi_||TR)/TR,a=void 0!==this.maxWidth_?this.maxWidth_*(this.dpi_||TR)/TR:void 0;let l=o*s,h="";if("degrees"==n){const t=Xe.degrees;l*=t,l=a){c=g,u=f,d=p;break}if(u>=o)break;g=c,f=u,p=d,++m}const _=this.scaleBar_?this.createScaleBar(u,c,h):c.toFixed(d<0?-d:0)+" "+h;this.renderedHTML_!=_&&(this.innerElement_.innerHTML=_,this.renderedHTML_=_),this.renderedWidth_!=u&&(this.innerElement_.style.width=u+"px",this.renderedWidth_=u),this.renderedVisible_||(this.element.style.display="",this.renderedVisible_=!0)}createScaleBar(t,e,i){const n=this.getScaleForResolution(),r=n<1?Math.round(1/n).toLocaleString()+" : 1":"1 : "+Math.round(n).toLocaleString(),s=this.scaleBarSteps_,o=t/s,a=[this.createMarker("absolute")];for(let n=0;n
`+this.createMarker("relative")+(n%2==0||2===s?this.createStepText(n,t,!1,e,i):"")+"")}a.push(this.createStepText(s,t,!0,e,i));return(this.scaleBarText_?`
`+r+"
":"")+a.join("")}createMarker(t){return`
`}createStepText(t,e,i,n,r){const s=(0===t?0:Math.round(n/this.scaleBarSteps_*t*100)/100)+(0===t?"":" "+r);return`
`+s+"
"}getScaleForResolution(){return rn(this.viewState_.projection,this.viewState_.resolution,this.viewState_.center,"m")*(1e3/25.4)*(this.dpi_||TR)}render(t){const e=t.frameState;this.viewState_=e?e.viewState:null,this.updateElement_()}};const RR=0,bR=1;var PR=class extends ca{constructor(t){super({target:(t=t||{}).target,element:document.createElement("div"),render:t.render}),this.dragListenerKeys_=[],this.currentResolution_=void 0,this.direction_=RR,this.dragging_,this.heightLimit_=0,this.widthLimit_=0,this.startX_,this.startY_,this.thumbSize_=null,this.sliderInitialized_=!1,this.duration_=void 0!==t.duration?t.duration:200;const e=void 0!==t.className?t.className:"ol-zoomslider",i=document.createElement("button");i.setAttribute("type","button"),i.className=e+"-thumb "+ho;const r=this.element;r.className=e+" "+ho+" "+uo,r.appendChild(i),r.addEventListener(Yo,this.handleDraggerStart_.bind(this),!1),r.addEventListener(Zo,this.handleDraggerDrag_.bind(this),!1),r.addEventListener(Ko,this.handleDraggerEnd_.bind(this),!1),r.addEventListener(R,this.handleContainerClick_.bind(this),!1),i.addEventListener(R,n,!1)}setMap(t){super.setMap(t),t&&t.render()}initSlider_(){const t=this.element;let e=t.offsetWidth,i=t.offsetHeight;if(0===e&&0===i)return this.sliderInitialized_=!1;const n=getComputedStyle(t);e-=parseFloat(n.paddingRight)+parseFloat(n.paddingLeft),i-=parseFloat(n.paddingTop)+parseFloat(n.paddingBottom);const r=t.firstElementChild,s=getComputedStyle(r),o=r.offsetWidth+parseFloat(s.marginRight)+parseFloat(s.marginLeft),a=r.offsetHeight+parseFloat(s.marginTop)+parseFloat(s.marginBottom);return this.thumbSize_=[o,a],e>i?(this.direction_=bR,this.widthLimit_=e-o):(this.direction_=RR,this.heightLimit_=i-a),this.sliderInitialized_=!0}handleContainerClick_(t){const e=this.getMap().getView(),i=this.getRelativePosition_(t.offsetX-this.thumbSize_[0]/2,t.offsetY-this.thumbSize_[1]/2),n=this.getResolutionForPosition_(i),r=e.getConstrainedZoom(e.getZoomForResolution(n));e.animateInternal({zoom:r,duration:this.duration_,easing:rt})}handleDraggerStart_(t){if(!this.dragging_&&t.target===this.element.firstElementChild){const e=this.element.firstElementChild;if(this.getMap().getView().beginInteraction(),this.startX_=t.clientX-parseFloat(e.style.left),this.startY_=t.clientY-parseFloat(e.style.top),this.dragging_=!0,0===this.dragListenerKeys_.length){const t=this.handleDraggerDrag_,e=this.handleDraggerEnd_,i=this.getMap().getOwnerDocument();this.dragListenerKeys_.push(D(i,Zo,t,this),D(i,Ko,e,this))}}}handleDraggerDrag_(t){if(this.dragging_){const e=t.clientX-this.startX_,i=t.clientY-this.startY_,n=this.getRelativePosition_(e,i);this.currentResolution_=this.getResolutionForPosition_(n),this.getMap().getView().setResolution(this.currentResolution_)}}handleDraggerEnd_(t){if(this.dragging_){this.getMap().getView().endInteraction(),this.dragging_=!1,this.startX_=void 0,this.startY_=void 0,this.dragListenerKeys_.forEach(G),this.dragListenerKeys_.length=0}}setThumbPosition_(t){const e=this.getPositionForResolution_(t),i=this.element.firstElementChild;this.direction_==bR?i.style.left=this.widthLimit_*e+"px":i.style.top=this.heightLimit_*e+"px"}getRelativePosition_(t,e){let i;return i=this.direction_===bR?t/this.widthLimit_:e/this.heightLimit_,gi(i,0,1)}getResolutionForPosition_(t){return this.getMap().getView().getResolutionForValueFunction()(1-t)}getPositionForResolution_(t){return gi(1-this.getMap().getView().getValueForResolutionFunction()(t),0,1)}render(t){if(!t.frameState)return;if(!this.sliderInitialized_&&!this.initSlider_())return;const e=t.frameState.viewState.resolution;this.currentResolution_=e,this.setThumbPosition_(e)}};var IR=class extends ca{constructor(t){t=t||{},super({element:document.createElement("div"),target:t.target}),this.extent=t.extent?t.extent:null;const e=void 0!==t.className?t.className:"ol-zoom-extent",i=void 0!==t.label?t.label:"E",n=void 0!==t.tipLabel?t.tipLabel:"Fit to extent",r=document.createElement("button");r.setAttribute("type","button"),r.title=n,r.appendChild("string"==typeof i?document.createTextNode(i):i),r.addEventListener(R,this.handleClick_.bind(this),!1);const s=e+" "+ho+" "+uo,o=this.element;o.className=s,o.appendChild(r)}handleClick_(t){t.preventDefault(),this.handleZoomToExtent()}handleZoomToExtent(){const t=this.getMap().getView(),e=this.extent?this.extent:t.getProjection().getExtent();t.fitInternal(Lr(e))}},FR={};return FR.AssertionError=i,FR.Collection=$,FR.Collection.CollectionEvent=q,FR.DataTile=Lt,FR.DataTile.asArrayLike=bt,FR.DataTile.asImageLike=Rt,FR.DataTile.toArray=It,FR.Disposable=o,FR.Feature=Nt,FR.Feature.createStyleFunction=Ot,FR.Geolocation=Zr,FR.Geolocation.GeolocationError=Wr,FR.Image=ts,FR.Image.listenImage=Qr,FR.ImageBase=Yr,FR.ImageCanvas=es,FR.ImageTile=is,FR.Kinetic=ns,FR.Map=hl,FR.MapBrowserEvent=Vo,FR.MapBrowserEventHandler=qo,FR.MapEvent=Xo,FR.Object=Z,FR.Object.ObjectEvent=W,FR.Observable=U,FR.Observable.unByKey=B,FR.Overlay=pl,FR.Tile=at,FR.TileCache=Tl,FR.TileQueue=la,FR.TileQueue.getTilePriority=ha,FR.TileRange=bl,FR.TileRange.createOrUpdate=Rl,FR.VectorRenderTile=Il,FR.VectorTile=Fl,FR.View=eo,FR.View.createCenterConstraint=qs,FR.View.createResolutionConstraint=$s,FR.View.createRotationConstraint=Js,FR.View.isNoopAnimation=Qs,FR.array={},FR.array.ascending=l,FR.array.binarySearch=a,FR.array.descending=h,FR.array.equals=g,FR.array.extend=d,FR.array.isSorted=f,FR.array.linearFindNearest=c,FR.array.remove=function(t,e){const i=t.indexOf(e),n=i>-1;return n&&t.splice(i,1),n},FR.array.reverseSubArray=u,FR.array.stableSort=function(t,e){const i=t.length,n=Array(t.length);let r;for(r=0;rZi.info||console.log(...t)},FR.console.setLevel=function(t){Yi=Zi[t]},FR.console.warn=Ki,FR.control={},FR.control.Attribution=ua,FR.control.Control=ca,FR.control.FullScreen=pR,FR.control.MousePosition=yR,FR.control.OverviewMap=SR,FR.control.Rotate=da,FR.control.ScaleLine=CR,FR.control.Zoom=ga,FR.control.ZoomSlider=PR,FR.control.ZoomToExtent=IR,FR.control.defaults={},FR.control.defaults.defaults=fa,FR.coordinate={},FR.coordinate.add=bi,FR.coordinate.closestOnCircle=Pi,FR.coordinate.closestOnSegment=Ii,FR.coordinate.createStringXY=function(t){return function(e){return Gi(e,t)}},FR.coordinate.degreesToStringHDMS=Fi,FR.coordinate.distance=Di,FR.coordinate.equals=Mi,FR.coordinate.format=Li,FR.coordinate.getWorldsAway=Bi,FR.coordinate.rotate=Ai,FR.coordinate.scale=Oi,FR.coordinate.squaredDistance=Ni,FR.coordinate.squaredDistanceToSegment=ki,FR.coordinate.toStringHDMS=function(t,e){return t?Fi("NS",t[1],e)+" "+Fi("EW",t[0],e):""},FR.coordinate.toStringXY=Gi,FR.coordinate.wrapX=ji,FR.css={},FR.css.CLASS_COLLAPSED=go,FR.css.CLASS_CONTROL=uo,FR.css.CLASS_HIDDEN=ao,FR.css.CLASS_SELECTABLE=lo,FR.css.CLASS_UNSELECTABLE=ho,FR.css.CLASS_UNSUPPORTED=co,FR.css.getFontParameters=mo,FR.dom={},FR.dom.createCanvasContext2D=yt,FR.dom.outerHeight=St,FR.dom.outerWidth=vt,FR.dom.releaseCanvas=xt,FR.dom.removeChildren=Tt,FR.dom.removeNode=Et,FR.dom.replaceChildren=Ct,FR.dom.replaceNode=wt,FR.easing={},FR.easing.easeIn=nt,FR.easing.easeOut=rt,FR.easing.inAndOut=st,FR.easing.linear=ot,FR.easing.upAndDown=function(t){return t<.5?st(2*t):1-st(2*(t-.5))},FR.events={},FR.events.Event=r,FR.events.Event.preventDefault=function(t){t.preventDefault()},FR.events.Event.stopPropagation=n,FR.events.SnapEvent={},FR.events.SnapEvent.SnapEvent=Hy,FR.events.Target=w,FR.events.condition={},FR.events.condition.all=wa,FR.events.condition.altKeyOnly=Ea,FR.events.condition.altShiftKeysOnly=Ta,FR.events.condition.always=ba,FR.events.condition.click=function(t){return t.type==Wo.CLICK},FR.events.condition.doubleClick=function(t){return t.type==Wo.DBLCLICK},FR.events.condition.focus=Ca,FR.events.condition.focusWithTabindex=Ra,FR.events.condition.mouseActionButton=Pa,FR.events.condition.mouseOnly=Na,FR.events.condition.never=Ia,FR.events.condition.noModifierKeys=La,FR.events.condition.penOnly=function(t){const e=t.originalEvent;return Mt(void 0!==e,56),"pen"===e.pointerType},FR.events.condition.platformModifierKey=Ma,FR.events.condition.platformModifierKeyOnly=function(t){const e=t.originalEvent;return!e.altKey&&(gt?e.metaKey:e.ctrlKey)&&!e.shiftKey},FR.events.condition.pointerMove=function(t){return"pointermove"==t.type},FR.events.condition.primaryAction=Da,FR.events.condition.shiftKeyOnly=Aa,FR.events.condition.singleClick=Fa,FR.events.condition.targetNotEditable=Oa,FR.events.condition.touchOnly=function(t){const e=t.originalEvent;return Mt(void 0!==e,56),"touch"===e.pointerType},FR.events.listen=D,FR.events.listenOnce=k,FR.events.unlistenByKey=G,FR.extent={},FR.extent.applyTransform=Ge,FR.extent.approximatelyEquals=ge,FR.extent.boundingExtent=Qt,FR.extent.buffer=te,FR.extent.clone=ee,FR.extent.closestSquaredDistanceXY=ie,FR.extent.containsCoordinate=ne,FR.extent.containsExtent=re,FR.extent.containsXY=se,FR.extent.coordinateRelationship=oe,FR.extent.createEmpty=ae,FR.extent.createOrUpdate=le,FR.extent.createOrUpdateEmpty=he,FR.extent.createOrUpdateFromCoordinate=ce,FR.extent.createOrUpdateFromCoordinates=function(t,e){return me(he(e),t)},FR.extent.createOrUpdateFromFlatCoordinates=ue,FR.extent.createOrUpdateFromRings=function(t,e){return ye(he(e),t)},FR.extent.equals=de,FR.extent.extend=fe,FR.extent.extendCoordinate=pe,FR.extent.extendCoordinates=me,FR.extent.extendFlatCoordinates=_e,FR.extent.extendRings=ye,FR.extent.extendXY=xe,FR.extent.forEachCorner=ve,FR.extent.getArea=Se,FR.extent.getBottomLeft=we,FR.extent.getBottomRight=Ee,FR.extent.getCenter=Te,FR.extent.getCorner=Ce,FR.extent.getEnlargedArea=function(t,e){const i=Math.min(t[0],e[0]),n=Math.min(t[1],e[1]);return(Math.max(t[2],e[2])-i)*(Math.max(t[3],e[3])-n)},FR.extent.getForViewAndSize=Re,FR.extent.getHeight=Pe,FR.extent.getIntersection=Ie,FR.extent.getIntersectionArea=function(t,e){return Se(Ie(t,e))},FR.extent.getMargin=function(t){return Me(t)+Pe(t)},FR.extent.getRotatedViewport=be,FR.extent.getSize=function(t){return[t[2]-t[0],t[3]-t[1]]},FR.extent.getTopLeft=Fe,FR.extent.getTopRight=Le,FR.extent.getWidth=Me,FR.extent.intersects=Ae,FR.extent.intersectsSegment=ke,FR.extent.isEmpty=Oe,FR.extent.returnOrUpdate=Ne,FR.extent.scaleFromCenter=De,FR.extent.wrapAndSliceX=Be,FR.extent.wrapX=je,FR.featureloader={},FR.featureloader.loadFeaturesXhr=Ol,FR.featureloader.setWithCredentials=function(t){Al=t},FR.featureloader.xhr=Nl,FR.format={},FR.format.EsriJSON=gx,FR.format.Feature=__,FR.format.Feature.transformExtentWithOptions=x_,FR.format.Feature.transformGeometryWithOptions=y_,FR.format.GML=zx,FR.format.GML2=Dx,FR.format.GML3=Bx,FR.format.GML32=Vx,FR.format.GMLBase=yx,FR.format.GMLBase.GMLNS=px,FR.format.GPX=Tv,FR.format.GeoJSON=bv,FR.format.IGC=Ov,FR.format.IIIFInfo=Gc,FR.format.JSONFeature=ox,FR.format.KML=Nw,FR.format.KML.getDefaultFillStyle=function(){return $v},FR.format.KML.getDefaultImageStyle=function(){return Qv},FR.format.KML.getDefaultStrokeStyle=function(){return eS},FR.format.KML.getDefaultStyle=function(){return nS},FR.format.KML.getDefaultStyleArray=function(){return sS},FR.format.KML.getDefaultTextStyle=function(){return iS},FR.format.KML.readFlatCoordinates=cS,FR.format.MVT=Y_,FR.format.OSMXML=Uw,FR.format.OWS=oE,FR.format.Polyline=mE,FR.format.Polyline.decodeDeltas=lE,FR.format.Polyline.decodeFloats=cE,FR.format.Polyline.decodeSignedIntegers=dE,FR.format.Polyline.decodeUnsignedIntegers=fE,FR.format.Polyline.encodeDeltas=aE,FR.format.Polyline.encodeFloats=hE,FR.format.Polyline.encodeSignedIntegers=uE,FR.format.Polyline.encodeUnsignedInteger=pE,FR.format.Polyline.encodeUnsignedIntegers=gE,FR.format.TextFeature=Iv,FR.format.TopoJSON=EE,FR.format.WFS=UT,FR.format.WFS.writeFilter=function(t,e){const i=hd(BT(e=e||"1.1.0"),"Filter"),n={node:i};return Object.assign(n,{version:e,filter:t}),TT(i,t,[n]),i},FR.format.WKB=eC,FR.format.WKT=SC,FR.format.WMSCapabilities=WC,FR.format.WMSGetFeatureInfo=ZC,FR.format.WMTSCapabilities=lR,FR.format.XML=zw,FR.format.XMLFeature=fx,FR.format.filter={},FR.format.filter.And=RE,FR.format.filter.Bbox=bE,FR.format.filter.Comparison=ME,FR.format.filter.ComparisonBinary=OE,FR.format.filter.Contains=IE,FR.format.filter.DWithin=FE,FR.format.filter.Disjoint=LE,FR.format.filter.During=AE,FR.format.filter.EqualTo=NE,FR.format.filter.Filter=TE,FR.format.filter.GreaterThan=DE,FR.format.filter.GreaterThanOrEqualTo=kE,FR.format.filter.Intersects=GE,FR.format.filter.IsBetween=jE,FR.format.filter.IsLike=BE,FR.format.filter.IsNull=UE,FR.format.filter.LessThan=zE,FR.format.filter.LessThanOrEqualTo=XE,FR.format.filter.LogicalNary=CE,FR.format.filter.Not=VE,FR.format.filter.NotEqualTo=WE,FR.format.filter.Or=ZE,FR.format.filter.ResourceId=YE,FR.format.filter.Spatial=PE,FR.format.filter.Within=KE,FR.format.filter.and=HE,FR.format.filter.bbox=qE,FR.format.filter.between=function(t,e,i){return new jE(t,e,i)},FR.format.filter.contains=function(t,e,i){return new IE(t,e,i)},FR.format.filter.disjoint=function(t,e,i){return new LE(t,e,i)},FR.format.filter.during=function(t,e,i){return new AE(t,e,i)},FR.format.filter.dwithin=function(t,e,i,n,r){return new FE(t,e,i,n,r)},FR.format.filter.equalTo=function(t,e,i){return new NE(t,e,i)},FR.format.filter.greaterThan=function(t,e){return new DE(t,e)},FR.format.filter.greaterThanOrEqualTo=function(t,e){return new kE(t,e)},FR.format.filter.intersects=function(t,e,i){return new GE(t,e,i)},FR.format.filter.isNull=function(t){return new UE(t)},FR.format.filter.lessThan=function(t,e){return new zE(t,e)},FR.format.filter.lessThanOrEqualTo=function(t,e){return new XE(t,e)},FR.format.filter.like=function(t,e,i,n,r,s){return new BE(t,e,i,n,r,s)},FR.format.filter.not=function(t){return new VE(t)},FR.format.filter.notEqualTo=function(t,e,i){return new WE(t,e,i)},FR.format.filter.or=function(t){const e=[null].concat(Array.prototype.slice.call(arguments));return new(Function.prototype.bind.apply(ZE,e))},FR.format.filter.resourceId=function(t){return new YE(t)},FR.format.filter.within=function(t,e,i){return new KE(t,e,i)},FR.format.xlink={},FR.format.xlink.readHref=Vw,FR.format.xsd={},FR.format.xsd.readBoolean=xx,FR.format.xsd.readBooleanString=vx,FR.format.xsd.readDateTime=Sx,FR.format.xsd.readDecimal=wx,FR.format.xsd.readDecimalString=Ex,FR.format.xsd.readNonNegativeIntegerString=Cx,FR.format.xsd.readPositiveInteger=Tx,FR.format.xsd.readString=Rx,FR.format.xsd.writeBooleanTextNode=bx,FR.format.xsd.writeCDATASection=Px,FR.format.xsd.writeDateTimeTextNode=Ix,FR.format.xsd.writeDecimalTextNode=Fx,FR.format.xsd.writeNonNegativeIntegerTextNode=Lx,FR.format.xsd.writeStringTextNode=Mx,FR.functions={},FR.functions.FALSE=m,FR.functions.TRUE=p,FR.functions.VOID=_,FR.functions.memoizeOne=y,FR.functions.toPromise=x,FR.geom={},FR.geom.Circle=Dm,FR.geom.Geometry=Ln,FR.geom.GeometryCollection=jm,FR.geom.LineString=Vm,FR.geom.LinearRing=or,FR.geom.MultiLineString=Zm,FR.geom.MultiPoint=Km,FR.geom.MultiPolygon=$m,FR.geom.Point=lr,FR.geom.Polygon=Ir,FR.geom.Polygon.circular=Fr,FR.geom.Polygon.fromCircle=Mr,FR.geom.Polygon.fromExtent=Lr,FR.geom.Polygon.makeRegular=Ar,FR.geom.SimpleGeometry=On,FR.geom.SimpleGeometry.getStrideForLayout=Mn,FR.geom.SimpleGeometry.transformGeom2D=An,FR.geom.flat={},FR.geom.flat.area={},FR.geom.flat.area.linearRing=ir,FR.geom.flat.area.linearRings=nr,FR.geom.flat.area.linearRingss=rr,FR.geom.flat.center={},FR.geom.flat.center.linearRingss=Hm,FR.geom.flat.closest={},FR.geom.flat.closest.arrayMaxSquaredDelta=kn,FR.geom.flat.closest.assignClosestArrayPoint=Bn,FR.geom.flat.closest.assignClosestMultiArrayPoint=Un,FR.geom.flat.closest.assignClosestPoint=jn,FR.geom.flat.closest.maxSquaredDelta=Dn,FR.geom.flat.closest.multiArrayMaxSquaredDelta=Gn,FR.geom.flat.contains={},FR.geom.flat.contains.linearRingContainsExtent=hr,FR.geom.flat.contains.linearRingContainsXY=cr,FR.geom.flat.contains.linearRingsContainsXY=ur,FR.geom.flat.contains.linearRingssContainsXY=dr,FR.geom.flat.deflate={},FR.geom.flat.deflate.deflateCoordinate=zn,FR.geom.flat.deflate.deflateCoordinates=Xn,FR.geom.flat.deflate.deflateCoordinatesArray=Vn,FR.geom.flat.deflate.deflateMultiCoordinatesArray=Wn,FR.geom.flat.flip={},FR.geom.flat.flip.flipXY=rx,FR.geom.flat.geodesic={},FR.geom.flat.geodesic.greatCircleArc=function(t,e,i,n,r,s){const o=nn("EPSG:4326"),a=Math.cos(yi(e)),l=Math.sin(yi(e)),h=Math.cos(yi(n)),c=Math.sin(yi(n)),u=Math.cos(yi(i-t)),d=Math.sin(yi(i-t)),g=l*c+a*h*u;return o_((function(e){if(1<=g)return[i,n];const r=e*Math.acos(g),s=Math.cos(r),o=Math.sin(r),f=d*h,p=a*c-l*h*u,m=Math.atan2(f,p),_=Math.asin(l*s+a*o*Math.cos(m));return[_i(yi(t)+Math.atan2(Math.sin(m)*o*a,s-l*Math.sin(_))),_i(_)]}),dn(o,r),s)},FR.geom.flat.geodesic.meridian=a_,FR.geom.flat.geodesic.parallel=l_,FR.geom.flat.inflate={},FR.geom.flat.inflate.inflateCoordinates=Qn,FR.geom.flat.inflate.inflateCoordinatesArray=tr,FR.geom.flat.inflate.inflateMultiCoordinatesArray=er,FR.geom.flat.interiorpoint={},FR.geom.flat.interiorpoint.getInteriorPointOfArray=gr,FR.geom.flat.interiorpoint.getInteriorPointsOfMultiArray=fr,FR.geom.flat.interpolate={},FR.geom.flat.interpolate.interpolatePoint=Bm,FR.geom.flat.interpolate.lineStringCoordinateAtM=Um,FR.geom.flat.interpolate.lineStringsCoordinateAtM=zm,FR.geom.flat.intersectsextent={},FR.geom.flat.intersectsextent.intersectsLineString=mr,FR.geom.flat.intersectsextent.intersectsLineStringArray=_r,FR.geom.flat.intersectsextent.intersectsLinearRing=yr,FR.geom.flat.intersectsextent.intersectsLinearRingArray=xr,FR.geom.flat.intersectsextent.intersectsLinearRingMultiArray=vr,FR.geom.flat.length={},FR.geom.flat.length.lineStringLength=dm,FR.geom.flat.length.linearRingLength=function(t,e,i,n){let r=dm(t,e,i,n);const s=t[i-n]-t[e],o=t[i-n+1]-t[e+1];return r+=Math.sqrt(s*s+o*o),r},FR.geom.flat.orient={},FR.geom.flat.orient.inflateEnds=br,FR.geom.flat.orient.linearRingIsClockwise=wr,FR.geom.flat.orient.linearRingsAreOriented=Er,FR.geom.flat.orient.linearRingssAreOriented=Tr,FR.geom.flat.orient.orientLinearRings=Cr,FR.geom.flat.orient.orientLinearRingsArray=Rr,FR.geom.flat.reverse={},FR.geom.flat.reverse.coordinates=Sr,FR.geom.flat.segments={},FR.geom.flat.segments.forEach=pr,FR.geom.flat.simplify={},FR.geom.flat.simplify.douglasPeucker=Zn,FR.geom.flat.simplify.douglasPeuckerArray=Yn,FR.geom.flat.simplify.douglasPeuckerMultiArray=function(t,e,i,n,r,s,o,a){for(let l=0,h=i.length;l3&&!!ir(t,e,i,n)},FR.geom.flat.transform={},FR.geom.flat.transform.rotate=bn,FR.geom.flat.transform.scale=Pn,FR.geom.flat.transform.transform2D=Rn,FR.geom.flat.transform.translate=In,FR.has={},FR.has.DEVICE_PIXEL_RATIO=ft,FR.has.FIREFOX=ht,FR.has.IMAGE_DECODE=mt,FR.has.MAC=gt,FR.has.PASSIVE_EVENT_LISTENERS=_t,FR.has.SAFARI=ct,FR.has.SAFARI_BUG_237906=ut,FR.has.WEBKIT=dt,FR.has.WORKER_OFFSCREEN_CANVAS=pt,FR.interaction={},FR.interaction.DblClickDragZoom=iy,FR.interaction.DoubleClickZoom=xa,FR.interaction.DragAndDrop=sy,FR.interaction.DragAndDrop.DragAndDropEvent=ry,FR.interaction.DragBox=Wa,FR.interaction.DragBox.DragBoxEvent=Va,FR.interaction.DragPan=ka,FR.interaction.DragRotate=Ga,FR.interaction.DragRotateAndZoom=oy,FR.interaction.DragZoom=Za,FR.interaction.Draw=Sy,FR.interaction.Draw.DrawEvent=cy,FR.interaction.Draw.createBox=function(){return function(t,e,i){const n=Qt([t[0],t[t.length-1]].map((function(t){return xn(t,i)}))),r=[[we(n),Ee(n),Le(n),Fe(n),we(n)]];e?e.setCoordinates(r):e=new Ir(r);const s=_n();return s&&e.transform(i,s),e}},FR.interaction.Draw.createRegularPolygon=function(t,e){return function(i,n,r){const s=xn(i[0],r),o=xn(i[i.length-1],r),a=Math.sqrt(Ni(s,o));n=n||Mr(new Dm(s),t);let l=e;if(!e&&0!==e){const t=o[0]-s[0],e=o[1]-s[1];l=Math.atan2(e,t)}Ar(n,s,a,l);const h=_n();return h&&n.transform(r,h),n}},FR.interaction.Extent=Py,FR.interaction.Extent.ExtentEvent=Ey,FR.interaction.Interaction=ya,FR.interaction.Interaction.pan=ma,FR.interaction.Interaction.zoomByDelta=_a,FR.interaction.KeyboardPan=$a,FR.interaction.KeyboardZoom=Ja,FR.interaction.Link=My,FR.interaction.Modify=zy,FR.interaction.Modify.ModifyEvent=ky,FR.interaction.MouseWheelZoom=Qa,FR.interaction.PinchRotate=tl,FR.interaction.PinchZoom=el,FR.interaction.Pointer=Sa,FR.interaction.Pointer.centroid=va,FR.interaction.Select=Yy,FR.interaction.Select.SelectEvent=Vy,FR.interaction.Snap=Jy,FR.interaction.Translate=nx,FR.interaction.Translate.TranslateEvent=ix,FR.interaction.defaults={},FR.interaction.defaults.defaults=il,FR.layer={},FR.layer.Base=bs,FR.layer.BaseImage=fu,FR.layer.BaseTile=Eu,FR.layer.BaseVector=Df,FR.layer.Graticule=u_,FR.layer.Group=zo,FR.layer.Group.GroupEvent=jo,FR.layer.Heatmap=m_,FR.layer.Image=vu,FR.layer.Layer=no,FR.layer.Layer.inView=io,FR.layer.MapboxVector=q_,FR.layer.Tile=Cu,FR.layer.Vector=s_,FR.layer.VectorImage=$_,FR.layer.VectorTile=K_,FR.layer.WebGLPoints=J_,FR.layer.WebGLTile=ey,FR.loadingstrategy={},FR.loadingstrategy.all=Dl,FR.loadingstrategy.bbox=function(t,e){return[t]},FR.loadingstrategy.tile=function(t){return function(e,i,n){const r=t.getZForResolution(En(i,n)),s=t.getTileRangeForExtentAndZ(Sn(e,n),r),o=[],a=[r,0,0];for(a[1]=s.minX;a[1]<=s.maxX;++a[1])for(a[2]=s.minY;a[2]<=s.maxY;++a[2])o.push(vn(t.getTileCoordExtent(a),n));return o}},FR.math={},FR.math.ceil=Ti,FR.math.clamp=gi,FR.math.floor=Ei,FR.math.lerp=vi,FR.math.modulo=xi,FR.math.round=wi,FR.math.solveLinearSystem=mi,FR.math.squaredDistance=pi,FR.math.squaredSegmentDistance=fi,FR.math.toDegrees=_i,FR.math.toFixed=Si,FR.math.toRadians=yi,FR.net={},FR.net.ClientError=jl,FR.net.ResponseError=Gl,FR.net.getJSON=Bl,FR.net.jsonp=kl,FR.net.overrideXHR=function(t){"undefined"!=typeof XMLHttpRequest&&(Ml=XMLHttpRequest),global.XMLHttpRequest=t},FR.net.resolveUrl=Ul,FR.net.restoreXHR=function(){global.XMLHttpRequest=Ml},FR.obj={},FR.obj.clear=v,FR.obj.isEmpty=S,FR.proj={},FR.proj.Projection=Ve,FR.proj.Units={},FR.proj.Units.METERS_PER_UNIT=Xe,FR.proj.Units.fromCode=ze,FR.proj.addCommon=Cn,FR.proj.addCoordinateTransforms=hn,FR.proj.addEquivalentProjections=sn,FR.proj.addEquivalentTransforms=on,FR.proj.addProjection=tn,FR.proj.addProjections=en,FR.proj.clearAllProjections=function(){oi(),ci()},FR.proj.clearUserProjection=function(){pn=null},FR.proj.cloneTransform=Ji,FR.proj.createProjection=an,FR.proj.createSafeCoordinateTransform=Tn,FR.proj.createTransformFromCoordinateTransform=ln,FR.proj.disableCoordinateWarning=$i,FR.proj.epsg3857={},FR.proj.epsg3857.EXTENT=Ye,FR.proj.epsg3857.HALF_SIZE=Ze,FR.proj.epsg3857.MAX_SAFE_Y=He,FR.proj.epsg3857.PROJECTIONS=$e,FR.proj.epsg3857.RADIUS=We,FR.proj.epsg3857.WORLD_EXTENT=Ke,FR.proj.epsg3857.fromEPSG4326=Je,FR.proj.epsg3857.toEPSG4326=Qe,FR.proj.epsg4326={},FR.proj.epsg4326.EXTENT=ei,FR.proj.epsg4326.METERS_PER_UNIT=ii,FR.proj.epsg4326.PROJECTIONS=ri,FR.proj.epsg4326.RADIUS=ti,FR.proj.equivalent=cn,FR.proj.fromLonLat=function(t,e){return $i(),gn(t,"EPSG:4326",void 0!==e?e:"EPSG:3857")},FR.proj.fromUserCoordinate=xn,FR.proj.fromUserExtent=Sn,FR.proj.fromUserResolution=En,FR.proj.get=nn,FR.proj.getPointResolution=rn,FR.proj.getTransform=dn,FR.proj.getTransformFromProjections=un,FR.proj.getUserProjection=_n,FR.proj.identityTransform=Qi,FR.proj.proj4={},FR.proj.proj4.epsgLookupMapTiler=function(t){return async function(e){const i=await fetch(`https://api.maptiler.com/coordinates/search/code:${e}.json?transformations=true&exports=true&key=${t}`);if(!i.ok)throw new Error(`Unexpected response from maptiler.com: ${i.status}`);return i.json().then((t=>{const i=t.results;if(i?.length>0){const t=i.filter((t=>"EPSG"===t.id?.authority&&t.id?.code===e))[0];if(t){const e=t.transformations;if(e?.length>0){const i=t.default_transformation;if(e.filter((t=>t.id?.authority===i?.authority&&t.id?.code===i?.code&&0===t.grids?.length)).length>0)return t.exports?.proj4;const n=e.filter((t=>0===t.grids?.length&&"EPSG"===t.target_crs?.authority&&4326===t.target_crs?.code&&!1===t.deprecated&&!0===t.usable)).sort(((t,e)=>t.accuracy-e.accuracy))[0]?.exports?.proj4;if(n)return n}return t.exports?.proj4}}}))}},FR.proj.proj4.fromEPSGCode=async function(t){"string"==typeof t&&(t=parseInt(t.split(":").pop(),10));const e=i_;if(!e)throw new Error("Proj4 must be registered first with register(proj4)");const i="EPSG:"+t;return e.defs(i)||(e.defs(i,await r_(t)),n_(e)),nn(i)},FR.proj.proj4.getEPSGLookup=function(){return r_},FR.proj.proj4.isRegistered=function(){return!!i_},FR.proj.proj4.register=n_,FR.proj.proj4.setEPSGLookup=function(t){r_=t},FR.proj.proj4.unregister=function(){i_=null},FR.proj.projections={},FR.proj.projections.add=li,FR.proj.projections.clear=oi,FR.proj.projections.get=ai,FR.proj.setUserProjection=mn,FR.proj.toLonLat=function(t,e){const i=gn(t,void 0!==e?e:"EPSG:3857","EPSG:4326"),n=i[0];return(n<-180||n>180)&&(i[0]=xi(n+180,360)-180),i},FR.proj.toUserCoordinate=yn,FR.proj.toUserExtent=vn,FR.proj.toUserResolution=wn,FR.proj.transform=gn,FR.proj.transformExtent=fn,FR.proj.transformWithProjections=function(t,e,i){return un(e,i)(t)},FR.proj.transforms={},FR.proj.transforms.add=ui,FR.proj.transforms.clear=ci,FR.proj.transforms.get=di,FR.proj.transforms.remove=function(t,e){const i=t.getCode(),n=e.getCode(),r=hi[i][n];return delete hi[i][n],S(hi[i])&&delete hi[i],r},FR.proj.useGeographic=function(){mn("EPSG:4326")},FR.render={},FR.render.Box=ja,FR.render.Event=oo,FR.render.Feature=e_,FR.render.Feature.toFeature=function(t,e){const i=t.getId(),n=t_(t),r=t.getProperties(),s=new Nt;return void 0!==e&&s.setGeometryName(e),s.setGeometry(n),void 0!==i&&s.setId(i),s.setProperties(r,!0),s},FR.render.Feature.toGeometry=t_,FR.render.VectorContext=zl,FR.render.canvas={},FR.render.canvas.Builder=em,FR.render.canvas.BuilderGroup=cm,FR.render.canvas.Executor=wm,FR.render.canvas.ExecutorGroup=Rm,FR.render.canvas.ExecutorGroup.getPixelIndexArray=Cm,FR.render.canvas.ImageBuilder=im,FR.render.canvas.Immediate=Xl,FR.render.canvas.Instruction={},FR.render.canvas.Instruction.beginPathInstruction=Qp,FR.render.canvas.Instruction.closePathInstruction=tm,FR.render.canvas.Instruction.fillInstruction=$p,FR.render.canvas.Instruction.strokeInstruction=Jp,FR.render.canvas.LineStringBuilder=nm,FR.render.canvas.PolygonBuilder=rm,FR.render.canvas.TextBuilder=lm,FR.render.canvas.TextBuilder.TEXT_ALIGN=am,FR.render.canvas.checkedFonts=bo,FR.render.canvas.defaultFillStyle=yo,FR.render.canvas.defaultFont=_o,FR.render.canvas.defaultLineCap=xo,FR.render.canvas.defaultLineDash=vo,FR.render.canvas.defaultLineDashOffset=0,FR.render.canvas.defaultLineJoin=So,FR.render.canvas.defaultLineWidth=1,FR.render.canvas.defaultMiterLimit=wo,FR.render.canvas.defaultPadding=Ro,FR.render.canvas.defaultStrokeStyle=Eo,FR.render.canvas.defaultTextAlign=To,FR.render.canvas.defaultTextBaseline=Co,FR.render.canvas.drawImageOrLabel=ko,FR.render.canvas.getTextDimensions=Do,FR.render.canvas.hitdetect={},FR.render.canvas.hitdetect.HIT_DETECT_RESOLUTION=bm,FR.render.canvas.hitdetect.createHitDetectionImageData=Pm,FR.render.canvas.hitdetect.hitDetect=Im,FR.render.canvas.measureAndCacheTextWidth=No,FR.render.canvas.measureTextHeight=Mo,FR.render.canvas.measureTextWidth=Oo,FR.render.canvas.registerFont=Lo,FR.render.canvas.rotateAtOffset=function(t,e,i,n){0!==e&&(t.translate(i,n),t.rotate(e),t.translate(-i,-n))},FR.render.canvas.textHeights=Fo,FR.render.getRenderPixel=function(t,e){return zt(t.inversePixelTransform,e.slice(0))},FR.render.getVectorContext=$l,FR.render.toContext=function(t,e){const i=t.canvas,n=(e=e||{}).pixelRatio||ft,r=e.size;r&&(i.width=r[0]*n,i.height=r[1]*n,i.style.width=r[0]+"px",i.style.height=r[1]+"px");const s=[0,0,i.width,i.height],o=Vt([1,0,0,1,0,0],n,n);return new Xl(t,n,s,o,0)},FR.render.webgl={},FR.render.webgl.MixedGeometryBatch=bf,FR.render.webgl.VectorStyleRenderer=Op,FR.render.webgl.renderinstructions={},FR.render.webgl.renderinstructions.generateLineStringRenderInstructions=Cp,FR.render.webgl.renderinstructions.generatePointRenderInstructions=Tp,FR.render.webgl.renderinstructions.generatePolygonRenderInstructions=Rp,FR.render.webgl.renderinstructions.getCustomAttributesSize=Ep,FR.render.webgl.utils={},FR.render.webgl.utils.colorDecodeId=xp,FR.render.webgl.utils.colorEncodeId=yp,FR.render.webgl.utils.getBlankImageData=function(){const t=document.createElement("canvas").getContext("2d").createImageData(1,1);return t.data[0]=255,t.data[1]=255,t.data[2]=255,t.data[3]=255,t},FR.render.webgl.utils.writeLineSegmentToBuffers=function(t,e,i,n,r,s,o,a,l,h){const c=5+a.length,u=s.length/c,d=[t[e+0],t[e+1]],g=[t[i],t[i+1]],f=zt(h,[...d]),p=zt(h,[...g]);function m(t,e,i){const n=1e4;return Math.round(1500*e)+Math.round(1500*i)*n+t*n*n}function _(t,e,i){const n=Math.sqrt((e[0]-t[0])*(e[0]-t[0])+(e[1]-t[1])*(e[1]-t[1])),r=[(e[0]-t[0])/n,(e[1]-t[1])/n],s=[-r[1],r[0]],o=Math.sqrt((i[0]-t[0])*(i[0]-t[0])+(i[1]-t[1])*(i[1]-t[1])),a=[(i[0]-t[0])/o,(i[1]-t[1])/o],l=0===n||0===o?0:Math.acos(gi(a[0]*r[0]+a[1]*r[1],-1,1));return a[0]*s[0]+a[1]*s[1]>0?l:2*Math.PI-l}const y=null!==r;let x=0,v=0;if(null!==n){x=_(f,p,zt(h,[...[t[n],t[n+1]]]))}if(y){v=_(p,f,zt(h,[...[t[r],t[r+1]]]))}s.push(d[0],d[1],g[0],g[1],m(0,x,v)),s.push(...a),s.push(d[0],d[1],g[0],g[1],m(1,x,v)),s.push(...a),s.push(d[0],d[1],g[0],g[1],m(2,x,v)),s.push(...a),s.push(d[0],d[1],g[0],g[1],m(3,x,v)),s.push(...a),o.push(u,u+1,u+2,u+1,u+3,u+2)},FR.render.webgl.utils.writePointFeatureToBuffers=function(t,e,i,n,r,s){const o=3+r,a=t[e+0],l=t[e+1],h=pp;h.length=r;for(let i=0;i1?"projection"in e?i.TileMatrixSetLink.findIndex((function(t){const i=n.find((function(e){return e.Identifier==t.TileMatrixSet})).SupportedCRS,r=nn(i),s=nn(e.projection);return r&&s?cn(r,s):i==e.projection})):i.TileMatrixSetLink.findIndex((function(t){return t.TileMatrixSet==e.matrixSet})):0,r<0&&(r=0);const s=i.TileMatrixSetLink[r].TileMatrixSet,o=i.TileMatrixSetLink[r].TileMatrixSetLimits;let a=i.Format[0];"format"in e&&(a=e.format),r=i.Style.findIndex((function(t){return"style"in e?t.Title==e.style:t.isDefault})),r<0&&(r=0);const l=i.Style[r].Identifier,h={};"Dimension"in i&&i.Dimension.forEach((function(t,e,i){const n=t.Identifier;let r=t.Default;void 0===r&&(r=t.Value[0]),h[n]=r}));const c=t.Contents.TileMatrixSet.find((function(t){return t.Identifier==s}));let u;const d=c.SupportedCRS;if(d&&(u=nn(d)),"projection"in e){const t=nn(e.projection);t&&(u&&!cn(t,u)||(u=t))}let g=!1;const f="ne"==u.getAxisOrientation().substr(0,2);let p=c.TileMatrix[0],m={MinTileCol:0,MinTileRow:0,MaxTileCol:p.MatrixWidth-1,MaxTileRow:p.MatrixHeight-1};if(o){m=o[o.length-1];const t=c.TileMatrix.find((t=>t.Identifier===m.TileMatrix||c.Identifier+":"+t.Identifier===m.TileMatrix));t&&(p=t)}const _=28e-5*p.ScaleDenominator/u.getMetersPerUnit(),y=f?[p.TopLeftCorner[1],p.TopLeftCorner[0]]:p.TopLeftCorner,x=p.TileWidth*_,v=p.TileHeight*_;let S=c.BoundingBox;S&&f&&(S=[S[1],S[0],S[3],S[2]]);let w=[y[0]+x*m.MinTileCol,y[1]-v*(1+m.MaxTileRow),y[0]+x*(1+m.MaxTileCol),y[1]-v*m.MinTileRow];if(void 0!==S&&!re(S,w)){const t=i.WGS84BoundingBox,e=nn("EPSG:4326").getExtent();if(w=S,t)g=t[0]===e[0]&&t[2]===e[2];else{const t=fn(S,c.SupportedCRS,"EPSG:4326");g=t[0]-1e-10<=e[0]&&t[2]+1e-10>=e[2]}}const E=Ju(c,w,o),T=[];let C=e.requestEncoding;if(C=void 0!==C?C:"","OperationsMetadata"in t&&"GetTile"in t.OperationsMetadata){const e=t.OperationsMetadata.GetTile.DCP.HTTP.Get;for(let t=0,i=e.length;t{const n=t.toString();if(!i.containsKey(n)){const r=e(t);i.set(n,r)}a.push(i.get(n))})),a}},FR.source.wms={},FR.source.wms.DEFAULT_VERSION=Qc,FR.sphere={},FR.sphere.DEFAULT_RADIUS=Ui,FR.sphere.getArea=function t(e,i){const n=(i=i||{}).radius||Ui,r=i.projection||"EPSG:3857",s=e.getType();"GeometryCollection"!==s&&(e=e.clone().transform(r,"EPSG:4326"));let o,a,l,h,c,u,d=0;switch(s){case"Point":case"MultiPoint":case"LineString":case"MultiLineString":case"LinearRing":break;case"Polygon":for(o=e.getCoordinates(),d=Math.abs(Vi(o[0],n)),l=1,h=o.length;l} */\nconst messages = {\n 1: 'The view center is not defined',\n 2: 'The view resolution is not defined',\n 3: 'The view rotation is not defined',\n 4: '`image` and `src` cannot be provided at the same time',\n 5: '`imgSize` must be set when `image` is provided',\n 7: '`format` must be set when `url` is set',\n 8: 'Unknown `serverType` configured',\n 9: '`url` must be configured or set using `#setUrl()`',\n 10: 'The default `geometryFunction` can only handle `Point` geometries',\n 11: '`options.featureTypes` must be an Array',\n 12: '`options.geometryName` must also be provided when `options.bbox` is set',\n 13: 'Invalid corner',\n 14: 'Invalid color',\n 15: 'Tried to get a value for a key that does not exist in the cache',\n 16: 'Tried to set a value for a key that is used already',\n 17: '`resolutions` must be sorted in descending order',\n 18: 'Either `origin` or `origins` must be configured, never both',\n 19: 'Number of `tileSizes` and `resolutions` must be equal',\n 20: 'Number of `origins` and `resolutions` must be equal',\n 22: 'Either `tileSize` or `tileSizes` must be configured, never both',\n 24: 'Invalid extent or geometry provided as `geometry`',\n 25: 'Cannot fit empty extent provided as `geometry`',\n 26: 'Features must have an id set',\n 27: 'Features must have an id set',\n 28: '`renderMode` must be `\"hybrid\"` or `\"vector\"`',\n 30: 'The passed `feature` was already added to the source',\n 31: 'Tried to enqueue an `element` that was already added to the queue',\n 32: 'Transformation matrix cannot be inverted',\n 33: 'Invalid units',\n 34: 'Invalid geometry layout',\n 36: 'Unknown SRS type',\n 37: 'Unknown geometry type found',\n 38: '`styleMapValue` has an unknown type',\n 39: 'Unknown geometry type',\n 40: 'Expected `feature` to have a geometry',\n 41: 'Expected an `ol/style/Style` or an array of `ol/style/Style.js`',\n 42: 'Question unknown, the answer is 42',\n 43: 'Expected `layers` to be an array or a `Collection`',\n 47: 'Expected `controls` to be an array or an `ol/Collection`',\n 48: 'Expected `interactions` to be an array or an `ol/Collection`',\n 49: 'Expected `overlays` to be an array or an `ol/Collection`',\n 50: '`options.featureTypes` should be an Array',\n 51: 'Either `url` or `tileJSON` options must be provided',\n 52: 'Unknown `serverType` configured',\n 53: 'Unknown `tierSizeCalculation` configured',\n 55: 'The {-y} placeholder requires a tile grid with extent',\n 56: 'mapBrowserEvent must originate from a pointer event',\n 57: 'At least 2 conditions are required',\n 59: 'Invalid command found in the PBF',\n 60: 'Missing or invalid `size`',\n 61: 'Cannot determine IIIF Image API version from provided image information JSON',\n 62: 'A `WebGLArrayBuffer` must either be of type `ELEMENT_ARRAY_BUFFER` or `ARRAY_BUFFER`',\n 64: 'Layer opacity must be a number',\n 66: '`forEachFeatureAtCoordinate` cannot be used on a WebGL layer if the hit detection logic has not been enabled. This is done by providing adequate shaders using the `hitVertexShader` and `hitFragmentShader` properties of `WebGLPointsLayerRenderer`',\n 67: 'A layer can only be added to the map once. Use either `layer.setMap()` or `map.addLayer()`, not both',\n 68: 'A VectorTile source can only be rendered if it has a projection compatible with the view projection',\n 69: '`width` or `height` cannot be provided together with `scale`',\n};\n\n/**\n * Error object thrown when an assertion failed. This is an ECMA-262 Error,\n * extended with a `code` property.\n * See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error.\n */\nclass AssertionError extends Error {\n /**\n * @param {number} code Error code.\n */\n constructor(code) {\n const message = messages[code];\n\n super(message);\n\n /**\n * Error code. The meaning of the code can be found on\n * https://openlayers.org/en/latest/doc/errors/ (replace `latest` with\n * the version found in the OpenLayers script's header comment if a version\n * other than the latest is used).\n * @type {number}\n * @deprecated ol/AssertionError and error codes will be removed in v8.0\n * @api\n */\n this.code = code;\n\n /**\n * @type {string}\n */\n this.name = 'AssertionError';\n\n // Re-assign message, see https://github.com/Rich-Harris/buble/issues/40\n this.message = message;\n }\n}\n\nexport default AssertionError;\n","/**\n * @module ol/events/Event\n */\n\n/**\n * @classdesc\n * Stripped down implementation of the W3C DOM Level 2 Event interface.\n * See https://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-interface.\n *\n * This implementation only provides `type` and `target` properties, and\n * `stopPropagation` and `preventDefault` methods. It is meant as base class\n * for higher level events defined in the library, and works with\n * {@link module:ol/events/Target~Target}.\n */\nclass BaseEvent {\n /**\n * @param {string} type Type.\n */\n constructor(type) {\n /**\n * @type {boolean}\n */\n this.propagationStopped;\n\n /**\n * @type {boolean}\n */\n this.defaultPrevented;\n\n /**\n * The event type.\n * @type {string}\n * @api\n */\n this.type = type;\n\n /**\n * The event target.\n * @type {Object}\n * @api\n */\n this.target = null;\n }\n\n /**\n * Prevent default. This means that no emulated `click`, `singleclick` or `doubleclick` events\n * will be fired.\n * @api\n */\n preventDefault() {\n this.defaultPrevented = true;\n }\n\n /**\n * Stop event propagation.\n * @api\n */\n stopPropagation() {\n this.propagationStopped = true;\n }\n}\n\n/**\n * @param {Event|import(\"./Event.js\").default} evt Event\n */\nexport function stopPropagation(evt) {\n evt.stopPropagation();\n}\n\n/**\n * @param {Event|import(\"./Event.js\").default} evt Event\n */\nexport function preventDefault(evt) {\n evt.preventDefault();\n}\n\nexport default BaseEvent;\n","/**\n * @module ol/ObjectEventType\n */\n\n/**\n * @enum {string}\n */\nexport default {\n /**\n * Triggered when a property is changed.\n * @event module:ol/Object.ObjectEvent#propertychange\n * @api\n */\n PROPERTYCHANGE: 'propertychange',\n};\n\n/**\n * @typedef {'propertychange'} Types\n */\n","/**\n * @module ol/Disposable\n */\n\n/**\n * @classdesc\n * Objects that need to clean up after themselves.\n */\nclass Disposable {\n constructor() {\n /**\n * The object has already been disposed.\n * @type {boolean}\n * @protected\n */\n this.disposed = false;\n }\n\n /**\n * Clean up.\n */\n dispose() {\n if (!this.disposed) {\n this.disposed = true;\n this.disposeInternal();\n }\n }\n\n /**\n * Extension point for disposable objects.\n * @protected\n */\n disposeInternal() {}\n}\n\nexport default Disposable;\n","/**\n * @module ol/array\n */\n\n/**\n * Performs a binary search on the provided sorted list and returns the index of the item if found. If it can't be found it'll return -1.\n * https://github.com/darkskyapp/binary-search\n *\n * @param {Array<*>} haystack Items to search through.\n * @param {*} needle The item to look for.\n * @param {Function} [comparator] Comparator function.\n * @return {number} The index of the item if found, -1 if not.\n */\nexport function binarySearch(haystack, needle, comparator) {\n let mid, cmp;\n comparator = comparator || ascending;\n let low = 0;\n let high = haystack.length;\n let found = false;\n\n while (low < high) {\n /* Note that \"(low + high) >>> 1\" may overflow, and results in a typecast\n * to double (which gives the wrong results). */\n mid = low + ((high - low) >> 1);\n cmp = +comparator(haystack[mid], needle);\n\n if (cmp < 0.0) {\n /* Too low. */\n low = mid + 1;\n } else {\n /* Key found or too high */\n high = mid;\n found = !cmp;\n }\n }\n\n /* Key not found. */\n return found ? low : ~low;\n}\n\n/**\n * Compare function sorting arrays in ascending order. Safe to use for numeric values.\n * @param {*} a The first object to be compared.\n * @param {*} b The second object to be compared.\n * @return {number} A negative number, zero, or a positive number as the first\n * argument is less than, equal to, or greater than the second.\n */\nexport function ascending(a, b) {\n return a > b ? 1 : a < b ? -1 : 0;\n}\n\n/**\n * Compare function sorting arrays in descending order. Safe to use for numeric values.\n * @param {*} a The first object to be compared.\n * @param {*} b The second object to be compared.\n * @return {number} A negative number, zero, or a positive number as the first\n * argument is greater than, equal to, or less than the second.\n */\nexport function descending(a, b) {\n return a < b ? 1 : a > b ? -1 : 0;\n}\n\n/**\n * {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution} can use a function\n * of this type to determine which nearest resolution to use.\n *\n * This function takes a `{number}` representing a value between two array entries,\n * a `{number}` representing the value of the nearest higher entry and\n * a `{number}` representing the value of the nearest lower entry\n * as arguments and returns a `{number}`. If a negative number or zero is returned\n * the lower value will be used, if a positive number is returned the higher value\n * will be used.\n * @typedef {function(number, number, number): number} NearestDirectionFunction\n * @api\n */\n\n/**\n * @param {Array} arr Array in descending order.\n * @param {number} target Target.\n * @param {number|NearestDirectionFunction} direction\n * 0 means return the nearest,\n * > 0 means return the largest nearest,\n * < 0 means return the smallest nearest.\n * @return {number} Index.\n */\nexport function linearFindNearest(arr, target, direction) {\n if (arr[0] <= target) {\n return 0;\n }\n\n const n = arr.length;\n if (target <= arr[n - 1]) {\n return n - 1;\n }\n\n if (typeof direction === 'function') {\n for (let i = 1; i < n; ++i) {\n const candidate = arr[i];\n if (candidate === target) {\n return i;\n }\n if (candidate < target) {\n if (direction(target, arr[i - 1], candidate) > 0) {\n return i - 1;\n }\n return i;\n }\n }\n return n - 1;\n }\n\n if (direction > 0) {\n for (let i = 1; i < n; ++i) {\n if (arr[i] < target) {\n return i - 1;\n }\n }\n return n - 1;\n }\n\n if (direction < 0) {\n for (let i = 1; i < n; ++i) {\n if (arr[i] <= target) {\n return i;\n }\n }\n return n - 1;\n }\n\n for (let i = 1; i < n; ++i) {\n if (arr[i] == target) {\n return i;\n }\n if (arr[i] < target) {\n if (arr[i - 1] - target < target - arr[i]) {\n return i - 1;\n }\n return i;\n }\n }\n return n - 1;\n}\n\n/**\n * @param {Array<*>} arr Array.\n * @param {number} begin Begin index.\n * @param {number} end End index.\n */\nexport function reverseSubArray(arr, begin, end) {\n while (begin < end) {\n const tmp = arr[begin];\n arr[begin] = arr[end];\n arr[end] = tmp;\n ++begin;\n --end;\n }\n}\n\n/**\n * @param {Array} arr The array to modify.\n * @param {!Array|VALUE} data The elements or arrays of elements to add to arr.\n * @template VALUE\n */\nexport function extend(arr, data) {\n const extension = Array.isArray(data) ? data : [data];\n const length = extension.length;\n for (let i = 0; i < length; i++) {\n arr[arr.length] = extension[i];\n }\n}\n\n/**\n * @param {Array} arr The array to modify.\n * @param {VALUE} obj The element to remove.\n * @template VALUE\n * @return {boolean} If the element was removed.\n */\nexport function remove(arr, obj) {\n const i = arr.indexOf(obj);\n const found = i > -1;\n if (found) {\n arr.splice(i, 1);\n }\n return found;\n}\n\n/**\n * @param {Array|Uint8ClampedArray} arr1 The first array to compare.\n * @param {Array|Uint8ClampedArray} arr2 The second array to compare.\n * @return {boolean} Whether the two arrays are equal.\n */\nexport function equals(arr1, arr2) {\n const len1 = arr1.length;\n if (len1 !== arr2.length) {\n return false;\n }\n for (let i = 0; i < len1; i++) {\n if (arr1[i] !== arr2[i]) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Sort the passed array such that the relative order of equal elements is preserved.\n * See https://en.wikipedia.org/wiki/Sorting_algorithm#Stability for details.\n * @param {Array<*>} arr The array to sort (modifies original).\n * @param {!function(*, *): number} compareFnc Comparison function.\n * @api\n */\nexport function stableSort(arr, compareFnc) {\n const length = arr.length;\n const tmp = Array(arr.length);\n let i;\n for (i = 0; i < length; i++) {\n tmp[i] = {index: i, value: arr[i]};\n }\n tmp.sort(function (a, b) {\n return compareFnc(a.value, b.value) || a.index - b.index;\n });\n for (i = 0; i < arr.length; i++) {\n arr[i] = tmp[i].value;\n }\n}\n\n/**\n * @param {Array<*>} arr The array to test.\n * @param {Function} [func] Comparison function.\n * @param {boolean} [strict] Strictly sorted (default false).\n * @return {boolean} Return index.\n */\nexport function isSorted(arr, func, strict) {\n const compare = func || ascending;\n return arr.every(function (currentVal, index) {\n if (index === 0) {\n return true;\n }\n const res = compare(arr[index - 1], currentVal);\n return !(res > 0 || (strict && res === 0));\n });\n}\n","/**\n * @module ol/functions\n */\n\nimport {equals as arrayEquals} from './array.js';\n\n/**\n * Always returns true.\n * @return {boolean} true.\n */\nexport function TRUE() {\n return true;\n}\n\n/**\n * Always returns false.\n * @return {boolean} false.\n */\nexport function FALSE() {\n return false;\n}\n\n/**\n * A reusable function, used e.g. as a default for callbacks.\n *\n * @return {void} Nothing.\n */\nexport function VOID() {}\n\n/**\n * Wrap a function in another function that remembers the last return. If the\n * returned function is called twice in a row with the same arguments and the same\n * this object, it will return the value from the first call in the second call.\n *\n * @param {function(...any): ReturnType} fn The function to memoize.\n * @return {function(...any): ReturnType} The memoized function.\n * @template ReturnType\n */\nexport function memoizeOne(fn) {\n let called = false;\n\n /** @type {ReturnType} */\n let lastResult;\n\n /** @type {Array} */\n let lastArgs;\n\n let lastThis;\n\n return function () {\n const nextArgs = Array.prototype.slice.call(arguments);\n if (!called || this !== lastThis || !arrayEquals(nextArgs, lastArgs)) {\n called = true;\n lastThis = this;\n lastArgs = nextArgs;\n lastResult = fn.apply(this, arguments);\n }\n return lastResult;\n };\n}\n\n/**\n * @template T\n * @param {function(): (T | Promise)} getter A function that returns a value or a promise for a value.\n * @return {Promise} A promise for the value.\n */\nexport function toPromise(getter) {\n function promiseGetter() {\n let value;\n try {\n value = getter();\n } catch (err) {\n return Promise.reject(err);\n }\n if (value instanceof Promise) {\n return value;\n }\n return Promise.resolve(value);\n }\n return promiseGetter();\n}\n","/**\n * @module ol/obj\n */\n\n/**\n * Removes all properties from an object.\n * @param {Object} object The object to clear.\n */\nexport function clear(object) {\n for (const property in object) {\n delete object[property];\n }\n}\n\n/**\n * Determine if an object has any properties.\n * @param {Object} object The object to check.\n * @return {boolean} The object is empty.\n */\nexport function isEmpty(object) {\n let property;\n for (property in object) {\n return false;\n }\n return !property;\n}\n","/**\n * @module ol/events/Target\n */\nimport Disposable from '../Disposable.js';\nimport Event from './Event.js';\nimport {VOID} from '../functions.js';\nimport {clear} from '../obj.js';\n\n/**\n * @typedef {EventTarget|Target} EventTargetLike\n */\n\n/**\n * @classdesc\n * A simplified implementation of the W3C DOM Level 2 EventTarget interface.\n * See https://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113/events.html#Events-EventTarget.\n *\n * There are two important simplifications compared to the specification:\n *\n * 1. The handling of `useCapture` in `addEventListener` and\n * `removeEventListener`. There is no real capture model.\n * 2. The handling of `stopPropagation` and `preventDefault` on `dispatchEvent`.\n * There is no event target hierarchy. When a listener calls\n * `stopPropagation` or `preventDefault` on an event object, it means that no\n * more listeners after this one will be called. Same as when the listener\n * returns false.\n */\nclass Target extends Disposable {\n /**\n * @param {*} [target] Default event target for dispatched events.\n */\n constructor(target) {\n super();\n\n /**\n * @private\n * @type {*}\n */\n this.eventTarget_ = target;\n\n /**\n * @private\n * @type {Object}\n */\n this.pendingRemovals_ = null;\n\n /**\n * @private\n * @type {Object}\n */\n this.dispatching_ = null;\n\n /**\n * @private\n * @type {Object>}\n */\n this.listeners_ = null;\n }\n\n /**\n * @param {string} type Type.\n * @param {import(\"../events.js\").Listener} listener Listener.\n */\n addEventListener(type, listener) {\n if (!type || !listener) {\n return;\n }\n const listeners = this.listeners_ || (this.listeners_ = {});\n const listenersForType = listeners[type] || (listeners[type] = []);\n if (!listenersForType.includes(listener)) {\n listenersForType.push(listener);\n }\n }\n\n /**\n * Dispatches an event and calls all listeners listening for events\n * of this type. The event parameter can either be a string or an\n * Object with a `type` property.\n *\n * @param {import(\"./Event.js\").default|string} event Event object.\n * @return {boolean|undefined} `false` if anyone called preventDefault on the\n * event object or if any of the listeners returned false.\n * @api\n */\n dispatchEvent(event) {\n const isString = typeof event === 'string';\n const type = isString ? event : event.type;\n const listeners = this.listeners_ && this.listeners_[type];\n if (!listeners) {\n return;\n }\n\n const evt = isString ? new Event(event) : /** @type {Event} */ (event);\n if (!evt.target) {\n evt.target = this.eventTarget_ || this;\n }\n const dispatching = this.dispatching_ || (this.dispatching_ = {});\n const pendingRemovals =\n this.pendingRemovals_ || (this.pendingRemovals_ = {});\n if (!(type in dispatching)) {\n dispatching[type] = 0;\n pendingRemovals[type] = 0;\n }\n ++dispatching[type];\n let propagate;\n for (let i = 0, ii = listeners.length; i < ii; ++i) {\n if ('handleEvent' in listeners[i]) {\n propagate = /** @type {import(\"../events.js\").ListenerObject} */ (\n listeners[i]\n ).handleEvent(evt);\n } else {\n propagate = /** @type {import(\"../events.js\").ListenerFunction} */ (\n listeners[i]\n ).call(this, evt);\n }\n if (propagate === false || evt.propagationStopped) {\n propagate = false;\n break;\n }\n }\n if (--dispatching[type] === 0) {\n let pr = pendingRemovals[type];\n delete pendingRemovals[type];\n while (pr--) {\n this.removeEventListener(type, VOID);\n }\n delete dispatching[type];\n }\n return propagate;\n }\n\n /**\n * Clean up.\n */\n disposeInternal() {\n this.listeners_ && clear(this.listeners_);\n }\n\n /**\n * Get the listeners for a specified event type. Listeners are returned in the\n * order that they will be called in.\n *\n * @param {string} type Type.\n * @return {Array|undefined} Listeners.\n */\n getListeners(type) {\n return (this.listeners_ && this.listeners_[type]) || undefined;\n }\n\n /**\n * @param {string} [type] Type. If not provided,\n * `true` will be returned if this event target has any listeners.\n * @return {boolean} Has listeners.\n */\n hasListener(type) {\n if (!this.listeners_) {\n return false;\n }\n return type\n ? type in this.listeners_\n : Object.keys(this.listeners_).length > 0;\n }\n\n /**\n * @param {string} type Type.\n * @param {import(\"../events.js\").Listener} listener Listener.\n */\n removeEventListener(type, listener) {\n const listeners = this.listeners_ && this.listeners_[type];\n if (listeners) {\n const index = listeners.indexOf(listener);\n if (index !== -1) {\n if (this.pendingRemovals_ && type in this.pendingRemovals_) {\n // make listener a no-op, and remove later in #dispatchEvent()\n listeners[index] = VOID;\n ++this.pendingRemovals_[type];\n } else {\n listeners.splice(index, 1);\n if (listeners.length === 0) {\n delete this.listeners_[type];\n }\n }\n }\n }\n }\n}\n\nexport default Target;\n","/**\n * @module ol/events/EventType\n */\n\n/**\n * @enum {string}\n * @const\n */\nexport default {\n /**\n * Generic change event. Triggered when the revision counter is increased.\n * @event module:ol/events/Event~BaseEvent#change\n * @api\n */\n CHANGE: 'change',\n\n /**\n * Generic error event. Triggered when an error occurs.\n * @event module:ol/events/Event~BaseEvent#error\n * @api\n */\n ERROR: 'error',\n\n BLUR: 'blur',\n CLEAR: 'clear',\n CONTEXTMENU: 'contextmenu',\n CLICK: 'click',\n DBLCLICK: 'dblclick',\n DRAGENTER: 'dragenter',\n DRAGOVER: 'dragover',\n DROP: 'drop',\n FOCUS: 'focus',\n KEYDOWN: 'keydown',\n KEYPRESS: 'keypress',\n LOAD: 'load',\n RESIZE: 'resize',\n TOUCHMOVE: 'touchmove',\n WHEEL: 'wheel',\n};\n","/**\n * @module ol/events\n */\nimport {clear} from './obj.js';\n\n/**\n * Key to use with {@link module:ol/Observable.unByKey}.\n * @typedef {Object} EventsKey\n * @property {ListenerFunction} listener Listener.\n * @property {import(\"./events/Target.js\").EventTargetLike} target Target.\n * @property {string} type Type.\n * @api\n */\n\n/**\n * Listener function. This function is called with an event object as argument.\n * When the function returns `false`, event propagation will stop.\n *\n * @typedef {function((Event|import(\"./events/Event.js\").default)): (void|boolean)} ListenerFunction\n * @api\n */\n\n/**\n * @typedef {Object} ListenerObject\n * @property {ListenerFunction} handleEvent HandleEvent listener function.\n */\n\n/**\n * @typedef {ListenerFunction|ListenerObject} Listener\n */\n\n/**\n * Registers an event listener on an event target. Inspired by\n * https://google.github.io/closure-library/api/source/closure/goog/events/events.js.src.html\n *\n * This function efficiently binds a `listener` to a `this` object, and returns\n * a key for use with {@link module:ol/events.unlistenByKey}.\n *\n * @param {import(\"./events/Target.js\").EventTargetLike} target Event target.\n * @param {string} type Event type.\n * @param {ListenerFunction} listener Listener.\n * @param {Object} [thisArg] Object referenced by the `this` keyword in the\n * listener. Default is the `target`.\n * @param {boolean} [once] If true, add the listener as one-off listener.\n * @return {EventsKey} Unique key for the listener.\n */\nexport function listen(target, type, listener, thisArg, once) {\n if (thisArg && thisArg !== target) {\n listener = listener.bind(thisArg);\n }\n if (once) {\n const originalListener = listener;\n listener = function () {\n target.removeEventListener(type, listener);\n originalListener.apply(this, arguments);\n };\n }\n const eventsKey = {\n target: target,\n type: type,\n listener: listener,\n };\n target.addEventListener(type, listener);\n return eventsKey;\n}\n\n/**\n * Registers a one-off event listener on an event target. Inspired by\n * https://google.github.io/closure-library/api/source/closure/goog/events/events.js.src.html\n *\n * This function efficiently binds a `listener` as self-unregistering listener\n * to a `this` object, and returns a key for use with\n * {@link module:ol/events.unlistenByKey} in case the listener needs to be\n * unregistered before it is called.\n *\n * When {@link module:ol/events.listen} is called with the same arguments after this\n * function, the self-unregistering listener will be turned into a permanent\n * listener.\n *\n * @param {import(\"./events/Target.js\").EventTargetLike} target Event target.\n * @param {string} type Event type.\n * @param {ListenerFunction} listener Listener.\n * @param {Object} [thisArg] Object referenced by the `this` keyword in the\n * listener. Default is the `target`.\n * @return {EventsKey} Key for unlistenByKey.\n */\nexport function listenOnce(target, type, listener, thisArg) {\n return listen(target, type, listener, thisArg, true);\n}\n\n/**\n * Unregisters event listeners on an event target. Inspired by\n * https://google.github.io/closure-library/api/source/closure/goog/events/events.js.src.html\n *\n * The argument passed to this function is the key returned from\n * {@link module:ol/events.listen} or {@link module:ol/events.listenOnce}.\n *\n * @param {EventsKey} key The key.\n */\nexport function unlistenByKey(key) {\n if (key && key.target) {\n key.target.removeEventListener(key.type, key.listener);\n clear(key);\n }\n}\n","/**\n * @module ol/Observable\n */\nimport EventTarget from './events/Target.js';\nimport EventType from './events/EventType.js';\nimport {listen, listenOnce, unlistenByKey} from './events.js';\n\n/***\n * @template {string} Type\n * @template {Event|import(\"./events/Event.js\").default} EventClass\n * @template Return\n * @typedef {(type: Type, listener: (event: EventClass) => ?) => Return} OnSignature\n */\n\n/***\n * @template {string} Type\n * @template Return\n * @typedef {(type: Type[], listener: (event: Event|import(\"./events/Event\").default) => ?) => Return extends void ? void : Return[]} CombinedOnSignature\n */\n\n/**\n * @typedef {'change'|'error'} EventTypes\n */\n\n/***\n * @template Return\n * @typedef {OnSignature & CombinedOnSignature} ObservableOnSignature\n */\n\n/**\n * @classdesc\n * Abstract base class; normally only used for creating subclasses and not\n * instantiated in apps.\n * An event target providing convenient methods for listener registration\n * and unregistration. A generic `change` event is always available through\n * {@link module:ol/Observable~Observable#changed}.\n *\n * @fires import(\"./events/Event.js\").default\n * @api\n */\nclass Observable extends EventTarget {\n constructor() {\n super();\n\n this.on =\n /** @type {ObservableOnSignature} */ (\n this.onInternal\n );\n\n this.once =\n /** @type {ObservableOnSignature} */ (\n this.onceInternal\n );\n\n this.un = /** @type {ObservableOnSignature} */ (this.unInternal);\n\n /**\n * @private\n * @type {number}\n */\n this.revision_ = 0;\n }\n\n /**\n * Increases the revision counter and dispatches a 'change' event.\n * @api\n */\n changed() {\n ++this.revision_;\n this.dispatchEvent(EventType.CHANGE);\n }\n\n /**\n * Get the version number for this object. Each time the object is modified,\n * its version number will be incremented.\n * @return {number} Revision.\n * @api\n */\n getRevision() {\n return this.revision_;\n }\n\n /**\n * @param {string|Array} type Type.\n * @param {function((Event|import(\"./events/Event\").default)): ?} listener Listener.\n * @return {import(\"./events.js\").EventsKey|Array} Event key.\n * @protected\n */\n onInternal(type, listener) {\n if (Array.isArray(type)) {\n const len = type.length;\n const keys = new Array(len);\n for (let i = 0; i < len; ++i) {\n keys[i] = listen(this, type[i], listener);\n }\n return keys;\n }\n return listen(this, /** @type {string} */ (type), listener);\n }\n\n /**\n * @param {string|Array} type Type.\n * @param {function((Event|import(\"./events/Event\").default)): ?} listener Listener.\n * @return {import(\"./events.js\").EventsKey|Array} Event key.\n * @protected\n */\n onceInternal(type, listener) {\n let key;\n if (Array.isArray(type)) {\n const len = type.length;\n key = new Array(len);\n for (let i = 0; i < len; ++i) {\n key[i] = listenOnce(this, type[i], listener);\n }\n } else {\n key = listenOnce(this, /** @type {string} */ (type), listener);\n }\n /** @type {Object} */ (listener).ol_key = key;\n return key;\n }\n\n /**\n * Unlisten for a certain type of event.\n * @param {string|Array} type Type.\n * @param {function((Event|import(\"./events/Event\").default)): ?} listener Listener.\n * @protected\n */\n unInternal(type, listener) {\n const key = /** @type {Object} */ (listener).ol_key;\n if (key) {\n unByKey(key);\n } else if (Array.isArray(type)) {\n for (let i = 0, ii = type.length; i < ii; ++i) {\n this.removeEventListener(type[i], listener);\n }\n } else {\n this.removeEventListener(type, listener);\n }\n }\n}\n\n/**\n * Listen for a certain type of event.\n * @function\n * @param {string|Array} type The event type or array of event types.\n * @param {function((Event|import(\"./events/Event\").default)): ?} listener The listener function.\n * @return {import(\"./events.js\").EventsKey|Array} Unique key for the listener. If\n * called with an array of event types as the first argument, the return\n * will be an array of keys.\n * @api\n */\nObservable.prototype.on;\n\n/**\n * Listen once for a certain type of event.\n * @function\n * @param {string|Array} type The event type or array of event types.\n * @param {function((Event|import(\"./events/Event\").default)): ?} listener The listener function.\n * @return {import(\"./events.js\").EventsKey|Array} Unique key for the listener. If\n * called with an array of event types as the first argument, the return\n * will be an array of keys.\n * @api\n */\nObservable.prototype.once;\n\n/**\n * Unlisten for a certain type of event.\n * @function\n * @param {string|Array} type The event type or array of event types.\n * @param {function((Event|import(\"./events/Event\").default)): ?} listener The listener function.\n * @api\n */\nObservable.prototype.un;\n\n/**\n * Removes an event listener using the key returned by `on()` or `once()`.\n * @param {import(\"./events.js\").EventsKey|Array} key The key returned by `on()`\n * or `once()` (or an array of keys).\n * @api\n */\nexport function unByKey(key) {\n if (Array.isArray(key)) {\n for (let i = 0, ii = key.length; i < ii; ++i) {\n unlistenByKey(key[i]);\n }\n } else {\n unlistenByKey(/** @type {import(\"./events.js\").EventsKey} */ (key));\n }\n}\n\nexport default Observable;\n","/**\n * @module ol/util\n */\n\n/**\n * @return {never} Any return.\n */\nexport function abstract() {\n throw new Error('Unimplemented abstract method.');\n}\n\n/**\n * Counter for getUid.\n * @type {number}\n * @private\n */\nlet uidCounter_ = 0;\n\n/**\n * Gets a unique ID for an object. This mutates the object so that further calls\n * with the same object as a parameter returns the same value. Unique IDs are generated\n * as a strictly increasing sequence. Adapted from goog.getUid.\n *\n * @param {Object} obj The object to get the unique ID for.\n * @return {string} The unique ID for the object.\n * @api\n */\nexport function getUid(obj) {\n return obj.ol_uid || (obj.ol_uid = String(++uidCounter_));\n}\n\n/**\n * OpenLayers version.\n * @type {string}\n */\nexport const VERSION = '7.5.1';\n","/**\n * @module ol/Object\n */\nimport Event from './events/Event.js';\nimport ObjectEventType from './ObjectEventType.js';\nimport Observable from './Observable.js';\nimport {getUid} from './util.js';\nimport {isEmpty} from './obj.js';\n\n/**\n * @classdesc\n * Events emitted by {@link module:ol/Object~BaseObject} instances are instances of this type.\n */\nexport class ObjectEvent extends Event {\n /**\n * @param {string} type The event type.\n * @param {string} key The property name.\n * @param {*} oldValue The old value for `key`.\n */\n constructor(type, key, oldValue) {\n super(type);\n\n /**\n * The name of the property whose value is changing.\n * @type {string}\n * @api\n */\n this.key = key;\n\n /**\n * The old value. To get the new value use `e.target.get(e.key)` where\n * `e` is the event object.\n * @type {*}\n * @api\n */\n this.oldValue = oldValue;\n }\n}\n\n/***\n * @template Return\n * @typedef {import(\"./Observable\").OnSignature &\n * import(\"./Observable\").OnSignature &\n * import(\"./Observable\").CombinedOnSignature} ObjectOnSignature\n */\n\n/**\n * @classdesc\n * Abstract base class; normally only used for creating subclasses and not\n * instantiated in apps.\n * Most non-trivial classes inherit from this.\n *\n * This extends {@link module:ol/Observable~Observable} with observable\n * properties, where each property is observable as well as the object as a\n * whole.\n *\n * Classes that inherit from this have pre-defined properties, to which you can\n * add your owns. The pre-defined properties are listed in this documentation as\n * 'Observable Properties', and have their own accessors; for example,\n * {@link module:ol/Map~Map} has a `target` property, accessed with\n * `getTarget()` and changed with `setTarget()`. Not all properties are however\n * settable. There are also general-purpose accessors `get()` and `set()`. For\n * example, `get('target')` is equivalent to `getTarget()`.\n *\n * The `set` accessors trigger a change event, and you can monitor this by\n * registering a listener. For example, {@link module:ol/View~View} has a\n * `center` property, so `view.on('change:center', function(evt) {...});` would\n * call the function whenever the value of the center property changes. Within\n * the function, `evt.target` would be the view, so `evt.target.getCenter()`\n * would return the new center.\n *\n * You can add your own observable properties with\n * `object.set('prop', 'value')`, and retrieve that with `object.get('prop')`.\n * You can listen for changes on that property value with\n * `object.on('change:prop', listener)`. You can get a list of all\n * properties with {@link module:ol/Object~BaseObject#getProperties}.\n *\n * Note that the observable properties are separate from standard JS properties.\n * You can, for example, give your map object a title with\n * `map.title='New title'` and with `map.set('title', 'Another title')`. The\n * first will be a `hasOwnProperty`; the second will appear in\n * `getProperties()`. Only the second is observable.\n *\n * Properties can be deleted by using the unset method. E.g.\n * object.unset('foo').\n *\n * @fires ObjectEvent\n * @api\n */\nclass BaseObject extends Observable {\n /**\n * @param {Object} [values] An object with key-value pairs.\n */\n constructor(values) {\n super();\n\n /***\n * @type {ObjectOnSignature}\n */\n this.on;\n\n /***\n * @type {ObjectOnSignature}\n */\n this.once;\n\n /***\n * @type {ObjectOnSignature}\n */\n this.un;\n\n // Call {@link module:ol/util.getUid} to ensure that the order of objects' ids is\n // the same as the order in which they were created. This also helps to\n // ensure that object properties are always added in the same order, which\n // helps many JavaScript engines generate faster code.\n getUid(this);\n\n /**\n * @private\n * @type {Object}\n */\n this.values_ = null;\n\n if (values !== undefined) {\n this.setProperties(values);\n }\n }\n\n /**\n * Gets a value.\n * @param {string} key Key name.\n * @return {*} Value.\n * @api\n */\n get(key) {\n let value;\n if (this.values_ && this.values_.hasOwnProperty(key)) {\n value = this.values_[key];\n }\n return value;\n }\n\n /**\n * Get a list of object property names.\n * @return {Array} List of property names.\n * @api\n */\n getKeys() {\n return (this.values_ && Object.keys(this.values_)) || [];\n }\n\n /**\n * Get an object of all property names and values.\n * @return {Object} Object.\n * @api\n */\n getProperties() {\n return (this.values_ && Object.assign({}, this.values_)) || {};\n }\n\n /**\n * @return {boolean} The object has properties.\n */\n hasProperties() {\n return !!this.values_;\n }\n\n /**\n * @param {string} key Key name.\n * @param {*} oldValue Old value.\n */\n notify(key, oldValue) {\n let eventType;\n eventType = `change:${key}`;\n if (this.hasListener(eventType)) {\n this.dispatchEvent(new ObjectEvent(eventType, key, oldValue));\n }\n eventType = ObjectEventType.PROPERTYCHANGE;\n if (this.hasListener(eventType)) {\n this.dispatchEvent(new ObjectEvent(eventType, key, oldValue));\n }\n }\n\n /**\n * @param {string} key Key name.\n * @param {import(\"./events.js\").Listener} listener Listener.\n */\n addChangeListener(key, listener) {\n this.addEventListener(`change:${key}`, listener);\n }\n\n /**\n * @param {string} key Key name.\n * @param {import(\"./events.js\").Listener} listener Listener.\n */\n removeChangeListener(key, listener) {\n this.removeEventListener(`change:${key}`, listener);\n }\n\n /**\n * Sets a value.\n * @param {string} key Key name.\n * @param {*} value Value.\n * @param {boolean} [silent] Update without triggering an event.\n * @api\n */\n set(key, value, silent) {\n const values = this.values_ || (this.values_ = {});\n if (silent) {\n values[key] = value;\n } else {\n const oldValue = values[key];\n values[key] = value;\n if (oldValue !== value) {\n this.notify(key, oldValue);\n }\n }\n }\n\n /**\n * Sets a collection of key-value pairs. Note that this changes any existing\n * properties and adds new ones (it does not remove any existing properties).\n * @param {Object} values Values.\n * @param {boolean} [silent] Update without triggering an event.\n * @api\n */\n setProperties(values, silent) {\n for (const key in values) {\n this.set(key, values[key], silent);\n }\n }\n\n /**\n * Apply any properties from another object without triggering events.\n * @param {BaseObject} source The source object.\n * @protected\n */\n applyProperties(source) {\n if (!source.values_) {\n return;\n }\n Object.assign(this.values_ || (this.values_ = {}), source.values_);\n }\n\n /**\n * Unsets a property.\n * @param {string} key Key name.\n * @param {boolean} [silent] Unset without triggering an event.\n * @api\n */\n unset(key, silent) {\n if (this.values_ && key in this.values_) {\n const oldValue = this.values_[key];\n delete this.values_[key];\n if (isEmpty(this.values_)) {\n this.values_ = null;\n }\n if (!silent) {\n this.notify(key, oldValue);\n }\n }\n }\n}\n\nexport default BaseObject;\n","/**\n * @module ol/CollectionEventType\n */\n\n/**\n * @enum {string}\n */\nexport default {\n /**\n * Triggered when an item is added to the collection.\n * @event module:ol/Collection.CollectionEvent#add\n * @api\n */\n ADD: 'add',\n /**\n * Triggered when an item is removed from the collection.\n * @event module:ol/Collection.CollectionEvent#remove\n * @api\n */\n REMOVE: 'remove',\n};\n","/**\n * @module ol/Collection\n */\nimport AssertionError from './AssertionError.js';\nimport BaseObject from './Object.js';\nimport CollectionEventType from './CollectionEventType.js';\nimport Event from './events/Event.js';\n\n/**\n * @enum {string}\n * @private\n */\nconst Property = {\n LENGTH: 'length',\n};\n\n/**\n * @classdesc\n * Events emitted by {@link module:ol/Collection~Collection} instances are instances of this\n * type.\n * @template T\n */\nexport class CollectionEvent extends Event {\n /**\n * @param {import(\"./CollectionEventType.js\").default} type Type.\n * @param {T} element Element.\n * @param {number} index The index of the added or removed element.\n */\n constructor(type, element, index) {\n super(type);\n\n /**\n * The element that is added to or removed from the collection.\n * @type {T}\n * @api\n */\n this.element = element;\n\n /**\n * The index of the added or removed element.\n * @type {number}\n * @api\n */\n this.index = index;\n }\n}\n\n/***\n * @template T\n * @template Return\n * @typedef {import(\"./Observable\").OnSignature &\n * import(\"./Observable\").OnSignature &\n * import(\"./Observable\").OnSignature<'add'|'remove', CollectionEvent, Return> &\n * import(\"./Observable\").CombinedOnSignature} CollectionOnSignature\n */\n\n/**\n * @typedef {Object} Options\n * @property {boolean} [unique=false] Disallow the same item from being added to\n * the collection twice.\n */\n\n/**\n * @classdesc\n * An expanded version of standard JS Array, adding convenience methods for\n * manipulation. Add and remove changes to the Collection trigger a Collection\n * event. Note that this does not cover changes to the objects _within_ the\n * Collection; they trigger events on the appropriate object, not on the\n * Collection as a whole.\n *\n * @fires CollectionEvent\n *\n * @template T\n * @api\n */\nclass Collection extends BaseObject {\n /**\n * @param {Array} [array] Array.\n * @param {Options} [options] Collection options.\n */\n constructor(array, options) {\n super();\n\n /***\n * @type {CollectionOnSignature}\n */\n this.on;\n\n /***\n * @type {CollectionOnSignature}\n */\n this.once;\n\n /***\n * @type {CollectionOnSignature}\n */\n this.un;\n\n options = options || {};\n\n /**\n * @private\n * @type {boolean}\n */\n this.unique_ = !!options.unique;\n\n /**\n * @private\n * @type {!Array}\n */\n this.array_ = array ? array : [];\n\n if (this.unique_) {\n for (let i = 0, ii = this.array_.length; i < ii; ++i) {\n this.assertUnique_(this.array_[i], i);\n }\n }\n\n this.updateLength_();\n }\n\n /**\n * Remove all elements from the collection.\n * @api\n */\n clear() {\n while (this.getLength() > 0) {\n this.pop();\n }\n }\n\n /**\n * Add elements to the collection. This pushes each item in the provided array\n * to the end of the collection.\n * @param {!Array} arr Array.\n * @return {Collection} This collection.\n * @api\n */\n extend(arr) {\n for (let i = 0, ii = arr.length; i < ii; ++i) {\n this.push(arr[i]);\n }\n return this;\n }\n\n /**\n * Iterate over each element, calling the provided callback.\n * @param {function(T, number, Array): *} f The function to call\n * for every element. This function takes 3 arguments (the element, the\n * index and the array). The return value is ignored.\n * @api\n */\n forEach(f) {\n const array = this.array_;\n for (let i = 0, ii = array.length; i < ii; ++i) {\n f(array[i], i, array);\n }\n }\n\n /**\n * Get a reference to the underlying Array object. Warning: if the array\n * is mutated, no events will be dispatched by the collection, and the\n * collection's \"length\" property won't be in sync with the actual length\n * of the array.\n * @return {!Array} Array.\n * @api\n */\n getArray() {\n return this.array_;\n }\n\n /**\n * Get the element at the provided index.\n * @param {number} index Index.\n * @return {T} Element.\n * @api\n */\n item(index) {\n return this.array_[index];\n }\n\n /**\n * Get the length of this collection.\n * @return {number} The length of the array.\n * @observable\n * @api\n */\n getLength() {\n return this.get(Property.LENGTH);\n }\n\n /**\n * Insert an element at the provided index.\n * @param {number} index Index.\n * @param {T} elem Element.\n * @api\n */\n insertAt(index, elem) {\n if (index < 0 || index > this.getLength()) {\n throw new Error('Index out of bounds: ' + index);\n }\n if (this.unique_) {\n this.assertUnique_(elem);\n }\n this.array_.splice(index, 0, elem);\n this.updateLength_();\n this.dispatchEvent(\n new CollectionEvent(CollectionEventType.ADD, elem, index)\n );\n }\n\n /**\n * Remove the last element of the collection and return it.\n * Return `undefined` if the collection is empty.\n * @return {T|undefined} Element.\n * @api\n */\n pop() {\n return this.removeAt(this.getLength() - 1);\n }\n\n /**\n * Insert the provided element at the end of the collection.\n * @param {T} elem Element.\n * @return {number} New length of the collection.\n * @api\n */\n push(elem) {\n if (this.unique_) {\n this.assertUnique_(elem);\n }\n const n = this.getLength();\n this.insertAt(n, elem);\n return this.getLength();\n }\n\n /**\n * Remove the first occurrence of an element from the collection.\n * @param {T} elem Element.\n * @return {T|undefined} The removed element or undefined if none found.\n * @api\n */\n remove(elem) {\n const arr = this.array_;\n for (let i = 0, ii = arr.length; i < ii; ++i) {\n if (arr[i] === elem) {\n return this.removeAt(i);\n }\n }\n return undefined;\n }\n\n /**\n * Remove the element at the provided index and return it.\n * Return `undefined` if the collection does not contain this index.\n * @param {number} index Index.\n * @return {T|undefined} Value.\n * @api\n */\n removeAt(index) {\n if (index < 0 || index >= this.getLength()) {\n return undefined;\n }\n const prev = this.array_[index];\n this.array_.splice(index, 1);\n this.updateLength_();\n this.dispatchEvent(\n /** @type {CollectionEvent} */ (\n new CollectionEvent(CollectionEventType.REMOVE, prev, index)\n )\n );\n return prev;\n }\n\n /**\n * Set the element at the provided index.\n * @param {number} index Index.\n * @param {T} elem Element.\n * @api\n */\n setAt(index, elem) {\n const n = this.getLength();\n if (index >= n) {\n this.insertAt(index, elem);\n return;\n }\n if (index < 0) {\n throw new Error('Index out of bounds: ' + index);\n }\n if (this.unique_) {\n this.assertUnique_(elem, index);\n }\n const prev = this.array_[index];\n this.array_[index] = elem;\n this.dispatchEvent(\n /** @type {CollectionEvent} */ (\n new CollectionEvent(CollectionEventType.REMOVE, prev, index)\n )\n );\n this.dispatchEvent(\n /** @type {CollectionEvent} */ (\n new CollectionEvent(CollectionEventType.ADD, elem, index)\n )\n );\n }\n\n /**\n * @private\n */\n updateLength_() {\n this.set(Property.LENGTH, this.array_.length);\n }\n\n /**\n * @private\n * @param {T} elem Element.\n * @param {number} [except] Optional index to ignore.\n */\n assertUnique_(elem, except) {\n for (let i = 0, ii = this.array_.length; i < ii; ++i) {\n if (this.array_[i] === elem && i !== except) {\n throw new AssertionError(58);\n }\n }\n }\n}\n\nexport default Collection;\n","/**\n * @module ol/TileState\n */\n\n/**\n * @enum {number}\n */\nexport default {\n IDLE: 0,\n LOADING: 1,\n LOADED: 2,\n /**\n * Indicates that tile loading failed\n * @type {number}\n */\n ERROR: 3,\n EMPTY: 4,\n};\n","/**\n * @module ol/easing\n */\n\n/**\n * Start slow and speed up.\n * @param {number} t Input between 0 and 1.\n * @return {number} Output between 0 and 1.\n * @api\n */\nexport function easeIn(t) {\n return Math.pow(t, 3);\n}\n\n/**\n * Start fast and slow down.\n * @param {number} t Input between 0 and 1.\n * @return {number} Output between 0 and 1.\n * @api\n */\nexport function easeOut(t) {\n return 1 - easeIn(1 - t);\n}\n\n/**\n * Start slow, speed up, and then slow down again.\n * @param {number} t Input between 0 and 1.\n * @return {number} Output between 0 and 1.\n * @api\n */\nexport function inAndOut(t) {\n return 3 * t * t - 2 * t * t * t;\n}\n\n/**\n * Maintain a constant speed over time.\n * @param {number} t Input between 0 and 1.\n * @return {number} Output between 0 and 1.\n * @api\n */\nexport function linear(t) {\n return t;\n}\n\n/**\n * Start slow, speed up, and at the very end slow down again. This has the\n * same general behavior as {@link module:ol/easing.inAndOut}, but the final\n * slowdown is delayed.\n * @param {number} t Input between 0 and 1.\n * @return {number} Output between 0 and 1.\n * @api\n */\nexport function upAndDown(t) {\n if (t < 0.5) {\n return inAndOut(2 * t);\n }\n return 1 - inAndOut(2 * (t - 0.5));\n}\n","/**\n * @module ol/Tile\n */\nimport EventTarget from './events/Target.js';\nimport EventType from './events/EventType.js';\nimport TileState from './TileState.js';\nimport {abstract} from './util.js';\nimport {easeIn} from './easing.js';\n\n/**\n * A function that takes an {@link module:ol/Tile~Tile} for the tile and a\n * `{string}` for the url as arguments. The default is\n * ```js\n * source.setTileLoadFunction(function(tile, src) {\n * tile.getImage().src = src;\n * });\n * ```\n * For more fine grained control, the load function can use fetch or XMLHttpRequest and involve\n * error handling:\n *\n * ```js\n * import TileState from 'ol/TileState.js';\n *\n * source.setTileLoadFunction(function(tile, src) {\n * const xhr = new XMLHttpRequest();\n * xhr.responseType = 'blob';\n * xhr.addEventListener('loadend', function (evt) {\n * const data = this.response;\n * if (data !== undefined) {\n * tile.getImage().src = URL.createObjectURL(data);\n * } else {\n * tile.setState(TileState.ERROR);\n * }\n * });\n * xhr.addEventListener('error', function () {\n * tile.setState(TileState.ERROR);\n * });\n * xhr.open('GET', src);\n * xhr.send();\n * });\n * ```\n *\n * @typedef {function(Tile, string): void} LoadFunction\n * @api\n */\n\n/**\n * {@link module:ol/source/Tile~TileSource} sources use a function of this type to get\n * the url that provides a tile for a given tile coordinate.\n *\n * This function takes an {@link module:ol/tilecoord~TileCoord} for the tile\n * coordinate, a `{number}` representing the pixel ratio and a\n * {@link module:ol/proj/Projection~Projection} for the projection as arguments\n * and returns a `{string}` representing the tile URL, or undefined if no tile\n * should be requested for the passed tile coordinate.\n *\n * @typedef {function(import(\"./tilecoord.js\").TileCoord, number,\n * import(\"./proj/Projection.js\").default): (string|undefined)} UrlFunction\n * @api\n */\n\n/**\n * @typedef {Object} Options\n * @property {number} [transition=250] A duration for tile opacity\n * transitions in milliseconds. A duration of 0 disables the opacity transition.\n * @property {boolean} [interpolate=false] Use interpolated values when resampling. By default,\n * the nearest neighbor is used when resampling.\n * @api\n */\n\n/**\n * @classdesc\n * Base class for tiles.\n *\n * @abstract\n */\nclass Tile extends EventTarget {\n /**\n * @param {import(\"./tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n * @param {import(\"./TileState.js\").default} state State.\n * @param {Options} [options] Tile options.\n */\n constructor(tileCoord, state, options) {\n super();\n\n options = options ? options : {};\n\n /**\n * @type {import(\"./tilecoord.js\").TileCoord}\n */\n this.tileCoord = tileCoord;\n\n /**\n * @protected\n * @type {import(\"./TileState.js\").default}\n */\n this.state = state;\n\n /**\n * An \"interim\" tile for this tile. The interim tile may be used while this\n * one is loading, for \"smooth\" transitions when changing params/dimensions\n * on the source.\n * @type {Tile}\n */\n this.interimTile = null;\n\n /**\n * A key assigned to the tile. This is used by the tile source to determine\n * if this tile can effectively be used, or if a new tile should be created\n * and this one be used as an interim tile for this new tile.\n * @type {string}\n */\n this.key = '';\n\n /**\n * The duration for the opacity transition.\n * @type {number}\n */\n this.transition_ =\n options.transition === undefined ? 250 : options.transition;\n\n /**\n * Lookup of start times for rendering transitions. If the start time is\n * equal to -1, the transition is complete.\n * @type {Object}\n */\n this.transitionStarts_ = {};\n\n /**\n * @type {boolean}\n */\n this.interpolate = !!options.interpolate;\n }\n\n /**\n * @protected\n */\n changed() {\n this.dispatchEvent(EventType.CHANGE);\n }\n\n /**\n * Called by the tile cache when the tile is removed from the cache due to expiry\n */\n release() {\n if (this.state === TileState.ERROR) {\n // to remove the `change` listener on this tile in `ol/TileQueue#handleTileChange`\n this.setState(TileState.EMPTY);\n }\n }\n\n /**\n * @return {string} Key.\n */\n getKey() {\n return this.key + '/' + this.tileCoord;\n }\n\n /**\n * Get the interim tile most suitable for rendering using the chain of interim\n * tiles. This corresponds to the most recent tile that has been loaded, if no\n * such tile exists, the original tile is returned.\n * @return {!Tile} Best tile for rendering.\n */\n getInterimTile() {\n if (!this.interimTile) {\n //empty chain\n return this;\n }\n let tile = this.interimTile;\n\n // find the first loaded tile and return it. Since the chain is sorted in\n // decreasing order of creation time, there is no need to search the remainder\n // of the list (all those tiles correspond to older requests and will be\n // cleaned up by refreshInterimChain)\n do {\n if (tile.getState() == TileState.LOADED) {\n // Show tile immediately instead of fading it in after loading, because\n // the interim tile is in place already\n this.transition_ = 0;\n return tile;\n }\n tile = tile.interimTile;\n } while (tile);\n\n // we can not find a better tile\n return this;\n }\n\n /**\n * Goes through the chain of interim tiles and discards sections of the chain\n * that are no longer relevant.\n */\n refreshInterimChain() {\n if (!this.interimTile) {\n return;\n }\n\n let tile = this.interimTile;\n\n /**\n * @type {Tile}\n */\n let prev = this;\n\n do {\n if (tile.getState() == TileState.LOADED) {\n //we have a loaded tile, we can discard the rest of the list\n //we would could abort any LOADING tile request\n //older than this tile (i.e. any LOADING tile following this entry in the chain)\n tile.interimTile = null;\n break;\n } else if (tile.getState() == TileState.LOADING) {\n //keep this LOADING tile any loaded tiles later in the chain are\n //older than this tile, so we're still interested in the request\n prev = tile;\n } else if (tile.getState() == TileState.IDLE) {\n //the head of the list is the most current tile, we don't need\n //to start any other requests for this chain\n prev.interimTile = tile.interimTile;\n } else {\n prev = tile;\n }\n tile = prev.interimTile;\n } while (tile);\n }\n\n /**\n * Get the tile coordinate for this tile.\n * @return {import(\"./tilecoord.js\").TileCoord} The tile coordinate.\n * @api\n */\n getTileCoord() {\n return this.tileCoord;\n }\n\n /**\n * @return {import(\"./TileState.js\").default} State.\n */\n getState() {\n return this.state;\n }\n\n /**\n * Sets the state of this tile. If you write your own {@link module:ol/Tile~LoadFunction tileLoadFunction} ,\n * it is important to set the state correctly to {@link module:ol/TileState~ERROR}\n * when the tile cannot be loaded. Otherwise the tile cannot be removed from\n * the tile queue and will block other requests.\n * @param {import(\"./TileState.js\").default} state State.\n * @api\n */\n setState(state) {\n if (this.state !== TileState.ERROR && this.state > state) {\n throw new Error('Tile load sequence violation');\n }\n this.state = state;\n this.changed();\n }\n\n /**\n * Load the image or retry if loading previously failed.\n * Loading is taken care of by the tile queue, and calling this method is\n * only needed for preloading or for reloading in case of an error.\n * @abstract\n * @api\n */\n load() {\n abstract();\n }\n\n /**\n * Get the alpha value for rendering.\n * @param {string} id An id for the renderer.\n * @param {number} time The render frame time.\n * @return {number} A number between 0 and 1.\n */\n getAlpha(id, time) {\n if (!this.transition_) {\n return 1;\n }\n\n let start = this.transitionStarts_[id];\n if (!start) {\n start = time;\n this.transitionStarts_[id] = start;\n } else if (start === -1) {\n return 1;\n }\n\n const delta = time - start + 1000 / 60; // avoid rendering at 0\n if (delta >= this.transition_) {\n return 1;\n }\n return easeIn(delta / this.transition_);\n }\n\n /**\n * Determine if a tile is in an alpha transition. A tile is considered in\n * transition if tile.getAlpha() has not yet been called or has been called\n * and returned 1.\n * @param {string} id An id for the renderer.\n * @return {boolean} The tile is in transition.\n */\n inTransition(id) {\n if (!this.transition_) {\n return false;\n }\n return this.transitionStarts_[id] !== -1;\n }\n\n /**\n * Mark a transition as complete.\n * @param {string} id An id for the renderer.\n */\n endTransition(id) {\n if (this.transition_) {\n this.transitionStarts_[id] = -1;\n }\n }\n}\n\nexport default Tile;\n","/**\n * @module ol/has\n */\n\nconst ua =\n typeof navigator !== 'undefined' && typeof navigator.userAgent !== 'undefined'\n ? navigator.userAgent.toLowerCase()\n : '';\n\n/**\n * User agent string says we are dealing with Firefox as browser.\n * @type {boolean}\n */\nexport const FIREFOX = ua.includes('firefox');\n\n/**\n * User agent string says we are dealing with Safari as browser.\n * @type {boolean}\n */\nexport const SAFARI = ua.includes('safari') && !ua.includes('chrom');\n\n/**\n * https://bugs.webkit.org/show_bug.cgi?id=237906\n * @type {boolean}\n */\nexport const SAFARI_BUG_237906 =\n SAFARI &&\n (ua.includes('version/15.4') ||\n /cpu (os|iphone os) 15_4 like mac os x/.test(ua));\n\n/**\n * User agent string says we are dealing with a WebKit engine.\n * @type {boolean}\n */\nexport const WEBKIT = ua.includes('webkit') && !ua.includes('edge');\n\n/**\n * User agent string says we are dealing with a Mac as platform.\n * @type {boolean}\n */\nexport const MAC = ua.includes('macintosh');\n\n/**\n * The ratio between physical pixels and device-independent pixels\n * (dips) on the device (`window.devicePixelRatio`).\n * @const\n * @type {number}\n * @api\n */\nexport const DEVICE_PIXEL_RATIO =\n typeof devicePixelRatio !== 'undefined' ? devicePixelRatio : 1;\n\n/**\n * The execution context is a worker with OffscreenCanvas available.\n * @const\n * @type {boolean}\n */\nexport const WORKER_OFFSCREEN_CANVAS =\n typeof WorkerGlobalScope !== 'undefined' &&\n typeof OffscreenCanvas !== 'undefined' &&\n self instanceof WorkerGlobalScope; //eslint-disable-line\n\n/**\n * Image.prototype.decode() is supported.\n * @type {boolean}\n */\nexport const IMAGE_DECODE =\n typeof Image !== 'undefined' && Image.prototype.decode;\n\n/**\n * @type {boolean}\n */\nexport const PASSIVE_EVENT_LISTENERS = (function () {\n let passive = false;\n try {\n const options = Object.defineProperty({}, 'passive', {\n get: function () {\n passive = true;\n },\n });\n\n window.addEventListener('_', null, options);\n window.removeEventListener('_', null, options);\n } catch (error) {\n // passive not supported\n }\n return passive;\n})();\n","import {WORKER_OFFSCREEN_CANVAS} from './has.js';\n\n/**\n * @module ol/dom\n */\n\n//FIXME Move this function to the canvas module\n/**\n * Create an html canvas element and returns its 2d context.\n * @param {number} [width] Canvas width.\n * @param {number} [height] Canvas height.\n * @param {Array} [canvasPool] Canvas pool to take existing canvas from.\n * @param {CanvasRenderingContext2DSettings} [settings] CanvasRenderingContext2DSettings\n * @return {CanvasRenderingContext2D} The context.\n */\nexport function createCanvasContext2D(width, height, canvasPool, settings) {\n /** @type {HTMLCanvasElement|OffscreenCanvas} */\n let canvas;\n if (canvasPool && canvasPool.length) {\n canvas = canvasPool.shift();\n } else if (WORKER_OFFSCREEN_CANVAS) {\n canvas = new OffscreenCanvas(width || 300, height || 300);\n } else {\n canvas = document.createElement('canvas');\n }\n if (width) {\n canvas.width = width;\n }\n if (height) {\n canvas.height = height;\n }\n //FIXME Allow OffscreenCanvasRenderingContext2D as return type\n return /** @type {CanvasRenderingContext2D} */ (\n canvas.getContext('2d', settings)\n );\n}\n\n/**\n * Releases canvas memory to avoid exceeding memory limits in Safari.\n * See https://pqina.nl/blog/total-canvas-memory-use-exceeds-the-maximum-limit/\n * @param {CanvasRenderingContext2D} context Context.\n */\nexport function releaseCanvas(context) {\n const canvas = context.canvas;\n canvas.width = 1;\n canvas.height = 1;\n context.clearRect(0, 0, 1, 1);\n}\n\n/**\n * Get the current computed width for the given element including margin,\n * padding and border.\n * Equivalent to jQuery's `$(el).outerWidth(true)`.\n * @param {!HTMLElement} element Element.\n * @return {number} The width.\n */\nexport function outerWidth(element) {\n let width = element.offsetWidth;\n const style = getComputedStyle(element);\n width += parseInt(style.marginLeft, 10) + parseInt(style.marginRight, 10);\n\n return width;\n}\n\n/**\n * Get the current computed height for the given element including margin,\n * padding and border.\n * Equivalent to jQuery's `$(el).outerHeight(true)`.\n * @param {!HTMLElement} element Element.\n * @return {number} The height.\n */\nexport function outerHeight(element) {\n let height = element.offsetHeight;\n const style = getComputedStyle(element);\n height += parseInt(style.marginTop, 10) + parseInt(style.marginBottom, 10);\n\n return height;\n}\n\n/**\n * @param {Node} newNode Node to replace old node\n * @param {Node} oldNode The node to be replaced\n */\nexport function replaceNode(newNode, oldNode) {\n const parent = oldNode.parentNode;\n if (parent) {\n parent.replaceChild(newNode, oldNode);\n }\n}\n\n/**\n * @param {Node} node The node to remove.\n * @return {Node|null} The node that was removed or null.\n */\nexport function removeNode(node) {\n return node && node.parentNode ? node.parentNode.removeChild(node) : null;\n}\n\n/**\n * @param {Node} node The node to remove the children from.\n */\nexport function removeChildren(node) {\n while (node.lastChild) {\n node.removeChild(node.lastChild);\n }\n}\n\n/**\n * Transform the children of a parent node so they match the\n * provided list of children. This function aims to efficiently\n * remove, add, and reorder child nodes while maintaining a simple\n * implementation (it is not guaranteed to minimize DOM operations).\n * @param {Node} node The parent node whose children need reworking.\n * @param {Array} children The desired children.\n */\nexport function replaceChildren(node, children) {\n const oldChildren = node.childNodes;\n\n for (let i = 0; true; ++i) {\n const oldChild = oldChildren[i];\n const newChild = children[i];\n\n // check if our work is done\n if (!oldChild && !newChild) {\n break;\n }\n\n // check if children match\n if (oldChild === newChild) {\n continue;\n }\n\n // check if a new child needs to be added\n if (!oldChild) {\n node.appendChild(newChild);\n continue;\n }\n\n // check if an old child needs to be removed\n if (!newChild) {\n node.removeChild(oldChild);\n --i;\n continue;\n }\n\n // reorder\n node.insertBefore(newChild, oldChild);\n }\n}\n","/**\n * @module ol/DataTile\n */\nimport Tile from './Tile.js';\nimport TileState from './TileState.js';\nimport {createCanvasContext2D} from './dom.js';\n\n/**\n * @typedef {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement} ImageLike\n */\n\n/**\n * @typedef {Uint8Array|Uint8ClampedArray|Float32Array|DataView} ArrayLike\n */\n\n/**\n * Data that can be used with a DataTile.\n * @typedef {ArrayLike|ImageLike} Data\n */\n\n/**\n * @param {Data} data Tile data.\n * @return {ImageLike|null} The image-like data.\n */\nexport function asImageLike(data) {\n return data instanceof Image ||\n data instanceof HTMLCanvasElement ||\n data instanceof HTMLVideoElement\n ? data\n : null;\n}\n\n/**\n * @param {Data} data Tile data.\n * @return {ArrayLike|null} The array-like data.\n */\nexport function asArrayLike(data) {\n return data instanceof Uint8Array ||\n data instanceof Uint8ClampedArray ||\n data instanceof Float32Array ||\n data instanceof DataView\n ? data\n : null;\n}\n\n/**\n * @type {CanvasRenderingContext2D|null}\n */\nlet sharedContext = null;\n\n/**\n * @param {ImageLike} image The image.\n * @return {Uint8ClampedArray} The data.\n */\nexport function toArray(image) {\n if (!sharedContext) {\n sharedContext = createCanvasContext2D(\n image.width,\n image.height,\n undefined,\n {willReadFrequently: true}\n );\n }\n const canvas = sharedContext.canvas;\n const width = image.width;\n if (canvas.width !== width) {\n canvas.width = width;\n }\n const height = image.height;\n if (canvas.height !== height) {\n canvas.height = height;\n }\n sharedContext.clearRect(0, 0, width, height);\n sharedContext.drawImage(image, 0, 0);\n return sharedContext.getImageData(0, 0, width, height).data;\n}\n\n/**\n * @type {import('./size.js').Size}\n */\nconst defaultSize = [256, 256];\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n * @property {function(): Promise} loader Data loader. For loaders that generate images,\n * the promise should not resolve until the image is loaded.\n * @property {number} [transition=250] A duration for tile opacity\n * transitions in milliseconds. A duration of 0 disables the opacity transition.\n * @property {boolean} [interpolate=false] Use interpolated values when resampling. By default,\n * the nearest neighbor is used when resampling.\n * @property {import('./size.js').Size} [size=[256, 256]] Tile size.\n * @api\n */\n\nclass DataTile extends Tile {\n /**\n * @param {Options} options Tile options.\n */\n constructor(options) {\n const state = TileState.IDLE;\n\n super(options.tileCoord, state, {\n transition: options.transition,\n interpolate: options.interpolate,\n });\n\n /**\n * @type {function(): Promise}\n * @private\n */\n this.loader_ = options.loader;\n\n /**\n * @type {Data}\n * @private\n */\n this.data_ = null;\n\n /**\n * @type {Error}\n * @private\n */\n this.error_ = null;\n\n /**\n * @type {import('./size.js').Size|null}\n * @private\n */\n this.size_ = options.size || null;\n }\n\n /**\n * Get the tile size.\n * @return {import('./size.js').Size} Tile size.\n */\n getSize() {\n if (this.size_) {\n return this.size_;\n }\n const imageData = asImageLike(this.data_);\n if (imageData) {\n return [imageData.width, imageData.height];\n }\n return defaultSize;\n }\n\n /**\n * Get the data for the tile.\n * @return {Data} Tile data.\n * @api\n */\n getData() {\n return this.data_;\n }\n\n /**\n * Get any loading error.\n * @return {Error} Loading error.\n * @api\n */\n getError() {\n return this.error_;\n }\n\n /**\n * Load not yet loaded URI.\n * @api\n */\n load() {\n if (this.state !== TileState.IDLE && this.state !== TileState.ERROR) {\n return;\n }\n this.state = TileState.LOADING;\n this.changed();\n\n const self = this;\n this.loader_()\n .then(function (data) {\n self.data_ = data;\n self.state = TileState.LOADED;\n self.changed();\n })\n .catch(function (error) {\n self.error_ = error;\n self.state = TileState.ERROR;\n self.changed();\n });\n }\n}\n\nexport default DataTile;\n","/**\n * @module ol/asserts\n */\nimport AssertionError from './AssertionError.js';\n\n/**\n * @param {*} assertion Assertion we expected to be truthy.\n * @param {number} errorCode Error code.\n */\nexport function assert(assertion, errorCode) {\n if (!assertion) {\n throw new AssertionError(errorCode);\n }\n}\n","/**\n * @module ol/Feature\n */\nimport BaseObject from './Object.js';\nimport EventType from './events/EventType.js';\nimport {assert} from './asserts.js';\nimport {listen, unlistenByKey} from './events.js';\n\n/**\n * @typedef {typeof Feature|typeof import(\"./render/Feature.js\").default} FeatureClass\n */\n\n/**\n * @typedef {Feature|import(\"./render/Feature.js\").default} FeatureLike\n */\n\n/***\n * @template Return\n * @typedef {import(\"./Observable\").OnSignature &\n * import(\"./Observable\").OnSignature &\n * import(\"./Observable\").CombinedOnSignature} FeatureOnSignature\n */\n\n/***\n * @template Geometry\n * @typedef {Object & { geometry?: Geometry }} ObjectWithGeometry\n */\n\n/**\n * @classdesc\n * A vector object for geographic features with a geometry and other\n * attribute properties, similar to the features in vector file formats like\n * GeoJSON.\n *\n * Features can be styled individually with `setStyle`; otherwise they use the\n * style of their vector layer.\n *\n * Note that attribute properties are set as {@link module:ol/Object~BaseObject} properties on\n * the feature object, so they are observable, and have get/set accessors.\n *\n * Typically, a feature has a single geometry property. You can set the\n * geometry using the `setGeometry` method and get it with `getGeometry`.\n * It is possible to store more than one geometry on a feature using attribute\n * properties. By default, the geometry used for rendering is identified by\n * the property name `geometry`. If you want to use another geometry property\n * for rendering, use the `setGeometryName` method to change the attribute\n * property associated with the geometry for the feature. For example:\n *\n * ```js\n *\n * import Feature from 'ol/Feature.js';\n * import Polygon from 'ol/geom/Polygon.js';\n * import Point from 'ol/geom/Point.js';\n *\n * const feature = new Feature({\n * geometry: new Polygon(polyCoords),\n * labelPoint: new Point(labelCoords),\n * name: 'My Polygon',\n * });\n *\n * // get the polygon geometry\n * const poly = feature.getGeometry();\n *\n * // Render the feature as a point using the coordinates from labelPoint\n * feature.setGeometryName('labelPoint');\n *\n * // get the point geometry\n * const point = feature.getGeometry();\n * ```\n *\n * @api\n * @template {import(\"./geom/Geometry.js\").default} [Geometry=import(\"./geom/Geometry.js\").default]\n */\nclass Feature extends BaseObject {\n /**\n * @param {Geometry|ObjectWithGeometry} [geometryOrProperties]\n * You may pass a Geometry object directly, or an object literal containing\n * properties. If you pass an object literal, you may include a Geometry\n * associated with a `geometry` key.\n */\n constructor(geometryOrProperties) {\n super();\n\n /***\n * @type {FeatureOnSignature}\n */\n this.on;\n\n /***\n * @type {FeatureOnSignature}\n */\n this.once;\n\n /***\n * @type {FeatureOnSignature}\n */\n this.un;\n\n /**\n * @private\n * @type {number|string|undefined}\n */\n this.id_ = undefined;\n\n /**\n * @type {string}\n * @private\n */\n this.geometryName_ = 'geometry';\n\n /**\n * User provided style.\n * @private\n * @type {import(\"./style/Style.js\").StyleLike}\n */\n this.style_ = null;\n\n /**\n * @private\n * @type {import(\"./style/Style.js\").StyleFunction|undefined}\n */\n this.styleFunction_ = undefined;\n\n /**\n * @private\n * @type {?import(\"./events.js\").EventsKey}\n */\n this.geometryChangeKey_ = null;\n\n this.addChangeListener(this.geometryName_, this.handleGeometryChanged_);\n\n if (geometryOrProperties) {\n if (\n typeof (\n /** @type {?} */ (geometryOrProperties).getSimplifiedGeometry\n ) === 'function'\n ) {\n const geometry = /** @type {Geometry} */ (geometryOrProperties);\n this.setGeometry(geometry);\n } else {\n /** @type {Object} */\n const properties = geometryOrProperties;\n this.setProperties(properties);\n }\n }\n }\n\n /**\n * Clone this feature. If the original feature has a geometry it\n * is also cloned. The feature id is not set in the clone.\n * @return {Feature} The clone.\n * @api\n */\n clone() {\n const clone = /** @type {Feature} */ (\n new Feature(this.hasProperties() ? this.getProperties() : null)\n );\n clone.setGeometryName(this.getGeometryName());\n const geometry = this.getGeometry();\n if (geometry) {\n clone.setGeometry(/** @type {Geometry} */ (geometry.clone()));\n }\n const style = this.getStyle();\n if (style) {\n clone.setStyle(style);\n }\n return clone;\n }\n\n /**\n * Get the feature's default geometry. A feature may have any number of named\n * geometries. The \"default\" geometry (the one that is rendered by default) is\n * set when calling {@link module:ol/Feature~Feature#setGeometry}.\n * @return {Geometry|undefined} The default geometry for the feature.\n * @api\n * @observable\n */\n getGeometry() {\n return /** @type {Geometry|undefined} */ (this.get(this.geometryName_));\n }\n\n /**\n * Get the feature identifier. This is a stable identifier for the feature and\n * is either set when reading data from a remote source or set explicitly by\n * calling {@link module:ol/Feature~Feature#setId}.\n * @return {number|string|undefined} Id.\n * @api\n */\n getId() {\n return this.id_;\n }\n\n /**\n * Get the name of the feature's default geometry. By default, the default\n * geometry is named `geometry`.\n * @return {string} Get the property name associated with the default geometry\n * for this feature.\n * @api\n */\n getGeometryName() {\n return this.geometryName_;\n }\n\n /**\n * Get the feature's style. Will return what was provided to the\n * {@link module:ol/Feature~Feature#setStyle} method.\n * @return {import(\"./style/Style.js\").StyleLike|undefined} The feature style.\n * @api\n */\n getStyle() {\n return this.style_;\n }\n\n /**\n * Get the feature's style function.\n * @return {import(\"./style/Style.js\").StyleFunction|undefined} Return a function\n * representing the current style of this feature.\n * @api\n */\n getStyleFunction() {\n return this.styleFunction_;\n }\n\n /**\n * @private\n */\n handleGeometryChange_() {\n this.changed();\n }\n\n /**\n * @private\n */\n handleGeometryChanged_() {\n if (this.geometryChangeKey_) {\n unlistenByKey(this.geometryChangeKey_);\n this.geometryChangeKey_ = null;\n }\n const geometry = this.getGeometry();\n if (geometry) {\n this.geometryChangeKey_ = listen(\n geometry,\n EventType.CHANGE,\n this.handleGeometryChange_,\n this\n );\n }\n this.changed();\n }\n\n /**\n * Set the default geometry for the feature. This will update the property\n * with the name returned by {@link module:ol/Feature~Feature#getGeometryName}.\n * @param {Geometry|undefined} geometry The new geometry.\n * @api\n * @observable\n */\n setGeometry(geometry) {\n this.set(this.geometryName_, geometry);\n }\n\n /**\n * Set the style for the feature to override the layer style. This can be a\n * single style object, an array of styles, or a function that takes a\n * resolution and returns an array of styles. To unset the feature style, call\n * `setStyle()` without arguments or a falsey value.\n * @param {import(\"./style/Style.js\").StyleLike} [style] Style for this feature.\n * @api\n * @fires module:ol/events/Event~BaseEvent#event:change\n */\n setStyle(style) {\n this.style_ = style;\n this.styleFunction_ = !style ? undefined : createStyleFunction(style);\n this.changed();\n }\n\n /**\n * Set the feature id. The feature id is considered stable and may be used when\n * requesting features or comparing identifiers returned from a remote source.\n * The feature id can be used with the\n * {@link module:ol/source/Vector~VectorSource#getFeatureById} method.\n * @param {number|string|undefined} id The feature id.\n * @api\n * @fires module:ol/events/Event~BaseEvent#event:change\n */\n setId(id) {\n this.id_ = id;\n this.changed();\n }\n\n /**\n * Set the property name to be used when getting the feature's default geometry.\n * When calling {@link module:ol/Feature~Feature#getGeometry}, the value of the property with\n * this name will be returned.\n * @param {string} name The property name of the default geometry.\n * @api\n */\n setGeometryName(name) {\n this.removeChangeListener(this.geometryName_, this.handleGeometryChanged_);\n this.geometryName_ = name;\n this.addChangeListener(this.geometryName_, this.handleGeometryChanged_);\n this.handleGeometryChanged_();\n }\n}\n\n/**\n * Convert the provided object into a feature style function. Functions passed\n * through unchanged. Arrays of Style or single style objects wrapped\n * in a new feature style function.\n * @param {!import(\"./style/Style.js\").StyleFunction|!Array|!import(\"./style/Style.js\").default} obj\n * A feature style function, a single style, or an array of styles.\n * @return {import(\"./style/Style.js\").StyleFunction} A style function.\n */\nexport function createStyleFunction(obj) {\n if (typeof obj === 'function') {\n return obj;\n }\n /**\n * @type {Array}\n */\n let styles;\n if (Array.isArray(obj)) {\n styles = obj;\n } else {\n assert(typeof (/** @type {?} */ (obj).getZIndex) === 'function', 41); // Expected an `import(\"./style/Style.js\").Style` or an array of `import(\"./style/Style.js\").Style`\n const style = /** @type {import(\"./style/Style.js\").default} */ (obj);\n styles = [style];\n }\n return function () {\n return styles;\n };\n}\nexport default Feature;\n","/**\n * @module ol/transform\n */\nimport {WORKER_OFFSCREEN_CANVAS} from './has.js';\nimport {assert} from './asserts.js';\n\n/**\n * An array representing an affine 2d transformation for use with\n * {@link module:ol/transform} functions. The array has 6 elements.\n * @typedef {!Array} Transform\n * @api\n */\n\n/**\n * Collection of affine 2d transformation functions. The functions work on an\n * array of 6 elements. The element order is compatible with the [SVGMatrix\n * interface](https://developer.mozilla.org/en-US/docs/Web/API/SVGMatrix) and is\n * a subset (elements a to f) of a 3×3 matrix:\n * ```\n * [ a c e ]\n * [ b d f ]\n * [ 0 0 1 ]\n * ```\n */\n\n/**\n * @private\n * @type {Transform}\n */\nconst tmp_ = new Array(6);\n\n/**\n * Create an identity transform.\n * @return {!Transform} Identity transform.\n */\nexport function create() {\n return [1, 0, 0, 1, 0, 0];\n}\n\n/**\n * Resets the given transform to an identity transform.\n * @param {!Transform} transform Transform.\n * @return {!Transform} Transform.\n */\nexport function reset(transform) {\n return set(transform, 1, 0, 0, 1, 0, 0);\n}\n\n/**\n * Multiply the underlying matrices of two transforms and return the result in\n * the first transform.\n * @param {!Transform} transform1 Transform parameters of matrix 1.\n * @param {!Transform} transform2 Transform parameters of matrix 2.\n * @return {!Transform} transform1 multiplied with transform2.\n */\nexport function multiply(transform1, transform2) {\n const a1 = transform1[0];\n const b1 = transform1[1];\n const c1 = transform1[2];\n const d1 = transform1[3];\n const e1 = transform1[4];\n const f1 = transform1[5];\n const a2 = transform2[0];\n const b2 = transform2[1];\n const c2 = transform2[2];\n const d2 = transform2[3];\n const e2 = transform2[4];\n const f2 = transform2[5];\n\n transform1[0] = a1 * a2 + c1 * b2;\n transform1[1] = b1 * a2 + d1 * b2;\n transform1[2] = a1 * c2 + c1 * d2;\n transform1[3] = b1 * c2 + d1 * d2;\n transform1[4] = a1 * e2 + c1 * f2 + e1;\n transform1[5] = b1 * e2 + d1 * f2 + f1;\n\n return transform1;\n}\n\n/**\n * Set the transform components a-f on a given transform.\n * @param {!Transform} transform Transform.\n * @param {number} a The a component of the transform.\n * @param {number} b The b component of the transform.\n * @param {number} c The c component of the transform.\n * @param {number} d The d component of the transform.\n * @param {number} e The e component of the transform.\n * @param {number} f The f component of the transform.\n * @return {!Transform} Matrix with transform applied.\n */\nexport function set(transform, a, b, c, d, e, f) {\n transform[0] = a;\n transform[1] = b;\n transform[2] = c;\n transform[3] = d;\n transform[4] = e;\n transform[5] = f;\n return transform;\n}\n\n/**\n * Set transform on one matrix from another matrix.\n * @param {!Transform} transform1 Matrix to set transform to.\n * @param {!Transform} transform2 Matrix to set transform from.\n * @return {!Transform} transform1 with transform from transform2 applied.\n */\nexport function setFromArray(transform1, transform2) {\n transform1[0] = transform2[0];\n transform1[1] = transform2[1];\n transform1[2] = transform2[2];\n transform1[3] = transform2[3];\n transform1[4] = transform2[4];\n transform1[5] = transform2[5];\n return transform1;\n}\n\n/**\n * Transforms the given coordinate with the given transform returning the\n * resulting, transformed coordinate. The coordinate will be modified in-place.\n *\n * @param {Transform} transform The transformation.\n * @param {import(\"./coordinate.js\").Coordinate|import(\"./pixel.js\").Pixel} coordinate The coordinate to transform.\n * @return {import(\"./coordinate.js\").Coordinate|import(\"./pixel.js\").Pixel} return coordinate so that operations can be\n * chained together.\n */\nexport function apply(transform, coordinate) {\n const x = coordinate[0];\n const y = coordinate[1];\n coordinate[0] = transform[0] * x + transform[2] * y + transform[4];\n coordinate[1] = transform[1] * x + transform[3] * y + transform[5];\n return coordinate;\n}\n\n/**\n * Applies rotation to the given transform.\n * @param {!Transform} transform Transform.\n * @param {number} angle Angle in radians.\n * @return {!Transform} The rotated transform.\n */\nexport function rotate(transform, angle) {\n const cos = Math.cos(angle);\n const sin = Math.sin(angle);\n return multiply(transform, set(tmp_, cos, sin, -sin, cos, 0, 0));\n}\n\n/**\n * Applies scale to a given transform.\n * @param {!Transform} transform Transform.\n * @param {number} x Scale factor x.\n * @param {number} y Scale factor y.\n * @return {!Transform} The scaled transform.\n */\nexport function scale(transform, x, y) {\n return multiply(transform, set(tmp_, x, 0, 0, y, 0, 0));\n}\n\n/**\n * Creates a scale transform.\n * @param {!Transform} target Transform to overwrite.\n * @param {number} x Scale factor x.\n * @param {number} y Scale factor y.\n * @return {!Transform} The scale transform.\n */\nexport function makeScale(target, x, y) {\n return set(target, x, 0, 0, y, 0, 0);\n}\n\n/**\n * Applies translation to the given transform.\n * @param {!Transform} transform Transform.\n * @param {number} dx Translation x.\n * @param {number} dy Translation y.\n * @return {!Transform} The translated transform.\n */\nexport function translate(transform, dx, dy) {\n return multiply(transform, set(tmp_, 1, 0, 0, 1, dx, dy));\n}\n\n/**\n * Creates a composite transform given an initial translation, scale, rotation, and\n * final translation (in that order only, not commutative).\n * @param {!Transform} transform The transform (will be modified in place).\n * @param {number} dx1 Initial translation x.\n * @param {number} dy1 Initial translation y.\n * @param {number} sx Scale factor x.\n * @param {number} sy Scale factor y.\n * @param {number} angle Rotation (in counter-clockwise radians).\n * @param {number} dx2 Final translation x.\n * @param {number} dy2 Final translation y.\n * @return {!Transform} The composite transform.\n */\nexport function compose(transform, dx1, dy1, sx, sy, angle, dx2, dy2) {\n const sin = Math.sin(angle);\n const cos = Math.cos(angle);\n transform[0] = sx * cos;\n transform[1] = sy * sin;\n transform[2] = -sx * sin;\n transform[3] = sy * cos;\n transform[4] = dx2 * sx * cos - dy2 * sx * sin + dx1;\n transform[5] = dx2 * sy * sin + dy2 * sy * cos + dy1;\n return transform;\n}\n\n/**\n * Creates a composite transform given an initial translation, scale, rotation, and\n * final translation (in that order only, not commutative). The resulting transform\n * string can be applied as `transform` property of an HTMLElement's style.\n * @param {number} dx1 Initial translation x.\n * @param {number} dy1 Initial translation y.\n * @param {number} sx Scale factor x.\n * @param {number} sy Scale factor y.\n * @param {number} angle Rotation (in counter-clockwise radians).\n * @param {number} dx2 Final translation x.\n * @param {number} dy2 Final translation y.\n * @return {string} The composite css transform.\n * @api\n */\nexport function composeCssTransform(dx1, dy1, sx, sy, angle, dx2, dy2) {\n return toString(compose(create(), dx1, dy1, sx, sy, angle, dx2, dy2));\n}\n\n/**\n * Invert the given transform.\n * @param {!Transform} source The source transform to invert.\n * @return {!Transform} The inverted (source) transform.\n */\nexport function invert(source) {\n return makeInverse(source, source);\n}\n\n/**\n * Invert the given transform.\n * @param {!Transform} target Transform to be set as the inverse of\n * the source transform.\n * @param {!Transform} source The source transform to invert.\n * @return {!Transform} The inverted (target) transform.\n */\nexport function makeInverse(target, source) {\n const det = determinant(source);\n assert(det !== 0, 32); // Transformation matrix cannot be inverted\n\n const a = source[0];\n const b = source[1];\n const c = source[2];\n const d = source[3];\n const e = source[4];\n const f = source[5];\n\n target[0] = d / det;\n target[1] = -b / det;\n target[2] = -c / det;\n target[3] = a / det;\n target[4] = (c * f - d * e) / det;\n target[5] = -(a * f - b * e) / det;\n\n return target;\n}\n\n/**\n * Returns the determinant of the given matrix.\n * @param {!Transform} mat Matrix.\n * @return {number} Determinant.\n */\nexport function determinant(mat) {\n return mat[0] * mat[3] - mat[1] * mat[2];\n}\n\n/**\n * @type {HTMLElement}\n * @private\n */\nlet transformStringDiv;\n\n/**\n * A rounded string version of the transform. This can be used\n * for CSS transforms.\n * @param {!Transform} mat Matrix.\n * @return {string} The transform as a string.\n */\nexport function toString(mat) {\n const transformString = 'matrix(' + mat.join(', ') + ')';\n if (WORKER_OFFSCREEN_CANVAS) {\n return transformString;\n }\n const node =\n transformStringDiv || (transformStringDiv = document.createElement('div'));\n node.style.transform = transformString;\n return node.style.transform;\n}\n","/**\n * @module ol/extent/Relationship\n */\n\n/**\n * Relationship to an extent.\n * @enum {number}\n */\nexport default {\n UNKNOWN: 0,\n INTERSECTING: 1,\n ABOVE: 2,\n RIGHT: 4,\n BELOW: 8,\n LEFT: 16,\n};\n","/**\n * @module ol/extent\n */\nimport Relationship from './extent/Relationship.js';\nimport {assert} from './asserts.js';\n\n/**\n * An array of numbers representing an extent: `[minx, miny, maxx, maxy]`.\n * @typedef {Array} Extent\n * @api\n */\n\n/**\n * Extent corner.\n * @typedef {'bottom-left' | 'bottom-right' | 'top-left' | 'top-right'} Corner\n */\n\n/**\n * Build an extent that includes all given coordinates.\n *\n * @param {Array} coordinates Coordinates.\n * @return {Extent} Bounding extent.\n * @api\n */\nexport function boundingExtent(coordinates) {\n const extent = createEmpty();\n for (let i = 0, ii = coordinates.length; i < ii; ++i) {\n extendCoordinate(extent, coordinates[i]);\n }\n return extent;\n}\n\n/**\n * @param {Array} xs Xs.\n * @param {Array} ys Ys.\n * @param {Extent} [dest] Destination extent.\n * @private\n * @return {Extent} Extent.\n */\nfunction _boundingExtentXYs(xs, ys, dest) {\n const minX = Math.min.apply(null, xs);\n const minY = Math.min.apply(null, ys);\n const maxX = Math.max.apply(null, xs);\n const maxY = Math.max.apply(null, ys);\n return createOrUpdate(minX, minY, maxX, maxY, dest);\n}\n\n/**\n * Return extent increased by the provided value.\n * @param {Extent} extent Extent.\n * @param {number} value The amount by which the extent should be buffered.\n * @param {Extent} [dest] Extent.\n * @return {Extent} Extent.\n * @api\n */\nexport function buffer(extent, value, dest) {\n if (dest) {\n dest[0] = extent[0] - value;\n dest[1] = extent[1] - value;\n dest[2] = extent[2] + value;\n dest[3] = extent[3] + value;\n return dest;\n }\n return [\n extent[0] - value,\n extent[1] - value,\n extent[2] + value,\n extent[3] + value,\n ];\n}\n\n/**\n * Creates a clone of an extent.\n *\n * @param {Extent} extent Extent to clone.\n * @param {Extent} [dest] Extent.\n * @return {Extent} The clone.\n */\nexport function clone(extent, dest) {\n if (dest) {\n dest[0] = extent[0];\n dest[1] = extent[1];\n dest[2] = extent[2];\n dest[3] = extent[3];\n return dest;\n }\n return extent.slice();\n}\n\n/**\n * @param {Extent} extent Extent.\n * @param {number} x X.\n * @param {number} y Y.\n * @return {number} Closest squared distance.\n */\nexport function closestSquaredDistanceXY(extent, x, y) {\n let dx, dy;\n if (x < extent[0]) {\n dx = extent[0] - x;\n } else if (extent[2] < x) {\n dx = x - extent[2];\n } else {\n dx = 0;\n }\n if (y < extent[1]) {\n dy = extent[1] - y;\n } else if (extent[3] < y) {\n dy = y - extent[3];\n } else {\n dy = 0;\n }\n return dx * dx + dy * dy;\n}\n\n/**\n * Check if the passed coordinate is contained or on the edge of the extent.\n *\n * @param {Extent} extent Extent.\n * @param {import(\"./coordinate.js\").Coordinate} coordinate Coordinate.\n * @return {boolean} The coordinate is contained in the extent.\n * @api\n */\nexport function containsCoordinate(extent, coordinate) {\n return containsXY(extent, coordinate[0], coordinate[1]);\n}\n\n/**\n * Check if one extent contains another.\n *\n * An extent is deemed contained if it lies completely within the other extent,\n * including if they share one or more edges.\n *\n * @param {Extent} extent1 Extent 1.\n * @param {Extent} extent2 Extent 2.\n * @return {boolean} The second extent is contained by or on the edge of the\n * first.\n * @api\n */\nexport function containsExtent(extent1, extent2) {\n return (\n extent1[0] <= extent2[0] &&\n extent2[2] <= extent1[2] &&\n extent1[1] <= extent2[1] &&\n extent2[3] <= extent1[3]\n );\n}\n\n/**\n * Check if the passed coordinate is contained or on the edge of the extent.\n *\n * @param {Extent} extent Extent.\n * @param {number} x X coordinate.\n * @param {number} y Y coordinate.\n * @return {boolean} The x, y values are contained in the extent.\n * @api\n */\nexport function containsXY(extent, x, y) {\n return extent[0] <= x && x <= extent[2] && extent[1] <= y && y <= extent[3];\n}\n\n/**\n * Get the relationship between a coordinate and extent.\n * @param {Extent} extent The extent.\n * @param {import(\"./coordinate.js\").Coordinate} coordinate The coordinate.\n * @return {import(\"./extent/Relationship.js\").default} The relationship (bitwise compare with\n * import(\"./extent/Relationship.js\").Relationship).\n */\nexport function coordinateRelationship(extent, coordinate) {\n const minX = extent[0];\n const minY = extent[1];\n const maxX = extent[2];\n const maxY = extent[3];\n const x = coordinate[0];\n const y = coordinate[1];\n let relationship = Relationship.UNKNOWN;\n if (x < minX) {\n relationship = relationship | Relationship.LEFT;\n } else if (x > maxX) {\n relationship = relationship | Relationship.RIGHT;\n }\n if (y < minY) {\n relationship = relationship | Relationship.BELOW;\n } else if (y > maxY) {\n relationship = relationship | Relationship.ABOVE;\n }\n if (relationship === Relationship.UNKNOWN) {\n relationship = Relationship.INTERSECTING;\n }\n return relationship;\n}\n\n/**\n * Create an empty extent.\n * @return {Extent} Empty extent.\n * @api\n */\nexport function createEmpty() {\n return [Infinity, Infinity, -Infinity, -Infinity];\n}\n\n/**\n * Create a new extent or update the provided extent.\n * @param {number} minX Minimum X.\n * @param {number} minY Minimum Y.\n * @param {number} maxX Maximum X.\n * @param {number} maxY Maximum Y.\n * @param {Extent} [dest] Destination extent.\n * @return {Extent} Extent.\n */\nexport function createOrUpdate(minX, minY, maxX, maxY, dest) {\n if (dest) {\n dest[0] = minX;\n dest[1] = minY;\n dest[2] = maxX;\n dest[3] = maxY;\n return dest;\n }\n return [minX, minY, maxX, maxY];\n}\n\n/**\n * Create a new empty extent or make the provided one empty.\n * @param {Extent} [dest] Extent.\n * @return {Extent} Extent.\n */\nexport function createOrUpdateEmpty(dest) {\n return createOrUpdate(Infinity, Infinity, -Infinity, -Infinity, dest);\n}\n\n/**\n * @param {import(\"./coordinate.js\").Coordinate} coordinate Coordinate.\n * @param {Extent} [dest] Extent.\n * @return {Extent} Extent.\n */\nexport function createOrUpdateFromCoordinate(coordinate, dest) {\n const x = coordinate[0];\n const y = coordinate[1];\n return createOrUpdate(x, y, x, y, dest);\n}\n\n/**\n * @param {Array} coordinates Coordinates.\n * @param {Extent} [dest] Extent.\n * @return {Extent} Extent.\n */\nexport function createOrUpdateFromCoordinates(coordinates, dest) {\n const extent = createOrUpdateEmpty(dest);\n return extendCoordinates(extent, coordinates);\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {Extent} [dest] Extent.\n * @return {Extent} Extent.\n */\nexport function createOrUpdateFromFlatCoordinates(\n flatCoordinates,\n offset,\n end,\n stride,\n dest\n) {\n const extent = createOrUpdateEmpty(dest);\n return extendFlatCoordinates(extent, flatCoordinates, offset, end, stride);\n}\n\n/**\n * @param {Array>} rings Rings.\n * @param {Extent} [dest] Extent.\n * @return {Extent} Extent.\n */\nexport function createOrUpdateFromRings(rings, dest) {\n const extent = createOrUpdateEmpty(dest);\n return extendRings(extent, rings);\n}\n\n/**\n * Determine if two extents are equivalent.\n * @param {Extent} extent1 Extent 1.\n * @param {Extent} extent2 Extent 2.\n * @return {boolean} The two extents are equivalent.\n * @api\n */\nexport function equals(extent1, extent2) {\n return (\n extent1[0] == extent2[0] &&\n extent1[2] == extent2[2] &&\n extent1[1] == extent2[1] &&\n extent1[3] == extent2[3]\n );\n}\n\n/**\n * Determine if two extents are approximately equivalent.\n * @param {Extent} extent1 Extent 1.\n * @param {Extent} extent2 Extent 2.\n * @param {number} tolerance Tolerance in extent coordinate units.\n * @return {boolean} The two extents differ by less than the tolerance.\n */\nexport function approximatelyEquals(extent1, extent2, tolerance) {\n return (\n Math.abs(extent1[0] - extent2[0]) < tolerance &&\n Math.abs(extent1[2] - extent2[2]) < tolerance &&\n Math.abs(extent1[1] - extent2[1]) < tolerance &&\n Math.abs(extent1[3] - extent2[3]) < tolerance\n );\n}\n\n/**\n * Modify an extent to include another extent.\n * @param {Extent} extent1 The extent to be modified.\n * @param {Extent} extent2 The extent that will be included in the first.\n * @return {Extent} A reference to the first (extended) extent.\n * @api\n */\nexport function extend(extent1, extent2) {\n if (extent2[0] < extent1[0]) {\n extent1[0] = extent2[0];\n }\n if (extent2[2] > extent1[2]) {\n extent1[2] = extent2[2];\n }\n if (extent2[1] < extent1[1]) {\n extent1[1] = extent2[1];\n }\n if (extent2[3] > extent1[3]) {\n extent1[3] = extent2[3];\n }\n return extent1;\n}\n\n/**\n * @param {Extent} extent Extent.\n * @param {import(\"./coordinate.js\").Coordinate} coordinate Coordinate.\n */\nexport function extendCoordinate(extent, coordinate) {\n if (coordinate[0] < extent[0]) {\n extent[0] = coordinate[0];\n }\n if (coordinate[0] > extent[2]) {\n extent[2] = coordinate[0];\n }\n if (coordinate[1] < extent[1]) {\n extent[1] = coordinate[1];\n }\n if (coordinate[1] > extent[3]) {\n extent[3] = coordinate[1];\n }\n}\n\n/**\n * @param {Extent} extent Extent.\n * @param {Array} coordinates Coordinates.\n * @return {Extent} Extent.\n */\nexport function extendCoordinates(extent, coordinates) {\n for (let i = 0, ii = coordinates.length; i < ii; ++i) {\n extendCoordinate(extent, coordinates[i]);\n }\n return extent;\n}\n\n/**\n * @param {Extent} extent Extent.\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @return {Extent} Extent.\n */\nexport function extendFlatCoordinates(\n extent,\n flatCoordinates,\n offset,\n end,\n stride\n) {\n for (; offset < end; offset += stride) {\n extendXY(extent, flatCoordinates[offset], flatCoordinates[offset + 1]);\n }\n return extent;\n}\n\n/**\n * @param {Extent} extent Extent.\n * @param {Array>} rings Rings.\n * @return {Extent} Extent.\n */\nexport function extendRings(extent, rings) {\n for (let i = 0, ii = rings.length; i < ii; ++i) {\n extendCoordinates(extent, rings[i]);\n }\n return extent;\n}\n\n/**\n * @param {Extent} extent Extent.\n * @param {number} x X.\n * @param {number} y Y.\n */\nexport function extendXY(extent, x, y) {\n extent[0] = Math.min(extent[0], x);\n extent[1] = Math.min(extent[1], y);\n extent[2] = Math.max(extent[2], x);\n extent[3] = Math.max(extent[3], y);\n}\n\n/**\n * This function calls `callback` for each corner of the extent. If the\n * callback returns a truthy value the function returns that value\n * immediately. Otherwise the function returns `false`.\n * @param {Extent} extent Extent.\n * @param {function(import(\"./coordinate.js\").Coordinate): S} callback Callback.\n * @return {S|boolean} Value.\n * @template S\n */\nexport function forEachCorner(extent, callback) {\n let val;\n val = callback(getBottomLeft(extent));\n if (val) {\n return val;\n }\n val = callback(getBottomRight(extent));\n if (val) {\n return val;\n }\n val = callback(getTopRight(extent));\n if (val) {\n return val;\n }\n val = callback(getTopLeft(extent));\n if (val) {\n return val;\n }\n return false;\n}\n\n/**\n * Get the size of an extent.\n * @param {Extent} extent Extent.\n * @return {number} Area.\n * @api\n */\nexport function getArea(extent) {\n let area = 0;\n if (!isEmpty(extent)) {\n area = getWidth(extent) * getHeight(extent);\n }\n return area;\n}\n\n/**\n * Get the bottom left coordinate of an extent.\n * @param {Extent} extent Extent.\n * @return {import(\"./coordinate.js\").Coordinate} Bottom left coordinate.\n * @api\n */\nexport function getBottomLeft(extent) {\n return [extent[0], extent[1]];\n}\n\n/**\n * Get the bottom right coordinate of an extent.\n * @param {Extent} extent Extent.\n * @return {import(\"./coordinate.js\").Coordinate} Bottom right coordinate.\n * @api\n */\nexport function getBottomRight(extent) {\n return [extent[2], extent[1]];\n}\n\n/**\n * Get the center coordinate of an extent.\n * @param {Extent} extent Extent.\n * @return {import(\"./coordinate.js\").Coordinate} Center.\n * @api\n */\nexport function getCenter(extent) {\n return [(extent[0] + extent[2]) / 2, (extent[1] + extent[3]) / 2];\n}\n\n/**\n * Get a corner coordinate of an extent.\n * @param {Extent} extent Extent.\n * @param {Corner} corner Corner.\n * @return {import(\"./coordinate.js\").Coordinate} Corner coordinate.\n */\nexport function getCorner(extent, corner) {\n let coordinate;\n if (corner === 'bottom-left') {\n coordinate = getBottomLeft(extent);\n } else if (corner === 'bottom-right') {\n coordinate = getBottomRight(extent);\n } else if (corner === 'top-left') {\n coordinate = getTopLeft(extent);\n } else if (corner === 'top-right') {\n coordinate = getTopRight(extent);\n } else {\n assert(false, 13); // Invalid corner\n }\n return coordinate;\n}\n\n/**\n * @param {Extent} extent1 Extent 1.\n * @param {Extent} extent2 Extent 2.\n * @return {number} Enlarged area.\n */\nexport function getEnlargedArea(extent1, extent2) {\n const minX = Math.min(extent1[0], extent2[0]);\n const minY = Math.min(extent1[1], extent2[1]);\n const maxX = Math.max(extent1[2], extent2[2]);\n const maxY = Math.max(extent1[3], extent2[3]);\n return (maxX - minX) * (maxY - minY);\n}\n\n/**\n * @param {import(\"./coordinate.js\").Coordinate} center Center.\n * @param {number} resolution Resolution.\n * @param {number} rotation Rotation.\n * @param {import(\"./size.js\").Size} size Size.\n * @param {Extent} [dest] Destination extent.\n * @return {Extent} Extent.\n */\nexport function getForViewAndSize(center, resolution, rotation, size, dest) {\n const [x0, y0, x1, y1, x2, y2, x3, y3] = getRotatedViewport(\n center,\n resolution,\n rotation,\n size\n );\n return createOrUpdate(\n Math.min(x0, x1, x2, x3),\n Math.min(y0, y1, y2, y3),\n Math.max(x0, x1, x2, x3),\n Math.max(y0, y1, y2, y3),\n dest\n );\n}\n\n/**\n * @param {import(\"./coordinate.js\").Coordinate} center Center.\n * @param {number} resolution Resolution.\n * @param {number} rotation Rotation.\n * @param {import(\"./size.js\").Size} size Size.\n * @return {Array} Linear ring representing the viewport.\n */\nexport function getRotatedViewport(center, resolution, rotation, size) {\n const dx = (resolution * size[0]) / 2;\n const dy = (resolution * size[1]) / 2;\n const cosRotation = Math.cos(rotation);\n const sinRotation = Math.sin(rotation);\n const xCos = dx * cosRotation;\n const xSin = dx * sinRotation;\n const yCos = dy * cosRotation;\n const ySin = dy * sinRotation;\n const x = center[0];\n const y = center[1];\n return [\n x - xCos + ySin,\n y - xSin - yCos,\n x - xCos - ySin,\n y - xSin + yCos,\n x + xCos - ySin,\n y + xSin + yCos,\n x + xCos + ySin,\n y + xSin - yCos,\n x - xCos + ySin,\n y - xSin - yCos,\n ];\n}\n\n/**\n * Get the height of an extent.\n * @param {Extent} extent Extent.\n * @return {number} Height.\n * @api\n */\nexport function getHeight(extent) {\n return extent[3] - extent[1];\n}\n\n/**\n * @param {Extent} extent1 Extent 1.\n * @param {Extent} extent2 Extent 2.\n * @return {number} Intersection area.\n */\nexport function getIntersectionArea(extent1, extent2) {\n const intersection = getIntersection(extent1, extent2);\n return getArea(intersection);\n}\n\n/**\n * Get the intersection of two extents.\n * @param {Extent} extent1 Extent 1.\n * @param {Extent} extent2 Extent 2.\n * @param {Extent} [dest] Optional extent to populate with intersection.\n * @return {Extent} Intersecting extent.\n * @api\n */\nexport function getIntersection(extent1, extent2, dest) {\n const intersection = dest ? dest : createEmpty();\n if (intersects(extent1, extent2)) {\n if (extent1[0] > extent2[0]) {\n intersection[0] = extent1[0];\n } else {\n intersection[0] = extent2[0];\n }\n if (extent1[1] > extent2[1]) {\n intersection[1] = extent1[1];\n } else {\n intersection[1] = extent2[1];\n }\n if (extent1[2] < extent2[2]) {\n intersection[2] = extent1[2];\n } else {\n intersection[2] = extent2[2];\n }\n if (extent1[3] < extent2[3]) {\n intersection[3] = extent1[3];\n } else {\n intersection[3] = extent2[3];\n }\n } else {\n createOrUpdateEmpty(intersection);\n }\n return intersection;\n}\n\n/**\n * @param {Extent} extent Extent.\n * @return {number} Margin.\n */\nexport function getMargin(extent) {\n return getWidth(extent) + getHeight(extent);\n}\n\n/**\n * Get the size (width, height) of an extent.\n * @param {Extent} extent The extent.\n * @return {import(\"./size.js\").Size} The extent size.\n * @api\n */\nexport function getSize(extent) {\n return [extent[2] - extent[0], extent[3] - extent[1]];\n}\n\n/**\n * Get the top left coordinate of an extent.\n * @param {Extent} extent Extent.\n * @return {import(\"./coordinate.js\").Coordinate} Top left coordinate.\n * @api\n */\nexport function getTopLeft(extent) {\n return [extent[0], extent[3]];\n}\n\n/**\n * Get the top right coordinate of an extent.\n * @param {Extent} extent Extent.\n * @return {import(\"./coordinate.js\").Coordinate} Top right coordinate.\n * @api\n */\nexport function getTopRight(extent) {\n return [extent[2], extent[3]];\n}\n\n/**\n * Get the width of an extent.\n * @param {Extent} extent Extent.\n * @return {number} Width.\n * @api\n */\nexport function getWidth(extent) {\n return extent[2] - extent[0];\n}\n\n/**\n * Determine if one extent intersects another.\n * @param {Extent} extent1 Extent 1.\n * @param {Extent} extent2 Extent.\n * @return {boolean} The two extents intersect.\n * @api\n */\nexport function intersects(extent1, extent2) {\n return (\n extent1[0] <= extent2[2] &&\n extent1[2] >= extent2[0] &&\n extent1[1] <= extent2[3] &&\n extent1[3] >= extent2[1]\n );\n}\n\n/**\n * Determine if an extent is empty.\n * @param {Extent} extent Extent.\n * @return {boolean} Is empty.\n * @api\n */\nexport function isEmpty(extent) {\n return extent[2] < extent[0] || extent[3] < extent[1];\n}\n\n/**\n * @param {Extent} extent Extent.\n * @param {Extent} [dest] Extent.\n * @return {Extent} Extent.\n */\nexport function returnOrUpdate(extent, dest) {\n if (dest) {\n dest[0] = extent[0];\n dest[1] = extent[1];\n dest[2] = extent[2];\n dest[3] = extent[3];\n return dest;\n }\n return extent;\n}\n\n/**\n * @param {Extent} extent Extent.\n * @param {number} value Value.\n */\nexport function scaleFromCenter(extent, value) {\n const deltaX = ((extent[2] - extent[0]) / 2) * (value - 1);\n const deltaY = ((extent[3] - extent[1]) / 2) * (value - 1);\n extent[0] -= deltaX;\n extent[2] += deltaX;\n extent[1] -= deltaY;\n extent[3] += deltaY;\n}\n\n/**\n * Determine if the segment between two coordinates intersects (crosses,\n * touches, or is contained by) the provided extent.\n * @param {Extent} extent The extent.\n * @param {import(\"./coordinate.js\").Coordinate} start Segment start coordinate.\n * @param {import(\"./coordinate.js\").Coordinate} end Segment end coordinate.\n * @return {boolean} The segment intersects the extent.\n */\nexport function intersectsSegment(extent, start, end) {\n let intersects = false;\n const startRel = coordinateRelationship(extent, start);\n const endRel = coordinateRelationship(extent, end);\n if (\n startRel === Relationship.INTERSECTING ||\n endRel === Relationship.INTERSECTING\n ) {\n intersects = true;\n } else {\n const minX = extent[0];\n const minY = extent[1];\n const maxX = extent[2];\n const maxY = extent[3];\n const startX = start[0];\n const startY = start[1];\n const endX = end[0];\n const endY = end[1];\n const slope = (endY - startY) / (endX - startX);\n let x, y;\n if (!!(endRel & Relationship.ABOVE) && !(startRel & Relationship.ABOVE)) {\n // potentially intersects top\n x = endX - (endY - maxY) / slope;\n intersects = x >= minX && x <= maxX;\n }\n if (\n !intersects &&\n !!(endRel & Relationship.RIGHT) &&\n !(startRel & Relationship.RIGHT)\n ) {\n // potentially intersects right\n y = endY - (endX - maxX) * slope;\n intersects = y >= minY && y <= maxY;\n }\n if (\n !intersects &&\n !!(endRel & Relationship.BELOW) &&\n !(startRel & Relationship.BELOW)\n ) {\n // potentially intersects bottom\n x = endX - (endY - minY) / slope;\n intersects = x >= minX && x <= maxX;\n }\n if (\n !intersects &&\n !!(endRel & Relationship.LEFT) &&\n !(startRel & Relationship.LEFT)\n ) {\n // potentially intersects left\n y = endY - (endX - minX) * slope;\n intersects = y >= minY && y <= maxY;\n }\n }\n return intersects;\n}\n\n/**\n * Apply a transform function to the extent.\n * @param {Extent} extent Extent.\n * @param {import(\"./proj.js\").TransformFunction} transformFn Transform function.\n * Called with `[minX, minY, maxX, maxY]` extent coordinates.\n * @param {Extent} [dest] Destination extent.\n * @param {number} [stops] Number of stops per side used for the transform.\n * By default only the corners are used.\n * @return {Extent} Extent.\n * @api\n */\nexport function applyTransform(extent, transformFn, dest, stops) {\n if (isEmpty(extent)) {\n return createOrUpdateEmpty(dest);\n }\n let coordinates = [];\n if (stops > 1) {\n const width = extent[2] - extent[0];\n const height = extent[3] - extent[1];\n for (let i = 0; i < stops; ++i) {\n coordinates.push(\n extent[0] + (width * i) / stops,\n extent[1],\n extent[2],\n extent[1] + (height * i) / stops,\n extent[2] - (width * i) / stops,\n extent[3],\n extent[0],\n extent[3] - (height * i) / stops\n );\n }\n } else {\n coordinates = [\n extent[0],\n extent[1],\n extent[2],\n extent[1],\n extent[2],\n extent[3],\n extent[0],\n extent[3],\n ];\n }\n transformFn(coordinates, coordinates, 2);\n const xs = [];\n const ys = [];\n for (let i = 0, l = coordinates.length; i < l; i += 2) {\n xs.push(coordinates[i]);\n ys.push(coordinates[i + 1]);\n }\n return _boundingExtentXYs(xs, ys, dest);\n}\n\n/**\n * Modifies the provided extent in-place to be within the real world\n * extent.\n *\n * @param {Extent} extent Extent.\n * @param {import(\"./proj/Projection.js\").default} projection Projection\n * @return {Extent} The extent within the real world extent.\n */\nexport function wrapX(extent, projection) {\n const projectionExtent = projection.getExtent();\n const center = getCenter(extent);\n if (\n projection.canWrapX() &&\n (center[0] < projectionExtent[0] || center[0] >= projectionExtent[2])\n ) {\n const worldWidth = getWidth(projectionExtent);\n const worldsAway = Math.floor(\n (center[0] - projectionExtent[0]) / worldWidth\n );\n const offset = worldsAway * worldWidth;\n extent[0] -= offset;\n extent[2] -= offset;\n }\n return extent;\n}\n\n/**\n * Fits the extent to the real world\n *\n * If the extent does not cross the anti meridian, this will return the extent in an array\n * If the extent crosses the anti meridian, the extent will be sliced, so each part fits within the\n * real world\n *\n *\n * @param {Extent} extent Extent.\n * @param {import(\"./proj/Projection.js\").default} projection Projection\n * @return {Array} The extent within the real world extent.\n */\nexport function wrapAndSliceX(extent, projection) {\n if (projection.canWrapX()) {\n const projectionExtent = projection.getExtent();\n\n if (!isFinite(extent[0]) || !isFinite(extent[2])) {\n return [[projectionExtent[0], extent[1], projectionExtent[2], extent[3]]];\n }\n\n wrapX(extent, projection);\n const worldWidth = getWidth(projectionExtent);\n\n if (getWidth(extent) > worldWidth) {\n // the extent wraps around on itself\n return [[projectionExtent[0], extent[1], projectionExtent[2], extent[3]]];\n }\n if (extent[0] < projectionExtent[0]) {\n // the extent crosses the anti meridian, so it needs to be sliced\n return [\n [extent[0] + worldWidth, extent[1], projectionExtent[2], extent[3]],\n [projectionExtent[0], extent[1], extent[2], extent[3]],\n ];\n }\n if (extent[2] > projectionExtent[2]) {\n // the extent crosses the anti meridian, so it needs to be sliced\n return [\n [extent[0], extent[1], projectionExtent[2], extent[3]],\n [projectionExtent[0], extent[1], extent[2] - worldWidth, extent[3]],\n ];\n }\n }\n\n return [extent];\n}\n","/**\n * @module ol/proj/Units\n */\n\n/**\n * @typedef {'radians' | 'degrees' | 'ft' | 'm' | 'pixels' | 'tile-pixels' | 'us-ft'} Units\n * Projection units.\n */\n\n/**\n * See http://duff.ess.washington.edu/data/raster/drg/docs/geotiff.txt\n * @type {Object}\n */\nconst unitByCode = {\n '9001': 'm',\n '9002': 'ft',\n '9003': 'us-ft',\n '9101': 'radians',\n '9102': 'degrees',\n};\n\n/**\n * @param {number} code Unit code.\n * @return {Units} Units.\n */\nexport function fromCode(code) {\n return unitByCode[code];\n}\n\n/**\n * @typedef {Object} MetersPerUnitLookup\n * @property {number} radians Radians\n * @property {number} degrees Degrees\n * @property {number} ft Feet\n * @property {number} m Meters\n * @property {number} us-ft US feet\n */\n\n/**\n * Meters per unit lookup table.\n * @const\n * @type {MetersPerUnitLookup}\n * @api\n */\nexport const METERS_PER_UNIT = {\n // use the radius of the Normal sphere\n 'radians': 6370997 / (2 * Math.PI),\n 'degrees': (2 * Math.PI * 6370997) / 360,\n 'ft': 0.3048,\n 'm': 1,\n 'us-ft': 1200 / 3937,\n};\n","/**\n * @module ol/proj/Projection\n */\nimport {METERS_PER_UNIT} from './Units.js';\n\n/**\n * @typedef {Object} Options\n * @property {string} code The SRS identifier code, e.g. `EPSG:4326`.\n * @property {import(\"./Units.js\").Units} [units] Units. Required unless a\n * proj4 projection is defined for `code`.\n * @property {import(\"../extent.js\").Extent} [extent] The validity extent for the SRS.\n * @property {string} [axisOrientation='enu'] The axis orientation as specified in Proj4.\n * @property {boolean} [global=false] Whether the projection is valid for the whole globe.\n * @property {number} [metersPerUnit] The meters per unit for the SRS.\n * If not provided, the `units` are used to get the meters per unit from the {@link METERS_PER_UNIT}\n * lookup table.\n * @property {import(\"../extent.js\").Extent} [worldExtent] The world extent for the SRS.\n * @property {function(number, import(\"../coordinate.js\").Coordinate):number} [getPointResolution]\n * Function to determine resolution at a point. The function is called with a\n * `number` view resolution and a {@link module:ol/coordinate~Coordinate} as arguments, and returns\n * the `number` resolution in projection units at the passed coordinate. If this is `undefined`,\n * the default {@link module:ol/proj.getPointResolution} function will be used.\n */\n\n/**\n * @classdesc\n * Projection definition class. One of these is created for each projection\n * supported in the application and stored in the {@link module:ol/proj} namespace.\n * You can use these in applications, but this is not required, as API params\n * and options use {@link module:ol/proj~ProjectionLike} which means the simple string\n * code will suffice.\n *\n * You can use {@link module:ol/proj.get} to retrieve the object for a particular\n * projection.\n *\n * The library includes definitions for `EPSG:4326` and `EPSG:3857`, together\n * with the following aliases:\n * * `EPSG:4326`: CRS:84, urn:ogc:def:crs:EPSG:6.6:4326,\n * urn:ogc:def:crs:OGC:1.3:CRS84, urn:ogc:def:crs:OGC:2:84,\n * http://www.opengis.net/gml/srs/epsg.xml#4326,\n * urn:x-ogc:def:crs:EPSG:4326\n * * `EPSG:3857`: EPSG:102100, EPSG:102113, EPSG:900913,\n * urn:ogc:def:crs:EPSG:6.18:3:3857,\n * http://www.opengis.net/gml/srs/epsg.xml#3857\n *\n * If you use [proj4js](https://github.com/proj4js/proj4js), aliases can\n * be added using `proj4.defs()`. After all required projection definitions are\n * added, call the {@link module:ol/proj/proj4.register} function.\n *\n * @api\n */\nclass Projection {\n /**\n * @param {Options} options Projection options.\n */\n constructor(options) {\n /**\n * @private\n * @type {string}\n */\n this.code_ = options.code;\n\n /**\n * Units of projected coordinates. When set to `TILE_PIXELS`, a\n * `this.extent_` and `this.worldExtent_` must be configured properly for each\n * tile.\n * @private\n * @type {import(\"./Units.js\").Units}\n */\n this.units_ = /** @type {import(\"./Units.js\").Units} */ (options.units);\n\n /**\n * Validity extent of the projection in projected coordinates. For projections\n * with `TILE_PIXELS` units, this is the extent of the tile in\n * tile pixel space.\n * @private\n * @type {import(\"../extent.js\").Extent}\n */\n this.extent_ = options.extent !== undefined ? options.extent : null;\n\n /**\n * Extent of the world in EPSG:4326. For projections with\n * `TILE_PIXELS` units, this is the extent of the tile in\n * projected coordinate space.\n * @private\n * @type {import(\"../extent.js\").Extent}\n */\n this.worldExtent_ =\n options.worldExtent !== undefined ? options.worldExtent : null;\n\n /**\n * @private\n * @type {string}\n */\n this.axisOrientation_ =\n options.axisOrientation !== undefined ? options.axisOrientation : 'enu';\n\n /**\n * @private\n * @type {boolean}\n */\n this.global_ = options.global !== undefined ? options.global : false;\n\n /**\n * @private\n * @type {boolean}\n */\n this.canWrapX_ = !!(this.global_ && this.extent_);\n\n /**\n * @private\n * @type {function(number, import(\"../coordinate.js\").Coordinate):number|undefined}\n */\n this.getPointResolutionFunc_ = options.getPointResolution;\n\n /**\n * @private\n * @type {import(\"../tilegrid/TileGrid.js\").default}\n */\n this.defaultTileGrid_ = null;\n\n /**\n * @private\n * @type {number|undefined}\n */\n this.metersPerUnit_ = options.metersPerUnit;\n }\n\n /**\n * @return {boolean} The projection is suitable for wrapping the x-axis\n */\n canWrapX() {\n return this.canWrapX_;\n }\n\n /**\n * Get the code for this projection, e.g. 'EPSG:4326'.\n * @return {string} Code.\n * @api\n */\n getCode() {\n return this.code_;\n }\n\n /**\n * Get the validity extent for this projection.\n * @return {import(\"../extent.js\").Extent} Extent.\n * @api\n */\n getExtent() {\n return this.extent_;\n }\n\n /**\n * Get the units of this projection.\n * @return {import(\"./Units.js\").Units} Units.\n * @api\n */\n getUnits() {\n return this.units_;\n }\n\n /**\n * Get the amount of meters per unit of this projection. If the projection is\n * not configured with `metersPerUnit` or a units identifier, the return is\n * `undefined`.\n * @return {number|undefined} Meters.\n * @api\n */\n getMetersPerUnit() {\n return this.metersPerUnit_ || METERS_PER_UNIT[this.units_];\n }\n\n /**\n * Get the world extent for this projection.\n * @return {import(\"../extent.js\").Extent} Extent.\n * @api\n */\n getWorldExtent() {\n return this.worldExtent_;\n }\n\n /**\n * Get the axis orientation of this projection.\n * Example values are:\n * enu - the default easting, northing, elevation.\n * neu - northing, easting, up - useful for \"lat/long\" geographic coordinates,\n * or south orientated transverse mercator.\n * wnu - westing, northing, up - some planetary coordinate systems have\n * \"west positive\" coordinate systems\n * @return {string} Axis orientation.\n * @api\n */\n getAxisOrientation() {\n return this.axisOrientation_;\n }\n\n /**\n * Is this projection a global projection which spans the whole world?\n * @return {boolean} Whether the projection is global.\n * @api\n */\n isGlobal() {\n return this.global_;\n }\n\n /**\n * Set if the projection is a global projection which spans the whole world\n * @param {boolean} global Whether the projection is global.\n * @api\n */\n setGlobal(global) {\n this.global_ = global;\n this.canWrapX_ = !!(global && this.extent_);\n }\n\n /**\n * @return {import(\"../tilegrid/TileGrid.js\").default} The default tile grid.\n */\n getDefaultTileGrid() {\n return this.defaultTileGrid_;\n }\n\n /**\n * @param {import(\"../tilegrid/TileGrid.js\").default} tileGrid The default tile grid.\n */\n setDefaultTileGrid(tileGrid) {\n this.defaultTileGrid_ = tileGrid;\n }\n\n /**\n * Set the validity extent for this projection.\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @api\n */\n setExtent(extent) {\n this.extent_ = extent;\n this.canWrapX_ = !!(this.global_ && extent);\n }\n\n /**\n * Set the world extent for this projection.\n * @param {import(\"../extent.js\").Extent} worldExtent World extent\n * [minlon, minlat, maxlon, maxlat].\n * @api\n */\n setWorldExtent(worldExtent) {\n this.worldExtent_ = worldExtent;\n }\n\n /**\n * Set the getPointResolution function (see {@link module:ol/proj.getPointResolution}\n * for this projection.\n * @param {function(number, import(\"../coordinate.js\").Coordinate):number} func Function\n * @api\n */\n setGetPointResolution(func) {\n this.getPointResolutionFunc_ = func;\n }\n\n /**\n * Get the custom point resolution function for this projection (if set).\n * @return {function(number, import(\"../coordinate.js\").Coordinate):number|undefined} The custom point\n * resolution function (if set).\n */\n getPointResolutionFunc() {\n return this.getPointResolutionFunc_;\n }\n}\n\nexport default Projection;\n","/**\n * @module ol/proj/epsg3857\n */\nimport Projection from './Projection.js';\n\n/**\n * Radius of WGS84 sphere\n *\n * @const\n * @type {number}\n */\nexport const RADIUS = 6378137;\n\n/**\n * @const\n * @type {number}\n */\nexport const HALF_SIZE = Math.PI * RADIUS;\n\n/**\n * @const\n * @type {import(\"../extent.js\").Extent}\n */\nexport const EXTENT = [-HALF_SIZE, -HALF_SIZE, HALF_SIZE, HALF_SIZE];\n\n/**\n * @const\n * @type {import(\"../extent.js\").Extent}\n */\nexport const WORLD_EXTENT = [-180, -85, 180, 85];\n\n/**\n * Maximum safe value in y direction\n * @const\n * @type {number}\n */\nexport const MAX_SAFE_Y = RADIUS * Math.log(Math.tan(Math.PI / 2));\n\n/**\n * @classdesc\n * Projection object for web/spherical Mercator (EPSG:3857).\n */\nclass EPSG3857Projection extends Projection {\n /**\n * @param {string} code Code.\n */\n constructor(code) {\n super({\n code: code,\n units: 'm',\n extent: EXTENT,\n global: true,\n worldExtent: WORLD_EXTENT,\n getPointResolution: function (resolution, point) {\n return resolution / Math.cosh(point[1] / RADIUS);\n },\n });\n }\n}\n\n/**\n * Projections equal to EPSG:3857.\n *\n * @const\n * @type {Array}\n */\nexport const PROJECTIONS = [\n new EPSG3857Projection('EPSG:3857'),\n new EPSG3857Projection('EPSG:102100'),\n new EPSG3857Projection('EPSG:102113'),\n new EPSG3857Projection('EPSG:900913'),\n new EPSG3857Projection('http://www.opengis.net/def/crs/EPSG/0/3857'),\n new EPSG3857Projection('http://www.opengis.net/gml/srs/epsg.xml#3857'),\n];\n\n/**\n * Transformation from EPSG:4326 to EPSG:3857.\n *\n * @param {Array} input Input array of coordinate values.\n * @param {Array} [output] Output array of coordinate values.\n * @param {number} [dimension] Dimension (default is `2`).\n * @return {Array} Output array of coordinate values.\n */\nexport function fromEPSG4326(input, output, dimension) {\n const length = input.length;\n dimension = dimension > 1 ? dimension : 2;\n if (output === undefined) {\n if (dimension > 2) {\n // preserve values beyond second dimension\n output = input.slice();\n } else {\n output = new Array(length);\n }\n }\n for (let i = 0; i < length; i += dimension) {\n output[i] = (HALF_SIZE * input[i]) / 180;\n let y = RADIUS * Math.log(Math.tan((Math.PI * (+input[i + 1] + 90)) / 360));\n if (y > MAX_SAFE_Y) {\n y = MAX_SAFE_Y;\n } else if (y < -MAX_SAFE_Y) {\n y = -MAX_SAFE_Y;\n }\n output[i + 1] = y;\n }\n return output;\n}\n\n/**\n * Transformation from EPSG:3857 to EPSG:4326.\n *\n * @param {Array} input Input array of coordinate values.\n * @param {Array} [output] Output array of coordinate values.\n * @param {number} [dimension] Dimension (default is `2`).\n * @return {Array} Output array of coordinate values.\n */\nexport function toEPSG4326(input, output, dimension) {\n const length = input.length;\n dimension = dimension > 1 ? dimension : 2;\n if (output === undefined) {\n if (dimension > 2) {\n // preserve values beyond second dimension\n output = input.slice();\n } else {\n output = new Array(length);\n }\n }\n for (let i = 0; i < length; i += dimension) {\n output[i] = (180 * input[i]) / HALF_SIZE;\n output[i + 1] =\n (360 * Math.atan(Math.exp(input[i + 1] / RADIUS))) / Math.PI - 90;\n }\n return output;\n}\n","/**\n * @module ol/proj/epsg4326\n */\nimport Projection from './Projection.js';\n\n/**\n * Semi-major radius of the WGS84 ellipsoid.\n *\n * @const\n * @type {number}\n */\nexport const RADIUS = 6378137;\n\n/**\n * Extent of the EPSG:4326 projection which is the whole world.\n *\n * @const\n * @type {import(\"../extent.js\").Extent}\n */\nexport const EXTENT = [-180, -90, 180, 90];\n\n/**\n * @const\n * @type {number}\n */\nexport const METERS_PER_UNIT = (Math.PI * RADIUS) / 180;\n\n/**\n * @classdesc\n * Projection object for WGS84 geographic coordinates (EPSG:4326).\n *\n * Note that OpenLayers does not strictly comply with the EPSG definition.\n * The EPSG registry defines 4326 as a CRS for Latitude,Longitude (y,x).\n * OpenLayers treats EPSG:4326 as a pseudo-projection, with x,y coordinates.\n */\nclass EPSG4326Projection extends Projection {\n /**\n * @param {string} code Code.\n * @param {string} [axisOrientation] Axis orientation.\n */\n constructor(code, axisOrientation) {\n super({\n code: code,\n units: 'degrees',\n extent: EXTENT,\n axisOrientation: axisOrientation,\n global: true,\n metersPerUnit: METERS_PER_UNIT,\n worldExtent: EXTENT,\n });\n }\n}\n\n/**\n * Projections equal to EPSG:4326.\n *\n * @const\n * @type {Array}\n */\nexport const PROJECTIONS = [\n new EPSG4326Projection('CRS:84'),\n new EPSG4326Projection('EPSG:4326', 'neu'),\n new EPSG4326Projection('urn:ogc:def:crs:OGC:1.3:CRS84'),\n new EPSG4326Projection('urn:ogc:def:crs:OGC:2:84'),\n new EPSG4326Projection('http://www.opengis.net/def/crs/OGC/1.3/CRS84'),\n new EPSG4326Projection('http://www.opengis.net/gml/srs/epsg.xml#4326', 'neu'),\n new EPSG4326Projection('http://www.opengis.net/def/crs/EPSG/0/4326', 'neu'),\n];\n","/**\n * @module ol/proj/projections\n */\n\n/**\n * @type {Object}\n */\nlet cache = {};\n\n/**\n * Clear the projections cache.\n */\nexport function clear() {\n cache = {};\n}\n\n/**\n * Get a cached projection by code.\n * @param {string} code The code for the projection.\n * @return {import(\"./Projection.js\").default} The projection (if cached).\n */\nexport function get(code) {\n return (\n cache[code] ||\n cache[code.replace(/urn:(x-)?ogc:def:crs:EPSG:(.*:)?(\\w+)$/, 'EPSG:$3')] ||\n null\n );\n}\n\n/**\n * Add a projection to the cache.\n * @param {string} code The projection code.\n * @param {import(\"./Projection.js\").default} projection The projection to cache.\n */\nexport function add(code, projection) {\n cache[code] = projection;\n}\n","/**\n * @module ol/proj/transforms\n */\nimport {isEmpty} from '../obj.js';\n\n/**\n * @private\n * @type {!Object>}\n */\nlet transforms = {};\n\n/**\n * Clear the transform cache.\n */\nexport function clear() {\n transforms = {};\n}\n\n/**\n * Registers a conversion function to convert coordinates from the source\n * projection to the destination projection.\n *\n * @param {import(\"./Projection.js\").default} source Source.\n * @param {import(\"./Projection.js\").default} destination Destination.\n * @param {import(\"../proj.js\").TransformFunction} transformFn Transform.\n */\nexport function add(source, destination, transformFn) {\n const sourceCode = source.getCode();\n const destinationCode = destination.getCode();\n if (!(sourceCode in transforms)) {\n transforms[sourceCode] = {};\n }\n transforms[sourceCode][destinationCode] = transformFn;\n}\n\n/**\n * Unregisters the conversion function to convert coordinates from the source\n * projection to the destination projection. This method is used to clean up\n * cached transforms during testing.\n *\n * @param {import(\"./Projection.js\").default} source Source projection.\n * @param {import(\"./Projection.js\").default} destination Destination projection.\n * @return {import(\"../proj.js\").TransformFunction} transformFn The unregistered transform.\n */\nexport function remove(source, destination) {\n const sourceCode = source.getCode();\n const destinationCode = destination.getCode();\n const transform = transforms[sourceCode][destinationCode];\n delete transforms[sourceCode][destinationCode];\n if (isEmpty(transforms[sourceCode])) {\n delete transforms[sourceCode];\n }\n return transform;\n}\n\n/**\n * Get a transform given a source code and a destination code.\n * @param {string} sourceCode The code for the source projection.\n * @param {string} destinationCode The code for the destination projection.\n * @return {import(\"../proj.js\").TransformFunction|undefined} The transform function (if found).\n */\nexport function get(sourceCode, destinationCode) {\n let transform;\n if (sourceCode in transforms && destinationCode in transforms[sourceCode]) {\n transform = transforms[sourceCode][destinationCode];\n }\n return transform;\n}\n","/**\n * @module ol/math\n */\n\n/**\n * Takes a number and clamps it to within the provided bounds.\n * @param {number} value The input number.\n * @param {number} min The minimum value to return.\n * @param {number} max The maximum value to return.\n * @return {number} The input number if it is within bounds, or the nearest\n * number within the bounds.\n */\nexport function clamp(value, min, max) {\n return Math.min(Math.max(value, min), max);\n}\n\n/**\n * Returns the square of the closest distance between the point (x, y) and the\n * line segment (x1, y1) to (x2, y2).\n * @param {number} x X.\n * @param {number} y Y.\n * @param {number} x1 X1.\n * @param {number} y1 Y1.\n * @param {number} x2 X2.\n * @param {number} y2 Y2.\n * @return {number} Squared distance.\n */\nexport function squaredSegmentDistance(x, y, x1, y1, x2, y2) {\n const dx = x2 - x1;\n const dy = y2 - y1;\n if (dx !== 0 || dy !== 0) {\n const t = ((x - x1) * dx + (y - y1) * dy) / (dx * dx + dy * dy);\n if (t > 1) {\n x1 = x2;\n y1 = y2;\n } else if (t > 0) {\n x1 += dx * t;\n y1 += dy * t;\n }\n }\n return squaredDistance(x, y, x1, y1);\n}\n\n/**\n * Returns the square of the distance between the points (x1, y1) and (x2, y2).\n * @param {number} x1 X1.\n * @param {number} y1 Y1.\n * @param {number} x2 X2.\n * @param {number} y2 Y2.\n * @return {number} Squared distance.\n */\nexport function squaredDistance(x1, y1, x2, y2) {\n const dx = x2 - x1;\n const dy = y2 - y1;\n return dx * dx + dy * dy;\n}\n\n/**\n * Solves system of linear equations using Gaussian elimination method.\n *\n * @param {Array>} mat Augmented matrix (n x n + 1 column)\n * in row-major order.\n * @return {Array} The resulting vector.\n */\nexport function solveLinearSystem(mat) {\n const n = mat.length;\n\n for (let i = 0; i < n; i++) {\n // Find max in the i-th column (ignoring i - 1 first rows)\n let maxRow = i;\n let maxEl = Math.abs(mat[i][i]);\n for (let r = i + 1; r < n; r++) {\n const absValue = Math.abs(mat[r][i]);\n if (absValue > maxEl) {\n maxEl = absValue;\n maxRow = r;\n }\n }\n\n if (maxEl === 0) {\n return null; // matrix is singular\n }\n\n // Swap max row with i-th (current) row\n const tmp = mat[maxRow];\n mat[maxRow] = mat[i];\n mat[i] = tmp;\n\n // Subtract the i-th row to make all the remaining rows 0 in the i-th column\n for (let j = i + 1; j < n; j++) {\n const coef = -mat[j][i] / mat[i][i];\n for (let k = i; k < n + 1; k++) {\n if (i == k) {\n mat[j][k] = 0;\n } else {\n mat[j][k] += coef * mat[i][k];\n }\n }\n }\n }\n\n // Solve Ax=b for upper triangular matrix A (mat)\n const x = new Array(n);\n for (let l = n - 1; l >= 0; l--) {\n x[l] = mat[l][n] / mat[l][l];\n for (let m = l - 1; m >= 0; m--) {\n mat[m][n] -= mat[m][l] * x[l];\n }\n }\n return x;\n}\n\n/**\n * Converts radians to to degrees.\n *\n * @param {number} angleInRadians Angle in radians.\n * @return {number} Angle in degrees.\n */\nexport function toDegrees(angleInRadians) {\n return (angleInRadians * 180) / Math.PI;\n}\n\n/**\n * Converts degrees to radians.\n *\n * @param {number} angleInDegrees Angle in degrees.\n * @return {number} Angle in radians.\n */\nexport function toRadians(angleInDegrees) {\n return (angleInDegrees * Math.PI) / 180;\n}\n\n/**\n * Returns the modulo of a / b, depending on the sign of b.\n *\n * @param {number} a Dividend.\n * @param {number} b Divisor.\n * @return {number} Modulo.\n */\nexport function modulo(a, b) {\n const r = a % b;\n return r * b < 0 ? r + b : r;\n}\n\n/**\n * Calculates the linearly interpolated value of x between a and b.\n *\n * @param {number} a Number\n * @param {number} b Number\n * @param {number} x Value to be interpolated.\n * @return {number} Interpolated value.\n */\nexport function lerp(a, b, x) {\n return a + x * (b - a);\n}\n\n/**\n * Returns a number with a limited number of decimal digits.\n * @param {number} n The input number.\n * @param {number} decimals The maximum number of decimal digits.\n * @return {number} The input number with a limited number of decimal digits.\n */\nexport function toFixed(n, decimals) {\n const factor = Math.pow(10, decimals);\n return Math.round(n * factor) / factor;\n}\n\n/**\n * Rounds a number to the nearest integer value considering only the given number\n * of decimal digits (with rounding on the final digit).\n * @param {number} n The input number.\n * @param {number} decimals The maximum number of decimal digits.\n * @return {number} The nearest integer.\n */\nexport function round(n, decimals) {\n return Math.round(toFixed(n, decimals));\n}\n\n/**\n * Rounds a number to the next smaller integer considering only the given number\n * of decimal digits (with rounding on the final digit).\n * @param {number} n The input number.\n * @param {number} decimals The maximum number of decimal digits.\n * @return {number} The next smaller integer.\n */\nexport function floor(n, decimals) {\n return Math.floor(toFixed(n, decimals));\n}\n\n/**\n * Rounds a number to the next bigger integer considering only the given number\n * of decimal digits (with rounding on the final digit).\n * @param {number} n The input number.\n * @param {number} decimals The maximum number of decimal digits.\n * @return {number} The next bigger integer.\n */\nexport function ceil(n, decimals) {\n return Math.ceil(toFixed(n, decimals));\n}\n","/**\n * @module ol/string\n */\n\n/**\n * @param {number} number Number to be formatted\n * @param {number} width The desired width\n * @param {number} [precision] Precision of the output string (i.e. number of decimal places)\n * @return {string} Formatted string\n */\nexport function padNumber(number, width, precision) {\n const numberString =\n precision !== undefined ? number.toFixed(precision) : '' + number;\n let decimal = numberString.indexOf('.');\n decimal = decimal === -1 ? numberString.length : decimal;\n return decimal > width\n ? numberString\n : new Array(1 + width - decimal).join('0') + numberString;\n}\n\n/**\n * Adapted from https://github.com/omichelsen/compare-versions/blob/master/index.js\n * @param {string|number} v1 First version\n * @param {string|number} v2 Second version\n * @return {number} Value\n */\nexport function compareVersions(v1, v2) {\n const s1 = ('' + v1).split('.');\n const s2 = ('' + v2).split('.');\n\n for (let i = 0; i < Math.max(s1.length, s2.length); i++) {\n const n1 = parseInt(s1[i] || '0', 10);\n const n2 = parseInt(s2[i] || '0', 10);\n\n if (n1 > n2) {\n return 1;\n }\n if (n2 > n1) {\n return -1;\n }\n }\n\n return 0;\n}\n","/**\n * @module ol/coordinate\n */\nimport {getWidth} from './extent.js';\nimport {modulo, toFixed} from './math.js';\nimport {padNumber} from './string.js';\n\n/**\n * An array of numbers representing an `xy`, `xyz` or `xyzm` coordinate.\n * Example: `[16, 48]`.\n * @typedef {Array} Coordinate\n * @api\n */\n\n/**\n * A function that takes a {@link module:ol/coordinate~Coordinate} and\n * transforms it into a `{string}`.\n *\n * @typedef {function((Coordinate|undefined)): string} CoordinateFormat\n * @api\n */\n\n/**\n * Add `delta` to `coordinate`. `coordinate` is modified in place and returned\n * by the function.\n *\n * Example:\n *\n * import {add} from 'ol/coordinate.js';\n *\n * const coord = [7.85, 47.983333];\n * add(coord, [-2, 4]);\n * // coord is now [5.85, 51.983333]\n *\n * @param {Coordinate} coordinate Coordinate.\n * @param {Coordinate} delta Delta.\n * @return {Coordinate} The input coordinate adjusted by\n * the given delta.\n * @api\n */\nexport function add(coordinate, delta) {\n coordinate[0] += +delta[0];\n coordinate[1] += +delta[1];\n return coordinate;\n}\n\n/**\n * Calculates the point closest to the passed coordinate on the passed circle.\n *\n * @param {Coordinate} coordinate The coordinate.\n * @param {import(\"./geom/Circle.js\").default} circle The circle.\n * @return {Coordinate} Closest point on the circumference.\n */\nexport function closestOnCircle(coordinate, circle) {\n const r = circle.getRadius();\n const center = circle.getCenter();\n const x0 = center[0];\n const y0 = center[1];\n const x1 = coordinate[0];\n const y1 = coordinate[1];\n\n let dx = x1 - x0;\n const dy = y1 - y0;\n if (dx === 0 && dy === 0) {\n dx = 1;\n }\n const d = Math.sqrt(dx * dx + dy * dy);\n\n const x = x0 + (r * dx) / d;\n const y = y0 + (r * dy) / d;\n\n return [x, y];\n}\n\n/**\n * Calculates the point closest to the passed coordinate on the passed segment.\n * This is the foot of the perpendicular of the coordinate to the segment when\n * the foot is on the segment, or the closest segment coordinate when the foot\n * is outside the segment.\n *\n * @param {Coordinate} coordinate The coordinate.\n * @param {Array} segment The two coordinates\n * of the segment.\n * @return {Coordinate} The foot of the perpendicular of\n * the coordinate to the segment.\n */\nexport function closestOnSegment(coordinate, segment) {\n const x0 = coordinate[0];\n const y0 = coordinate[1];\n const start = segment[0];\n const end = segment[1];\n const x1 = start[0];\n const y1 = start[1];\n const x2 = end[0];\n const y2 = end[1];\n const dx = x2 - x1;\n const dy = y2 - y1;\n const along =\n dx === 0 && dy === 0\n ? 0\n : (dx * (x0 - x1) + dy * (y0 - y1)) / (dx * dx + dy * dy || 0);\n let x, y;\n if (along <= 0) {\n x = x1;\n y = y1;\n } else if (along >= 1) {\n x = x2;\n y = y2;\n } else {\n x = x1 + along * dx;\n y = y1 + along * dy;\n }\n return [x, y];\n}\n\n/**\n * Returns a {@link module:ol/coordinate~CoordinateFormat} function that can be\n * used to format\n * a {Coordinate} to a string.\n *\n * Example without specifying the fractional digits:\n *\n * import {createStringXY} from 'ol/coordinate.js';\n *\n * const coord = [7.85, 47.983333];\n * const stringifyFunc = createStringXY();\n * const out = stringifyFunc(coord);\n * // out is now '8, 48'\n *\n * Example with explicitly specifying 2 fractional digits:\n *\n * import {createStringXY} from 'ol/coordinate.js';\n *\n * const coord = [7.85, 47.983333];\n * const stringifyFunc = createStringXY(2);\n * const out = stringifyFunc(coord);\n * // out is now '7.85, 47.98'\n *\n * @param {number} [fractionDigits] The number of digits to include\n * after the decimal point. Default is `0`.\n * @return {CoordinateFormat} Coordinate format.\n * @api\n */\nexport function createStringXY(fractionDigits) {\n return (\n /**\n * @param {Coordinate} coordinate Coordinate.\n * @return {string} String XY.\n */\n function (coordinate) {\n return toStringXY(coordinate, fractionDigits);\n }\n );\n}\n\n/**\n * @param {string} hemispheres Hemispheres.\n * @param {number} degrees Degrees.\n * @param {number} [fractionDigits] The number of digits to include\n * after the decimal point. Default is `0`.\n * @return {string} String.\n */\nexport function degreesToStringHDMS(hemispheres, degrees, fractionDigits) {\n const normalizedDegrees = modulo(degrees + 180, 360) - 180;\n const x = Math.abs(3600 * normalizedDegrees);\n const decimals = fractionDigits || 0;\n\n let deg = Math.floor(x / 3600);\n let min = Math.floor((x - deg * 3600) / 60);\n let sec = toFixed(x - deg * 3600 - min * 60, decimals);\n\n if (sec >= 60) {\n sec = 0;\n min += 1;\n }\n\n if (min >= 60) {\n min = 0;\n deg += 1;\n }\n\n let hdms = deg + '\\u00b0';\n if (min !== 0 || sec !== 0) {\n hdms += ' ' + padNumber(min, 2) + '\\u2032';\n }\n if (sec !== 0) {\n hdms += ' ' + padNumber(sec, 2, decimals) + '\\u2033';\n }\n if (normalizedDegrees !== 0) {\n hdms += ' ' + hemispheres.charAt(normalizedDegrees < 0 ? 1 : 0);\n }\n\n return hdms;\n}\n\n/**\n * Transforms the given {@link module:ol/coordinate~Coordinate} to a string\n * using the given string template. The strings `{x}` and `{y}` in the template\n * will be replaced with the first and second coordinate values respectively.\n *\n * Example without specifying the fractional digits:\n *\n * import {format} from 'ol/coordinate.js';\n *\n * const coord = [7.85, 47.983333];\n * const template = 'Coordinate is ({x}|{y}).';\n * const out = format(coord, template);\n * // out is now 'Coordinate is (8|48).'\n *\n * Example explicitly specifying the fractional digits:\n *\n * import {format} from 'ol/coordinate.js';\n *\n * const coord = [7.85, 47.983333];\n * const template = 'Coordinate is ({x}|{y}).';\n * const out = format(coord, template, 2);\n * // out is now 'Coordinate is (7.85|47.98).'\n *\n * @param {Coordinate} coordinate Coordinate.\n * @param {string} template A template string with `{x}` and `{y}` placeholders\n * that will be replaced by first and second coordinate values.\n * @param {number} [fractionDigits] The number of digits to include\n * after the decimal point. Default is `0`.\n * @return {string} Formatted coordinate.\n * @api\n */\nexport function format(coordinate, template, fractionDigits) {\n if (coordinate) {\n return template\n .replace('{x}', coordinate[0].toFixed(fractionDigits))\n .replace('{y}', coordinate[1].toFixed(fractionDigits));\n }\n return '';\n}\n\n/**\n * @param {Coordinate} coordinate1 First coordinate.\n * @param {Coordinate} coordinate2 Second coordinate.\n * @return {boolean} The two coordinates are equal.\n */\nexport function equals(coordinate1, coordinate2) {\n let equals = true;\n for (let i = coordinate1.length - 1; i >= 0; --i) {\n if (coordinate1[i] != coordinate2[i]) {\n equals = false;\n break;\n }\n }\n return equals;\n}\n\n/**\n * Rotate `coordinate` by `angle`. `coordinate` is modified in place and\n * returned by the function.\n *\n * Example:\n *\n * import {rotate} from 'ol/coordinate.js';\n *\n * const coord = [7.85, 47.983333];\n * const rotateRadians = Math.PI / 2; // 90 degrees\n * rotate(coord, rotateRadians);\n * // coord is now [-47.983333, 7.85]\n *\n * @param {Coordinate} coordinate Coordinate.\n * @param {number} angle Angle in radian.\n * @return {Coordinate} Coordinate.\n * @api\n */\nexport function rotate(coordinate, angle) {\n const cosAngle = Math.cos(angle);\n const sinAngle = Math.sin(angle);\n const x = coordinate[0] * cosAngle - coordinate[1] * sinAngle;\n const y = coordinate[1] * cosAngle + coordinate[0] * sinAngle;\n coordinate[0] = x;\n coordinate[1] = y;\n return coordinate;\n}\n\n/**\n * Scale `coordinate` by `scale`. `coordinate` is modified in place and returned\n * by the function.\n *\n * Example:\n *\n * import {scale as scaleCoordinate} from 'ol/coordinate.js';\n *\n * const coord = [7.85, 47.983333];\n * const scale = 1.2;\n * scaleCoordinate(coord, scale);\n * // coord is now [9.42, 57.5799996]\n *\n * @param {Coordinate} coordinate Coordinate.\n * @param {number} scale Scale factor.\n * @return {Coordinate} Coordinate.\n */\nexport function scale(coordinate, scale) {\n coordinate[0] *= scale;\n coordinate[1] *= scale;\n return coordinate;\n}\n\n/**\n * @param {Coordinate} coord1 First coordinate.\n * @param {Coordinate} coord2 Second coordinate.\n * @return {number} Squared distance between coord1 and coord2.\n */\nexport function squaredDistance(coord1, coord2) {\n const dx = coord1[0] - coord2[0];\n const dy = coord1[1] - coord2[1];\n return dx * dx + dy * dy;\n}\n\n/**\n * @param {Coordinate} coord1 First coordinate.\n * @param {Coordinate} coord2 Second coordinate.\n * @return {number} Distance between coord1 and coord2.\n */\nexport function distance(coord1, coord2) {\n return Math.sqrt(squaredDistance(coord1, coord2));\n}\n\n/**\n * Calculate the squared distance from a coordinate to a line segment.\n *\n * @param {Coordinate} coordinate Coordinate of the point.\n * @param {Array} segment Line segment (2\n * coordinates).\n * @return {number} Squared distance from the point to the line segment.\n */\nexport function squaredDistanceToSegment(coordinate, segment) {\n return squaredDistance(coordinate, closestOnSegment(coordinate, segment));\n}\n\n/**\n * Format a geographic coordinate with the hemisphere, degrees, minutes, and\n * seconds.\n *\n * Example without specifying fractional digits:\n *\n * import {toStringHDMS} from 'ol/coordinate.js';\n *\n * const coord = [7.85, 47.983333];\n * const out = toStringHDMS(coord);\n * // out is now '47° 58′ 60″ N 7° 50′ 60″ E'\n *\n * Example explicitly specifying 1 fractional digit:\n *\n * import {toStringHDMS} from 'ol/coordinate.js';\n *\n * const coord = [7.85, 47.983333];\n * const out = toStringHDMS(coord, 1);\n * // out is now '47° 58′ 60.0″ N 7° 50′ 60.0″ E'\n *\n * @param {Coordinate} coordinate Coordinate.\n * @param {number} [fractionDigits] The number of digits to include\n * after the decimal point. Default is `0`.\n * @return {string} Hemisphere, degrees, minutes and seconds.\n * @api\n */\nexport function toStringHDMS(coordinate, fractionDigits) {\n if (coordinate) {\n return (\n degreesToStringHDMS('NS', coordinate[1], fractionDigits) +\n ' ' +\n degreesToStringHDMS('EW', coordinate[0], fractionDigits)\n );\n }\n return '';\n}\n\n/**\n * Format a coordinate as a comma delimited string.\n *\n * Example without specifying fractional digits:\n *\n * import {toStringXY} from 'ol/coordinate.js';\n *\n * const coord = [7.85, 47.983333];\n * const out = toStringXY(coord);\n * // out is now '8, 48'\n *\n * Example explicitly specifying 1 fractional digit:\n *\n * import {toStringXY} from 'ol/coordinate.js';\n *\n * const coord = [7.85, 47.983333];\n * const out = toStringXY(coord, 1);\n * // out is now '7.8, 48.0'\n *\n * @param {Coordinate} coordinate Coordinate.\n * @param {number} [fractionDigits] The number of digits to include\n * after the decimal point. Default is `0`.\n * @return {string} XY.\n * @api\n */\nexport function toStringXY(coordinate, fractionDigits) {\n return format(coordinate, '{x}, {y}', fractionDigits);\n}\n\n/**\n * Modifies the provided coordinate in-place to be within the real world\n * extent. The lower projection extent boundary is inclusive, the upper one\n * exclusive.\n *\n * @param {Coordinate} coordinate Coordinate.\n * @param {import(\"./proj/Projection.js\").default} projection Projection.\n * @return {Coordinate} The coordinate within the real world extent.\n */\nexport function wrapX(coordinate, projection) {\n if (projection.canWrapX()) {\n const worldWidth = getWidth(projection.getExtent());\n const worldsAway = getWorldsAway(coordinate, projection, worldWidth);\n if (worldsAway) {\n coordinate[0] -= worldsAway * worldWidth;\n }\n }\n return coordinate;\n}\n/**\n * @param {Coordinate} coordinate Coordinate.\n * @param {import(\"./proj/Projection.js\").default} projection Projection.\n * @param {number} [sourceExtentWidth] Width of the source extent.\n * @return {number} Offset in world widths.\n */\nexport function getWorldsAway(coordinate, projection, sourceExtentWidth) {\n const projectionExtent = projection.getExtent();\n let worldsAway = 0;\n if (\n projection.canWrapX() &&\n (coordinate[0] < projectionExtent[0] || coordinate[0] > projectionExtent[2])\n ) {\n sourceExtentWidth = sourceExtentWidth || getWidth(projectionExtent);\n worldsAway = Math.floor(\n (coordinate[0] - projectionExtent[0]) / sourceExtentWidth\n );\n }\n return worldsAway;\n}\n","/**\n * @module ol/sphere\n */\nimport {toDegrees, toRadians} from './math.js';\n\n/**\n * Object literal with options for the {@link getLength} or {@link getArea}\n * functions.\n * @typedef {Object} SphereMetricOptions\n * @property {import(\"./proj.js\").ProjectionLike} [projection='EPSG:3857']\n * Projection of the geometry. By default, the geometry is assumed to be in\n * Web Mercator.\n * @property {number} [radius=6371008.8] Sphere radius. By default, the\n * [mean Earth radius](https://en.wikipedia.org/wiki/Earth_radius#Mean_radius)\n * for the WGS84 ellipsoid is used.\n */\n\n/**\n * The mean Earth radius (1/3 * (2a + b)) for the WGS84 ellipsoid.\n * https://en.wikipedia.org/wiki/Earth_radius#Mean_radius\n * @type {number}\n */\nexport const DEFAULT_RADIUS = 6371008.8;\n\n/**\n * Get the great circle distance (in meters) between two geographic coordinates.\n * @param {Array} c1 Starting coordinate.\n * @param {Array} c2 Ending coordinate.\n * @param {number} [radius] The sphere radius to use. Defaults to the Earth's\n * mean radius using the WGS84 ellipsoid.\n * @return {number} The great circle distance between the points (in meters).\n * @api\n */\nexport function getDistance(c1, c2, radius) {\n radius = radius || DEFAULT_RADIUS;\n const lat1 = toRadians(c1[1]);\n const lat2 = toRadians(c2[1]);\n const deltaLatBy2 = (lat2 - lat1) / 2;\n const deltaLonBy2 = toRadians(c2[0] - c1[0]) / 2;\n const a =\n Math.sin(deltaLatBy2) * Math.sin(deltaLatBy2) +\n Math.sin(deltaLonBy2) *\n Math.sin(deltaLonBy2) *\n Math.cos(lat1) *\n Math.cos(lat2);\n return 2 * radius * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n}\n\n/**\n * Get the cumulative great circle length of linestring coordinates (geographic).\n * @param {Array} coordinates Linestring coordinates.\n * @param {number} radius The sphere radius to use.\n * @return {number} The length (in meters).\n */\nfunction getLengthInternal(coordinates, radius) {\n let length = 0;\n for (let i = 0, ii = coordinates.length; i < ii - 1; ++i) {\n length += getDistance(coordinates[i], coordinates[i + 1], radius);\n }\n return length;\n}\n\n/**\n * Get the spherical length of a geometry. This length is the sum of the\n * great circle distances between coordinates. For polygons, the length is\n * the sum of all rings. For points, the length is zero. For multi-part\n * geometries, the length is the sum of the length of each part.\n * @param {import(\"./geom/Geometry.js\").default} geometry A geometry.\n * @param {SphereMetricOptions} [options] Options for the\n * length calculation. By default, geometries are assumed to be in 'EPSG:3857'.\n * You can change this by providing a `projection` option.\n * @return {number} The spherical length (in meters).\n * @api\n */\nexport function getLength(geometry, options) {\n options = options || {};\n const radius = options.radius || DEFAULT_RADIUS;\n const projection = options.projection || 'EPSG:3857';\n const type = geometry.getType();\n if (type !== 'GeometryCollection') {\n geometry = geometry.clone().transform(projection, 'EPSG:4326');\n }\n let length = 0;\n let coordinates, coords, i, ii, j, jj;\n switch (type) {\n case 'Point':\n case 'MultiPoint': {\n break;\n }\n case 'LineString':\n case 'LinearRing': {\n coordinates = /** @type {import(\"./geom/SimpleGeometry.js\").default} */ (\n geometry\n ).getCoordinates();\n length = getLengthInternal(coordinates, radius);\n break;\n }\n case 'MultiLineString':\n case 'Polygon': {\n coordinates = /** @type {import(\"./geom/SimpleGeometry.js\").default} */ (\n geometry\n ).getCoordinates();\n for (i = 0, ii = coordinates.length; i < ii; ++i) {\n length += getLengthInternal(coordinates[i], radius);\n }\n break;\n }\n case 'MultiPolygon': {\n coordinates = /** @type {import(\"./geom/SimpleGeometry.js\").default} */ (\n geometry\n ).getCoordinates();\n for (i = 0, ii = coordinates.length; i < ii; ++i) {\n coords = coordinates[i];\n for (j = 0, jj = coords.length; j < jj; ++j) {\n length += getLengthInternal(coords[j], radius);\n }\n }\n break;\n }\n case 'GeometryCollection': {\n const geometries =\n /** @type {import(\"./geom/GeometryCollection.js\").default} */ (\n geometry\n ).getGeometries();\n for (i = 0, ii = geometries.length; i < ii; ++i) {\n length += getLength(geometries[i], options);\n }\n break;\n }\n default: {\n throw new Error('Unsupported geometry type: ' + type);\n }\n }\n return length;\n}\n\n/**\n * Returns the spherical area for a list of coordinates.\n *\n * [Reference](https://trs.jpl.nasa.gov/handle/2014/40409)\n * Robert. G. Chamberlain and William H. Duquette, \"Some Algorithms for\n * Polygons on a Sphere\", JPL Publication 07-03, Jet Propulsion\n * Laboratory, Pasadena, CA, June 2007\n *\n * @param {Array} coordinates List of coordinates of a linear\n * ring. If the ring is oriented clockwise, the area will be positive,\n * otherwise it will be negative.\n * @param {number} radius The sphere radius.\n * @return {number} Area (in square meters).\n */\nfunction getAreaInternal(coordinates, radius) {\n let area = 0;\n const len = coordinates.length;\n let x1 = coordinates[len - 1][0];\n let y1 = coordinates[len - 1][1];\n for (let i = 0; i < len; i++) {\n const x2 = coordinates[i][0];\n const y2 = coordinates[i][1];\n area +=\n toRadians(x2 - x1) *\n (2 + Math.sin(toRadians(y1)) + Math.sin(toRadians(y2)));\n x1 = x2;\n y1 = y2;\n }\n return (area * radius * radius) / 2.0;\n}\n\n/**\n * Get the spherical area of a geometry. This is the area (in meters) assuming\n * that polygon edges are segments of great circles on a sphere.\n * @param {import(\"./geom/Geometry.js\").default} geometry A geometry.\n * @param {SphereMetricOptions} [options] Options for the area\n * calculation. By default, geometries are assumed to be in 'EPSG:3857'.\n * You can change this by providing a `projection` option.\n * @return {number} The spherical area (in square meters).\n * @api\n */\nexport function getArea(geometry, options) {\n options = options || {};\n const radius = options.radius || DEFAULT_RADIUS;\n const projection = options.projection || 'EPSG:3857';\n const type = geometry.getType();\n if (type !== 'GeometryCollection') {\n geometry = geometry.clone().transform(projection, 'EPSG:4326');\n }\n let area = 0;\n let coordinates, coords, i, ii, j, jj;\n switch (type) {\n case 'Point':\n case 'MultiPoint':\n case 'LineString':\n case 'MultiLineString':\n case 'LinearRing': {\n break;\n }\n case 'Polygon': {\n coordinates = /** @type {import(\"./geom/Polygon.js\").default} */ (\n geometry\n ).getCoordinates();\n area = Math.abs(getAreaInternal(coordinates[0], radius));\n for (i = 1, ii = coordinates.length; i < ii; ++i) {\n area -= Math.abs(getAreaInternal(coordinates[i], radius));\n }\n break;\n }\n case 'MultiPolygon': {\n coordinates = /** @type {import(\"./geom/SimpleGeometry.js\").default} */ (\n geometry\n ).getCoordinates();\n for (i = 0, ii = coordinates.length; i < ii; ++i) {\n coords = coordinates[i];\n area += Math.abs(getAreaInternal(coords[0], radius));\n for (j = 1, jj = coords.length; j < jj; ++j) {\n area -= Math.abs(getAreaInternal(coords[j], radius));\n }\n }\n break;\n }\n case 'GeometryCollection': {\n const geometries =\n /** @type {import(\"./geom/GeometryCollection.js\").default} */ (\n geometry\n ).getGeometries();\n for (i = 0, ii = geometries.length; i < ii; ++i) {\n area += getArea(geometries[i], options);\n }\n break;\n }\n default: {\n throw new Error('Unsupported geometry type: ' + type);\n }\n }\n return area;\n}\n\n/**\n * Returns the coordinate at the given distance and bearing from `c1`.\n *\n * @param {import(\"./coordinate.js\").Coordinate} c1 The origin point (`[lon, lat]` in degrees).\n * @param {number} distance The great-circle distance between the origin\n * point and the target point.\n * @param {number} bearing The bearing (in radians).\n * @param {number} [radius] The sphere radius to use. Defaults to the Earth's\n * mean radius using the WGS84 ellipsoid.\n * @return {import(\"./coordinate.js\").Coordinate} The target point.\n */\nexport function offset(c1, distance, bearing, radius) {\n radius = radius || DEFAULT_RADIUS;\n const lat1 = toRadians(c1[1]);\n const lon1 = toRadians(c1[0]);\n const dByR = distance / radius;\n const lat = Math.asin(\n Math.sin(lat1) * Math.cos(dByR) +\n Math.cos(lat1) * Math.sin(dByR) * Math.cos(bearing)\n );\n const lon =\n lon1 +\n Math.atan2(\n Math.sin(bearing) * Math.sin(dByR) * Math.cos(lat1),\n Math.cos(dByR) - Math.sin(lat1) * Math.sin(lat)\n );\n return [toDegrees(lon), toDegrees(lat)];\n}\n","/**\n * @module ol/console\n */\n\n/**\n * @typedef {'info'|'warn'|'error'|'none'} Level\n */\n\n/**\n * @type {Object}\n */\nconst levels = {\n info: 1,\n warn: 2,\n error: 3,\n none: 4,\n};\n\n/**\n * @type {number}\n */\nlet level = levels.info;\n\n/**\n * Set the logging level. By default, the level is set to 'info' and all\n * messages will be logged. Set to 'warn' to only display warnings and errors.\n * Set to 'error' to only display errors. Set to 'none' to silence all messages.\n *\n * @param {Level} l The new level.\n */\nexport function setLevel(l) {\n level = levels[l];\n}\n\nexport function log(...args) {\n if (level > levels.info) {\n return;\n }\n console.log(...args); // eslint-disable-line no-console\n}\n\nexport function warn(...args) {\n if (level > levels.warn) {\n return;\n }\n console.warn(...args); // eslint-disable-line no-console\n}\n\nexport function error(...args) {\n if (level > levels.error) {\n return;\n }\n console.error(...args); // eslint-disable-line no-console\n}\n","/**\n * @module ol/proj\n */\n\n/**\n * The ol/proj module stores:\n * * a list of {@link module:ol/proj/Projection~Projection}\n * objects, one for each projection supported by the application\n * * a list of transform functions needed to convert coordinates in one projection\n * into another.\n *\n * The static functions are the methods used to maintain these.\n * Each transform function can handle not only simple coordinate pairs, but also\n * large arrays of coordinates such as vector geometries.\n *\n * When loaded, the library adds projection objects for EPSG:4326 (WGS84\n * geographic coordinates) and EPSG:3857 (Web or Spherical Mercator, as used\n * for example by Bing Maps or OpenStreetMap), together with the relevant\n * transform functions.\n *\n * Additional transforms may be added by using the http://proj4js.org/\n * library (version 2.2 or later). You can use the full build supplied by\n * Proj4js, or create a custom build to support those projections you need; see\n * the Proj4js website for how to do this. You also need the Proj4js definitions\n * for the required projections. These definitions can be obtained from\n * https://epsg.io/, and are a JS function, so can be loaded in a script\n * tag (as in the examples) or pasted into your application.\n *\n * After all required projection definitions are added to proj4's registry (by\n * using `proj4.defs()`), simply call `register(proj4)` from the `ol/proj/proj4`\n * package. Existing transforms are not changed by this function. See\n * examples/wms-image-custom-proj for an example of this.\n *\n * Additional projection definitions can be registered with `proj4.defs()` any\n * time. Just make sure to call `register(proj4)` again; for example, with user-supplied data where you don't\n * know in advance what projections are needed, you can initially load minimal\n * support and then load whichever are requested.\n *\n * Note that Proj4js does not support projection extents. If you want to add\n * one for creating default tile grids, you can add it after the Projection\n * object has been created with `setExtent`, for example,\n * `get('EPSG:1234').setExtent(extent)`.\n *\n * In addition to Proj4js support, any transform functions can be added with\n * {@link module:ol/proj.addCoordinateTransforms}. To use this, you must first create\n * a {@link module:ol/proj/Projection~Projection} object for the new projection and add it with\n * {@link module:ol/proj.addProjection}. You can then add the forward and inverse\n * functions with {@link module:ol/proj.addCoordinateTransforms}. See\n * examples/wms-custom-proj for an example of this.\n *\n * Note that if no transforms are needed and you only need to define the\n * projection, just add a {@link module:ol/proj/Projection~Projection} with\n * {@link module:ol/proj.addProjection}. See examples/wms-no-proj for an example of\n * this.\n */\nimport Projection from './proj/Projection.js';\nimport {\n PROJECTIONS as EPSG3857_PROJECTIONS,\n fromEPSG4326,\n toEPSG4326,\n} from './proj/epsg3857.js';\nimport {PROJECTIONS as EPSG4326_PROJECTIONS} from './proj/epsg4326.js';\nimport {METERS_PER_UNIT} from './proj/Units.js';\nimport {\n add as addProj,\n clear as clearProj,\n get as getProj,\n} from './proj/projections.js';\nimport {\n add as addTransformFunc,\n clear as clearTransformFuncs,\n get as getTransformFunc,\n} from './proj/transforms.js';\nimport {applyTransform, getWidth} from './extent.js';\nimport {clamp, modulo} from './math.js';\nimport {equals, getWorldsAway} from './coordinate.js';\nimport {getDistance} from './sphere.js';\nimport {warn} from './console.js';\n\n/**\n * A projection as {@link module:ol/proj/Projection~Projection}, SRS identifier\n * string or undefined.\n * @typedef {Projection|string|undefined} ProjectionLike\n * @api\n */\n\n/**\n * A transform function accepts an array of input coordinate values, an optional\n * output array, and an optional dimension (default should be 2). The function\n * transforms the input coordinate values, populates the output array, and\n * returns the output array.\n *\n * @typedef {function(Array, Array=, number=): Array} TransformFunction\n * @api\n */\n\nexport {METERS_PER_UNIT};\n\nexport {Projection};\n\nlet showCoordinateWarning = true;\n\n/**\n * @param {boolean} [disable = true] Disable console info about `useGeographic()`\n */\nexport function disableCoordinateWarning(disable) {\n const hide = disable === undefined ? true : disable;\n showCoordinateWarning = !hide;\n}\n\n/**\n * @param {Array} input Input coordinate array.\n * @param {Array} [output] Output array of coordinate values.\n * @return {Array} Output coordinate array (new array, same coordinate\n * values).\n */\nexport function cloneTransform(input, output) {\n if (output !== undefined) {\n for (let i = 0, ii = input.length; i < ii; ++i) {\n output[i] = input[i];\n }\n output = output;\n } else {\n output = input.slice();\n }\n return output;\n}\n\n/**\n * @param {Array} input Input coordinate array.\n * @param {Array} [output] Output array of coordinate values.\n * @return {Array} Input coordinate array (same array as input).\n */\nexport function identityTransform(input, output) {\n if (output !== undefined && input !== output) {\n for (let i = 0, ii = input.length; i < ii; ++i) {\n output[i] = input[i];\n }\n input = output;\n }\n return input;\n}\n\n/**\n * Add a Projection object to the list of supported projections that can be\n * looked up by their code.\n *\n * @param {Projection} projection Projection instance.\n * @api\n */\nexport function addProjection(projection) {\n addProj(projection.getCode(), projection);\n addTransformFunc(projection, projection, cloneTransform);\n}\n\n/**\n * @param {Array} projections Projections.\n */\nexport function addProjections(projections) {\n projections.forEach(addProjection);\n}\n\n/**\n * Fetches a Projection object for the code specified.\n *\n * @param {ProjectionLike} projectionLike Either a code string which is\n * a combination of authority and identifier such as \"EPSG:4326\", or an\n * existing projection object, or undefined.\n * @return {Projection|null} Projection object, or null if not in list.\n * @api\n */\nexport function get(projectionLike) {\n return typeof projectionLike === 'string'\n ? getProj(/** @type {string} */ (projectionLike))\n : /** @type {Projection} */ (projectionLike) || null;\n}\n\n/**\n * Get the resolution of the point in degrees or distance units.\n * For projections with degrees as the unit this will simply return the\n * provided resolution. For other projections the point resolution is\n * by default estimated by transforming the `point` pixel to EPSG:4326,\n * measuring its width and height on the normal sphere,\n * and taking the average of the width and height.\n * A custom function can be provided for a specific projection, either\n * by setting the `getPointResolution` option in the\n * {@link module:ol/proj/Projection~Projection} constructor or by using\n * {@link module:ol/proj/Projection~Projection#setGetPointResolution} to change an existing\n * projection object.\n * @param {ProjectionLike} projection The projection.\n * @param {number} resolution Nominal resolution in projection units.\n * @param {import(\"./coordinate.js\").Coordinate} point Point to find adjusted resolution at.\n * @param {import(\"./proj/Units.js\").Units} [units] Units to get the point resolution in.\n * Default is the projection's units.\n * @return {number} Point resolution.\n * @api\n */\nexport function getPointResolution(projection, resolution, point, units) {\n projection = get(projection);\n let pointResolution;\n const getter = projection.getPointResolutionFunc();\n if (getter) {\n pointResolution = getter(resolution, point);\n if (units && units !== projection.getUnits()) {\n const metersPerUnit = projection.getMetersPerUnit();\n if (metersPerUnit) {\n pointResolution =\n (pointResolution * metersPerUnit) / METERS_PER_UNIT[units];\n }\n }\n } else {\n const projUnits = projection.getUnits();\n if ((projUnits == 'degrees' && !units) || units == 'degrees') {\n pointResolution = resolution;\n } else {\n // Estimate point resolution by transforming the center pixel to EPSG:4326,\n // measuring its width and height on the normal sphere, and taking the\n // average of the width and height.\n const toEPSG4326 = getTransformFromProjections(\n projection,\n get('EPSG:4326')\n );\n if (toEPSG4326 === identityTransform && projUnits !== 'degrees') {\n // no transform is available\n pointResolution = resolution * projection.getMetersPerUnit();\n } else {\n let vertices = [\n point[0] - resolution / 2,\n point[1],\n point[0] + resolution / 2,\n point[1],\n point[0],\n point[1] - resolution / 2,\n point[0],\n point[1] + resolution / 2,\n ];\n vertices = toEPSG4326(vertices, vertices, 2);\n const width = getDistance(vertices.slice(0, 2), vertices.slice(2, 4));\n const height = getDistance(vertices.slice(4, 6), vertices.slice(6, 8));\n pointResolution = (width + height) / 2;\n }\n const metersPerUnit = units\n ? METERS_PER_UNIT[units]\n : projection.getMetersPerUnit();\n if (metersPerUnit !== undefined) {\n pointResolution /= metersPerUnit;\n }\n }\n }\n return pointResolution;\n}\n\n/**\n * Registers transformation functions that don't alter coordinates. Those allow\n * to transform between projections with equal meaning.\n *\n * @param {Array} projections Projections.\n * @api\n */\nexport function addEquivalentProjections(projections) {\n addProjections(projections);\n projections.forEach(function (source) {\n projections.forEach(function (destination) {\n if (source !== destination) {\n addTransformFunc(source, destination, cloneTransform);\n }\n });\n });\n}\n\n/**\n * Registers transformation functions to convert coordinates in any projection\n * in projection1 to any projection in projection2.\n *\n * @param {Array} projections1 Projections with equal\n * meaning.\n * @param {Array} projections2 Projections with equal\n * meaning.\n * @param {TransformFunction} forwardTransform Transformation from any\n * projection in projection1 to any projection in projection2.\n * @param {TransformFunction} inverseTransform Transform from any projection\n * in projection2 to any projection in projection1..\n */\nexport function addEquivalentTransforms(\n projections1,\n projections2,\n forwardTransform,\n inverseTransform\n) {\n projections1.forEach(function (projection1) {\n projections2.forEach(function (projection2) {\n addTransformFunc(projection1, projection2, forwardTransform);\n addTransformFunc(projection2, projection1, inverseTransform);\n });\n });\n}\n\n/**\n * Clear all cached projections and transforms.\n */\nexport function clearAllProjections() {\n clearProj();\n clearTransformFuncs();\n}\n\n/**\n * @param {Projection|string|undefined} projection Projection.\n * @param {string} defaultCode Default code.\n * @return {Projection} Projection.\n */\nexport function createProjection(projection, defaultCode) {\n if (!projection) {\n return get(defaultCode);\n }\n if (typeof projection === 'string') {\n return get(projection);\n }\n return /** @type {Projection} */ (projection);\n}\n\n/**\n * Creates a {@link module:ol/proj~TransformFunction} from a simple 2D coordinate transform\n * function.\n * @param {function(import(\"./coordinate.js\").Coordinate): import(\"./coordinate.js\").Coordinate} coordTransform Coordinate\n * transform.\n * @return {TransformFunction} Transform function.\n */\nexport function createTransformFromCoordinateTransform(coordTransform) {\n return (\n /**\n * @param {Array} input Input.\n * @param {Array} [output] Output.\n * @param {number} [dimension] Dimension.\n * @return {Array} Output.\n */\n function (input, output, dimension) {\n const length = input.length;\n dimension = dimension !== undefined ? dimension : 2;\n output = output !== undefined ? output : new Array(length);\n for (let i = 0; i < length; i += dimension) {\n const point = coordTransform(input.slice(i, i + dimension));\n const pointLength = point.length;\n for (let j = 0, jj = dimension; j < jj; ++j) {\n output[i + j] = j >= pointLength ? input[i + j] : point[j];\n }\n }\n return output;\n }\n );\n}\n\n/**\n * Registers coordinate transform functions to convert coordinates between the\n * source projection and the destination projection.\n * The forward and inverse functions convert coordinate pairs; this function\n * converts these into the functions used internally which also handle\n * extents and coordinate arrays.\n *\n * @param {ProjectionLike} source Source projection.\n * @param {ProjectionLike} destination Destination projection.\n * @param {function(import(\"./coordinate.js\").Coordinate): import(\"./coordinate.js\").Coordinate} forward The forward transform\n * function (that is, from the source projection to the destination\n * projection) that takes a {@link module:ol/coordinate~Coordinate} as argument and returns\n * the transformed {@link module:ol/coordinate~Coordinate}.\n * @param {function(import(\"./coordinate.js\").Coordinate): import(\"./coordinate.js\").Coordinate} inverse The inverse transform\n * function (that is, from the destination projection to the source\n * projection) that takes a {@link module:ol/coordinate~Coordinate} as argument and returns\n * the transformed {@link module:ol/coordinate~Coordinate}. If the transform function can only\n * transform less dimensions than the input coordinate, it is supposeed to return a coordinate\n * with only the length it can transform. The other dimensions will be taken unchanged from the\n * source.\n * @api\n */\nexport function addCoordinateTransforms(source, destination, forward, inverse) {\n const sourceProj = get(source);\n const destProj = get(destination);\n addTransformFunc(\n sourceProj,\n destProj,\n createTransformFromCoordinateTransform(forward)\n );\n addTransformFunc(\n destProj,\n sourceProj,\n createTransformFromCoordinateTransform(inverse)\n );\n}\n\n/**\n * Transforms a coordinate from longitude/latitude to a different projection.\n * @param {import(\"./coordinate.js\").Coordinate} coordinate Coordinate as longitude and latitude, i.e.\n * an array with longitude as 1st and latitude as 2nd element.\n * @param {ProjectionLike} [projection] Target projection. The\n * default is Web Mercator, i.e. 'EPSG:3857'.\n * @return {import(\"./coordinate.js\").Coordinate} Coordinate projected to the target projection.\n * @api\n */\nexport function fromLonLat(coordinate, projection) {\n disableCoordinateWarning();\n return transform(\n coordinate,\n 'EPSG:4326',\n projection !== undefined ? projection : 'EPSG:3857'\n );\n}\n\n/**\n * Transforms a coordinate to longitude/latitude.\n * @param {import(\"./coordinate.js\").Coordinate} coordinate Projected coordinate.\n * @param {ProjectionLike} [projection] Projection of the coordinate.\n * The default is Web Mercator, i.e. 'EPSG:3857'.\n * @return {import(\"./coordinate.js\").Coordinate} Coordinate as longitude and latitude, i.e. an array\n * with longitude as 1st and latitude as 2nd element.\n * @api\n */\nexport function toLonLat(coordinate, projection) {\n const lonLat = transform(\n coordinate,\n projection !== undefined ? projection : 'EPSG:3857',\n 'EPSG:4326'\n );\n const lon = lonLat[0];\n if (lon < -180 || lon > 180) {\n lonLat[0] = modulo(lon + 180, 360) - 180;\n }\n return lonLat;\n}\n\n/**\n * Checks if two projections are the same, that is every coordinate in one\n * projection does represent the same geographic point as the same coordinate in\n * the other projection.\n *\n * @param {Projection} projection1 Projection 1.\n * @param {Projection} projection2 Projection 2.\n * @return {boolean} Equivalent.\n * @api\n */\nexport function equivalent(projection1, projection2) {\n if (projection1 === projection2) {\n return true;\n }\n const equalUnits = projection1.getUnits() === projection2.getUnits();\n if (projection1.getCode() === projection2.getCode()) {\n return equalUnits;\n }\n const transformFunc = getTransformFromProjections(projection1, projection2);\n return transformFunc === cloneTransform && equalUnits;\n}\n\n/**\n * Searches in the list of transform functions for the function for converting\n * coordinates from the source projection to the destination projection.\n *\n * @param {Projection} sourceProjection Source Projection object.\n * @param {Projection} destinationProjection Destination Projection\n * object.\n * @return {TransformFunction} Transform function.\n */\nexport function getTransformFromProjections(\n sourceProjection,\n destinationProjection\n) {\n const sourceCode = sourceProjection.getCode();\n const destinationCode = destinationProjection.getCode();\n let transformFunc = getTransformFunc(sourceCode, destinationCode);\n if (!transformFunc) {\n transformFunc = identityTransform;\n }\n return transformFunc;\n}\n\n/**\n * Given the projection-like objects, searches for a transformation\n * function to convert a coordinates array from the source projection to the\n * destination projection.\n *\n * @param {ProjectionLike} source Source.\n * @param {ProjectionLike} destination Destination.\n * @return {TransformFunction} Transform function.\n * @api\n */\nexport function getTransform(source, destination) {\n const sourceProjection = get(source);\n const destinationProjection = get(destination);\n return getTransformFromProjections(sourceProjection, destinationProjection);\n}\n\n/**\n * Transforms a coordinate from source projection to destination projection.\n * This returns a new coordinate (and does not modify the original).\n *\n * See {@link module:ol/proj.transformExtent} for extent transformation.\n * See the transform method of {@link module:ol/geom/Geometry~Geometry} and its\n * subclasses for geometry transforms.\n *\n * @param {import(\"./coordinate.js\").Coordinate} coordinate Coordinate.\n * @param {ProjectionLike} source Source projection-like.\n * @param {ProjectionLike} destination Destination projection-like.\n * @return {import(\"./coordinate.js\").Coordinate} Coordinate.\n * @api\n */\nexport function transform(coordinate, source, destination) {\n const transformFunc = getTransform(source, destination);\n return transformFunc(coordinate, undefined, coordinate.length);\n}\n\n/**\n * Transforms an extent from source projection to destination projection. This\n * returns a new extent (and does not modify the original).\n *\n * @param {import(\"./extent.js\").Extent} extent The extent to transform.\n * @param {ProjectionLike} source Source projection-like.\n * @param {ProjectionLike} destination Destination projection-like.\n * @param {number} [stops] Number of stops per side used for the transform.\n * By default only the corners are used.\n * @return {import(\"./extent.js\").Extent} The transformed extent.\n * @api\n */\nexport function transformExtent(extent, source, destination, stops) {\n const transformFunc = getTransform(source, destination);\n return applyTransform(extent, transformFunc, undefined, stops);\n}\n\n/**\n * Transforms the given point to the destination projection.\n *\n * @param {import(\"./coordinate.js\").Coordinate} point Point.\n * @param {Projection} sourceProjection Source projection.\n * @param {Projection} destinationProjection Destination projection.\n * @return {import(\"./coordinate.js\").Coordinate} Point.\n */\nexport function transformWithProjections(\n point,\n sourceProjection,\n destinationProjection\n) {\n const transformFunc = getTransformFromProjections(\n sourceProjection,\n destinationProjection\n );\n return transformFunc(point);\n}\n\n/**\n * @type {Projection|null}\n */\nlet userProjection = null;\n\n/**\n * Set the projection for coordinates supplied from and returned by API methods.\n * This includes all API methods except for those interacting with tile grids,\n * plus {@link import(\"./Map.js\").FrameState} and {@link import(\"./View.js\").State}.\n * @param {ProjectionLike} projection The user projection.\n * @api\n */\nexport function setUserProjection(projection) {\n userProjection = get(projection);\n}\n\n/**\n * Clear the user projection if set.\n * @api\n */\nexport function clearUserProjection() {\n userProjection = null;\n}\n\n/**\n * Get the projection for coordinates supplied from and returned by API methods.\n * @return {Projection|null} The user projection (or null if not set).\n * @api\n */\nexport function getUserProjection() {\n return userProjection;\n}\n\n/**\n * Use geographic coordinates (WGS-84 datum) in API methods.\n * This includes all API methods except for those interacting with tile grids,\n * plus {@link import(\"./Map.js\").FrameState} and {@link import(\"./View.js\").State}.\n * @api\n */\nexport function useGeographic() {\n setUserProjection('EPSG:4326');\n}\n\n/**\n * Return a coordinate transformed into the user projection. If no user projection\n * is set, the original coordinate is returned.\n * @param {Array} coordinate Input coordinate.\n * @param {ProjectionLike} sourceProjection The input coordinate projection.\n * @return {Array} The input coordinate in the user projection.\n */\nexport function toUserCoordinate(coordinate, sourceProjection) {\n if (!userProjection) {\n return coordinate;\n }\n return transform(coordinate, sourceProjection, userProjection);\n}\n\n/**\n * Return a coordinate transformed from the user projection. If no user projection\n * is set, the original coordinate is returned.\n * @param {Array} coordinate Input coordinate.\n * @param {ProjectionLike} destProjection The destination projection.\n * @return {Array} The input coordinate transformed.\n */\nexport function fromUserCoordinate(coordinate, destProjection) {\n if (!userProjection) {\n if (\n showCoordinateWarning &&\n !equals(coordinate, [0, 0]) &&\n coordinate[0] >= -180 &&\n coordinate[0] <= 180 &&\n coordinate[1] >= -90 &&\n coordinate[1] <= 90\n ) {\n showCoordinateWarning = false;\n warn(\n 'Call useGeographic() from ol/proj once to work with [longitude, latitude] coordinates.'\n );\n }\n return coordinate;\n }\n return transform(coordinate, userProjection, destProjection);\n}\n\n/**\n * Return an extent transformed into the user projection. If no user projection\n * is set, the original extent is returned.\n * @param {import(\"./extent.js\").Extent} extent Input extent.\n * @param {ProjectionLike} sourceProjection The input extent projection.\n * @return {import(\"./extent.js\").Extent} The input extent in the user projection.\n */\nexport function toUserExtent(extent, sourceProjection) {\n if (!userProjection) {\n return extent;\n }\n return transformExtent(extent, sourceProjection, userProjection);\n}\n\n/**\n * Return an extent transformed from the user projection. If no user projection\n * is set, the original extent is returned.\n * @param {import(\"./extent.js\").Extent} extent Input extent.\n * @param {ProjectionLike} destProjection The destination projection.\n * @return {import(\"./extent.js\").Extent} The input extent transformed.\n */\nexport function fromUserExtent(extent, destProjection) {\n if (!userProjection) {\n return extent;\n }\n return transformExtent(extent, userProjection, destProjection);\n}\n\n/**\n * Return the resolution in user projection units per pixel. If no user projection\n * is set, or source or user projection are missing units, the original resolution\n * is returned.\n * @param {number} resolution Resolution in input projection units per pixel.\n * @param {ProjectionLike} sourceProjection The input projection.\n * @return {number} Resolution in user projection units per pixel.\n */\nexport function toUserResolution(resolution, sourceProjection) {\n if (!userProjection) {\n return resolution;\n }\n const sourceUnits = get(sourceProjection).getUnits();\n const userUnits = userProjection.getUnits();\n return sourceUnits && userUnits\n ? (resolution * METERS_PER_UNIT[sourceUnits]) / METERS_PER_UNIT[userUnits]\n : resolution;\n}\n\n/**\n * Return the resolution in user projection units per pixel. If no user projection\n * is set, or source or user projection are missing units, the original resolution\n * is returned.\n * @param {number} resolution Resolution in user projection units per pixel.\n * @param {ProjectionLike} destProjection The destination projection.\n * @return {number} Resolution in destination projection units per pixel.\n */\nexport function fromUserResolution(resolution, destProjection) {\n if (!userProjection) {\n return resolution;\n }\n const sourceUnits = get(destProjection).getUnits();\n const userUnits = userProjection.getUnits();\n return sourceUnits && userUnits\n ? (resolution * METERS_PER_UNIT[userUnits]) / METERS_PER_UNIT[sourceUnits]\n : resolution;\n}\n\n/**\n * Creates a safe coordinate transform function from a coordinate transform function.\n * \"Safe\" means that it can handle wrapping of x-coordinates for global projections,\n * and that coordinates exceeding the source projection validity extent's range will be\n * clamped to the validity range.\n * @param {Projection} sourceProj Source projection.\n * @param {Projection} destProj Destination projection.\n * @param {function(import(\"./coordinate.js\").Coordinate): import(\"./coordinate.js\").Coordinate} transform Transform function (source to destination).\n * @return {function(import(\"./coordinate.js\").Coordinate): import(\"./coordinate.js\").Coordinate} Safe transform function (source to destination).\n */\nexport function createSafeCoordinateTransform(sourceProj, destProj, transform) {\n return function (coord) {\n let transformed, worldsAway;\n if (sourceProj.canWrapX()) {\n const sourceExtent = sourceProj.getExtent();\n const sourceExtentWidth = getWidth(sourceExtent);\n coord = coord.slice(0);\n worldsAway = getWorldsAway(coord, sourceProj, sourceExtentWidth);\n if (worldsAway) {\n // Move x to the real world\n coord[0] = coord[0] - worldsAway * sourceExtentWidth;\n }\n coord[0] = clamp(coord[0], sourceExtent[0], sourceExtent[2]);\n coord[1] = clamp(coord[1], sourceExtent[1], sourceExtent[3]);\n transformed = transform(coord);\n } else {\n transformed = transform(coord);\n }\n if (worldsAway && destProj.canWrapX()) {\n // Move transformed coordinate back to the offset world\n transformed[0] += worldsAway * getWidth(destProj.getExtent());\n }\n return transformed;\n };\n}\n\n/**\n * Add transforms to and from EPSG:4326 and EPSG:3857. This function is called\n * by when this module is executed and should only need to be called again after\n * `clearAllProjections()` is called (e.g. in tests).\n */\nexport function addCommon() {\n // Add transformations that don't alter coordinates to convert within set of\n // projections with equal meaning.\n addEquivalentProjections(EPSG3857_PROJECTIONS);\n addEquivalentProjections(EPSG4326_PROJECTIONS);\n // Add transformations to convert EPSG:4326 like coordinates to EPSG:3857 like\n // coordinates and back.\n addEquivalentTransforms(\n EPSG4326_PROJECTIONS,\n EPSG3857_PROJECTIONS,\n fromEPSG4326,\n toEPSG4326\n );\n}\n\naddCommon();\n","/**\n * @module ol/geom/flat/transform\n */\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {import(\"../../transform.js\").Transform} transform Transform.\n * @param {Array} [dest] Destination.\n * @return {Array} Transformed coordinates.\n */\nexport function transform2D(\n flatCoordinates,\n offset,\n end,\n stride,\n transform,\n dest\n) {\n dest = dest ? dest : [];\n let i = 0;\n for (let j = offset; j < end; j += stride) {\n const x = flatCoordinates[j];\n const y = flatCoordinates[j + 1];\n dest[i++] = transform[0] * x + transform[2] * y + transform[4];\n dest[i++] = transform[1] * x + transform[3] * y + transform[5];\n }\n if (dest && dest.length != i) {\n dest.length = i;\n }\n return dest;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} angle Angle.\n * @param {Array} anchor Rotation anchor point.\n * @param {Array} [dest] Destination.\n * @return {Array} Transformed coordinates.\n */\nexport function rotate(\n flatCoordinates,\n offset,\n end,\n stride,\n angle,\n anchor,\n dest\n) {\n dest = dest ? dest : [];\n const cos = Math.cos(angle);\n const sin = Math.sin(angle);\n const anchorX = anchor[0];\n const anchorY = anchor[1];\n let i = 0;\n for (let j = offset; j < end; j += stride) {\n const deltaX = flatCoordinates[j] - anchorX;\n const deltaY = flatCoordinates[j + 1] - anchorY;\n dest[i++] = anchorX + deltaX * cos - deltaY * sin;\n dest[i++] = anchorY + deltaX * sin + deltaY * cos;\n for (let k = j + 2; k < j + stride; ++k) {\n dest[i++] = flatCoordinates[k];\n }\n }\n if (dest && dest.length != i) {\n dest.length = i;\n }\n return dest;\n}\n\n/**\n * Scale the coordinates.\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} sx Scale factor in the x-direction.\n * @param {number} sy Scale factor in the y-direction.\n * @param {Array} anchor Scale anchor point.\n * @param {Array} [dest] Destination.\n * @return {Array} Transformed coordinates.\n */\nexport function scale(\n flatCoordinates,\n offset,\n end,\n stride,\n sx,\n sy,\n anchor,\n dest\n) {\n dest = dest ? dest : [];\n const anchorX = anchor[0];\n const anchorY = anchor[1];\n let i = 0;\n for (let j = offset; j < end; j += stride) {\n const deltaX = flatCoordinates[j] - anchorX;\n const deltaY = flatCoordinates[j + 1] - anchorY;\n dest[i++] = anchorX + sx * deltaX;\n dest[i++] = anchorY + sy * deltaY;\n for (let k = j + 2; k < j + stride; ++k) {\n dest[i++] = flatCoordinates[k];\n }\n }\n if (dest && dest.length != i) {\n dest.length = i;\n }\n return dest;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} deltaX Delta X.\n * @param {number} deltaY Delta Y.\n * @param {Array} [dest] Destination.\n * @return {Array} Transformed coordinates.\n */\nexport function translate(\n flatCoordinates,\n offset,\n end,\n stride,\n deltaX,\n deltaY,\n dest\n) {\n dest = dest ? dest : [];\n let i = 0;\n for (let j = offset; j < end; j += stride) {\n dest[i++] = flatCoordinates[j] + deltaX;\n dest[i++] = flatCoordinates[j + 1] + deltaY;\n for (let k = j + 2; k < j + stride; ++k) {\n dest[i++] = flatCoordinates[k];\n }\n }\n if (dest && dest.length != i) {\n dest.length = i;\n }\n return dest;\n}\n","/**\n * @module ol/geom/Geometry\n */\nimport BaseObject from '../Object.js';\nimport {abstract} from '../util.js';\nimport {\n compose as composeTransform,\n create as createTransform,\n} from '../transform.js';\nimport {\n createEmpty,\n createOrUpdateEmpty,\n getHeight,\n returnOrUpdate,\n} from '../extent.js';\nimport {get as getProjection, getTransform} from '../proj.js';\nimport {memoizeOne} from '../functions.js';\nimport {transform2D} from './flat/transform.js';\n\n/**\n * @typedef {'XY' | 'XYZ' | 'XYM' | 'XYZM'} GeometryLayout\n * The coordinate layout for geometries, indicating whether a 3rd or 4th z ('Z')\n * or measure ('M') coordinate is available.\n */\n\n/**\n * @typedef {'Point' | 'LineString' | 'LinearRing' | 'Polygon' | 'MultiPoint' | 'MultiLineString' | 'MultiPolygon' | 'GeometryCollection' | 'Circle'} Type\n * The geometry type. One of `'Point'`, `'LineString'`, `'LinearRing'`,\n * `'Polygon'`, `'MultiPoint'`, `'MultiLineString'`, `'MultiPolygon'`,\n * `'GeometryCollection'`, or `'Circle'`.\n */\n\n/**\n * @type {import(\"../transform.js\").Transform}\n */\nconst tmpTransform = createTransform();\n\n/**\n * @classdesc\n * Abstract base class; normally only used for creating subclasses and not\n * instantiated in apps.\n * Base class for vector geometries.\n *\n * To get notified of changes to the geometry, register a listener for the\n * generic `change` event on your geometry instance.\n *\n * @abstract\n * @api\n */\nclass Geometry extends BaseObject {\n constructor() {\n super();\n\n /**\n * @private\n * @type {import(\"../extent.js\").Extent}\n */\n this.extent_ = createEmpty();\n\n /**\n * @private\n * @type {number}\n */\n this.extentRevision_ = -1;\n\n /**\n * @protected\n * @type {number}\n */\n this.simplifiedGeometryMaxMinSquaredTolerance = 0;\n\n /**\n * @protected\n * @type {number}\n */\n this.simplifiedGeometryRevision = 0;\n\n /**\n * Get a transformed and simplified version of the geometry.\n * @abstract\n * @param {number} revision The geometry revision.\n * @param {number} squaredTolerance Squared tolerance.\n * @param {import(\"../proj.js\").TransformFunction} [transform] Optional transform function.\n * @return {Geometry} Simplified geometry.\n */\n this.simplifyTransformedInternal = memoizeOne(function (\n revision,\n squaredTolerance,\n transform\n ) {\n if (!transform) {\n return this.getSimplifiedGeometry(squaredTolerance);\n }\n const clone = this.clone();\n clone.applyTransform(transform);\n return clone.getSimplifiedGeometry(squaredTolerance);\n });\n }\n\n /**\n * Get a transformed and simplified version of the geometry.\n * @abstract\n * @param {number} squaredTolerance Squared tolerance.\n * @param {import(\"../proj.js\").TransformFunction} [transform] Optional transform function.\n * @return {Geometry} Simplified geometry.\n */\n simplifyTransformed(squaredTolerance, transform) {\n return this.simplifyTransformedInternal(\n this.getRevision(),\n squaredTolerance,\n transform\n );\n }\n\n /**\n * Make a complete copy of the geometry.\n * @abstract\n * @return {!Geometry} Clone.\n */\n clone() {\n return abstract();\n }\n\n /**\n * @abstract\n * @param {number} x X.\n * @param {number} y Y.\n * @param {import(\"../coordinate.js\").Coordinate} closestPoint Closest point.\n * @param {number} minSquaredDistance Minimum squared distance.\n * @return {number} Minimum squared distance.\n */\n closestPointXY(x, y, closestPoint, minSquaredDistance) {\n return abstract();\n }\n\n /**\n * @param {number} x X.\n * @param {number} y Y.\n * @return {boolean} Contains (x, y).\n */\n containsXY(x, y) {\n const coord = this.getClosestPoint([x, y]);\n return coord[0] === x && coord[1] === y;\n }\n\n /**\n * Return the closest point of the geometry to the passed point as\n * {@link module:ol/coordinate~Coordinate coordinate}.\n * @param {import(\"../coordinate.js\").Coordinate} point Point.\n * @param {import(\"../coordinate.js\").Coordinate} [closestPoint] Closest point.\n * @return {import(\"../coordinate.js\").Coordinate} Closest point.\n * @api\n */\n getClosestPoint(point, closestPoint) {\n closestPoint = closestPoint ? closestPoint : [NaN, NaN];\n this.closestPointXY(point[0], point[1], closestPoint, Infinity);\n return closestPoint;\n }\n\n /**\n * Returns true if this geometry includes the specified coordinate. If the\n * coordinate is on the boundary of the geometry, returns false.\n * @param {import(\"../coordinate.js\").Coordinate} coordinate Coordinate.\n * @return {boolean} Contains coordinate.\n * @api\n */\n intersectsCoordinate(coordinate) {\n return this.containsXY(coordinate[0], coordinate[1]);\n }\n\n /**\n * @abstract\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @protected\n * @return {import(\"../extent.js\").Extent} extent Extent.\n */\n computeExtent(extent) {\n return abstract();\n }\n\n /**\n * Get the extent of the geometry.\n * @param {import(\"../extent.js\").Extent} [extent] Extent.\n * @return {import(\"../extent.js\").Extent} extent Extent.\n * @api\n */\n getExtent(extent) {\n if (this.extentRevision_ != this.getRevision()) {\n const extent = this.computeExtent(this.extent_);\n if (isNaN(extent[0]) || isNaN(extent[1])) {\n createOrUpdateEmpty(extent);\n }\n this.extentRevision_ = this.getRevision();\n }\n return returnOrUpdate(this.extent_, extent);\n }\n\n /**\n * Rotate the geometry around a given coordinate. This modifies the geometry\n * coordinates in place.\n * @abstract\n * @param {number} angle Rotation angle in radians.\n * @param {import(\"../coordinate.js\").Coordinate} anchor The rotation center.\n * @api\n */\n rotate(angle, anchor) {\n abstract();\n }\n\n /**\n * Scale the geometry (with an optional origin). This modifies the geometry\n * coordinates in place.\n * @abstract\n * @param {number} sx The scaling factor in the x-direction.\n * @param {number} [sy] The scaling factor in the y-direction (defaults to sx).\n * @param {import(\"../coordinate.js\").Coordinate} [anchor] The scale origin (defaults to the center\n * of the geometry extent).\n * @api\n */\n scale(sx, sy, anchor) {\n abstract();\n }\n\n /**\n * Create a simplified version of this geometry. For linestrings, this uses\n * the [Douglas Peucker](https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm)\n * algorithm. For polygons, a quantization-based\n * simplification is used to preserve topology.\n * @param {number} tolerance The tolerance distance for simplification.\n * @return {Geometry} A new, simplified version of the original geometry.\n * @api\n */\n simplify(tolerance) {\n return this.getSimplifiedGeometry(tolerance * tolerance);\n }\n\n /**\n * Create a simplified version of this geometry using the Douglas Peucker\n * algorithm.\n * See https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm.\n * @abstract\n * @param {number} squaredTolerance Squared tolerance.\n * @return {Geometry} Simplified geometry.\n */\n getSimplifiedGeometry(squaredTolerance) {\n return abstract();\n }\n\n /**\n * Get the type of this geometry.\n * @abstract\n * @return {Type} Geometry type.\n */\n getType() {\n return abstract();\n }\n\n /**\n * Apply a transform function to the coordinates of the geometry.\n * The geometry is modified in place.\n * If you do not want the geometry modified in place, first `clone()` it and\n * then use this function on the clone.\n * @abstract\n * @param {import(\"../proj.js\").TransformFunction} transformFn Transform function.\n * Called with a flat array of geometry coordinates.\n */\n applyTransform(transformFn) {\n abstract();\n }\n\n /**\n * Test if the geometry and the passed extent intersect.\n * @abstract\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @return {boolean} `true` if the geometry and the extent intersect.\n */\n intersectsExtent(extent) {\n return abstract();\n }\n\n /**\n * Translate the geometry. This modifies the geometry coordinates in place. If\n * instead you want a new geometry, first `clone()` this geometry.\n * @abstract\n * @param {number} deltaX Delta X.\n * @param {number} deltaY Delta Y.\n * @api\n */\n translate(deltaX, deltaY) {\n abstract();\n }\n\n /**\n * Transform each coordinate of the geometry from one coordinate reference\n * system to another. The geometry is modified in place.\n * For example, a line will be transformed to a line and a circle to a circle.\n * If you do not want the geometry modified in place, first `clone()` it and\n * then use this function on the clone.\n *\n * @param {import(\"../proj.js\").ProjectionLike} source The current projection. Can be a\n * string identifier or a {@link module:ol/proj/Projection~Projection} object.\n * @param {import(\"../proj.js\").ProjectionLike} destination The desired projection. Can be a\n * string identifier or a {@link module:ol/proj/Projection~Projection} object.\n * @return {Geometry} This geometry. Note that original geometry is\n * modified in place.\n * @api\n */\n transform(source, destination) {\n /** @type {import(\"../proj/Projection.js\").default} */\n const sourceProj = getProjection(source);\n const transformFn =\n sourceProj.getUnits() == 'tile-pixels'\n ? function (inCoordinates, outCoordinates, stride) {\n const pixelExtent = sourceProj.getExtent();\n const projectedExtent = sourceProj.getWorldExtent();\n const scale = getHeight(projectedExtent) / getHeight(pixelExtent);\n composeTransform(\n tmpTransform,\n projectedExtent[0],\n projectedExtent[3],\n scale,\n -scale,\n 0,\n 0,\n 0\n );\n transform2D(\n inCoordinates,\n 0,\n inCoordinates.length,\n stride,\n tmpTransform,\n outCoordinates\n );\n return getTransform(sourceProj, destination)(\n inCoordinates,\n outCoordinates,\n stride\n );\n }\n : getTransform(sourceProj, destination);\n this.applyTransform(transformFn);\n return this;\n }\n}\n\nexport default Geometry;\n","/**\n * @module ol/geom/SimpleGeometry\n */\nimport Geometry from './Geometry.js';\nimport {abstract} from '../util.js';\nimport {createOrUpdateFromFlatCoordinates, getCenter} from '../extent.js';\nimport {rotate, scale, transform2D, translate} from './flat/transform.js';\n\n/**\n * @classdesc\n * Abstract base class; only used for creating subclasses; do not instantiate\n * in apps, as cannot be rendered.\n *\n * @abstract\n * @api\n */\nclass SimpleGeometry extends Geometry {\n constructor() {\n super();\n\n /**\n * @protected\n * @type {import(\"./Geometry.js\").GeometryLayout}\n */\n this.layout = 'XY';\n\n /**\n * @protected\n * @type {number}\n */\n this.stride = 2;\n\n /**\n * @protected\n * @type {Array}\n */\n this.flatCoordinates = null;\n }\n\n /**\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @protected\n * @return {import(\"../extent.js\").Extent} extent Extent.\n */\n computeExtent(extent) {\n return createOrUpdateFromFlatCoordinates(\n this.flatCoordinates,\n 0,\n this.flatCoordinates.length,\n this.stride,\n extent\n );\n }\n\n /**\n * @abstract\n * @return {Array<*> | null} Coordinates.\n */\n getCoordinates() {\n return abstract();\n }\n\n /**\n * Return the first coordinate of the geometry.\n * @return {import(\"../coordinate.js\").Coordinate} First coordinate.\n * @api\n */\n getFirstCoordinate() {\n return this.flatCoordinates.slice(0, this.stride);\n }\n\n /**\n * @return {Array} Flat coordinates.\n */\n getFlatCoordinates() {\n return this.flatCoordinates;\n }\n\n /**\n * Return the last coordinate of the geometry.\n * @return {import(\"../coordinate.js\").Coordinate} Last point.\n * @api\n */\n getLastCoordinate() {\n return this.flatCoordinates.slice(\n this.flatCoordinates.length - this.stride\n );\n }\n\n /**\n * Return the {@link import(\"./Geometry.js\").GeometryLayout layout} of the geometry.\n * @return {import(\"./Geometry.js\").GeometryLayout} Layout.\n * @api\n */\n getLayout() {\n return this.layout;\n }\n\n /**\n * Create a simplified version of this geometry using the Douglas Peucker algorithm.\n * @param {number} squaredTolerance Squared tolerance.\n * @return {SimpleGeometry} Simplified geometry.\n */\n getSimplifiedGeometry(squaredTolerance) {\n if (this.simplifiedGeometryRevision !== this.getRevision()) {\n this.simplifiedGeometryMaxMinSquaredTolerance = 0;\n this.simplifiedGeometryRevision = this.getRevision();\n }\n // If squaredTolerance is negative or if we know that simplification will not\n // have any effect then just return this.\n if (\n squaredTolerance < 0 ||\n (this.simplifiedGeometryMaxMinSquaredTolerance !== 0 &&\n squaredTolerance <= this.simplifiedGeometryMaxMinSquaredTolerance)\n ) {\n return this;\n }\n\n const simplifiedGeometry =\n this.getSimplifiedGeometryInternal(squaredTolerance);\n const simplifiedFlatCoordinates = simplifiedGeometry.getFlatCoordinates();\n if (simplifiedFlatCoordinates.length < this.flatCoordinates.length) {\n return simplifiedGeometry;\n }\n // Simplification did not actually remove any coordinates. We now know\n // that any calls to getSimplifiedGeometry with a squaredTolerance less\n // than or equal to the current squaredTolerance will also not have any\n // effect. This allows us to short circuit simplification (saving CPU\n // cycles) and prevents the cache of simplified geometries from filling\n // up with useless identical copies of this geometry (saving memory).\n this.simplifiedGeometryMaxMinSquaredTolerance = squaredTolerance;\n return this;\n }\n\n /**\n * @param {number} squaredTolerance Squared tolerance.\n * @return {SimpleGeometry} Simplified geometry.\n * @protected\n */\n getSimplifiedGeometryInternal(squaredTolerance) {\n return this;\n }\n\n /**\n * @return {number} Stride.\n */\n getStride() {\n return this.stride;\n }\n\n /**\n * @param {import(\"./Geometry.js\").GeometryLayout} layout Layout.\n * @param {Array} flatCoordinates Flat coordinates.\n */\n setFlatCoordinates(layout, flatCoordinates) {\n this.stride = getStrideForLayout(layout);\n this.layout = layout;\n this.flatCoordinates = flatCoordinates;\n }\n\n /**\n * @abstract\n * @param {!Array<*>} coordinates Coordinates.\n * @param {import(\"./Geometry.js\").GeometryLayout} [layout] Layout.\n */\n setCoordinates(coordinates, layout) {\n abstract();\n }\n\n /**\n * @param {import(\"./Geometry.js\").GeometryLayout|undefined} layout Layout.\n * @param {Array<*>} coordinates Coordinates.\n * @param {number} nesting Nesting.\n * @protected\n */\n setLayout(layout, coordinates, nesting) {\n /** @type {number} */\n let stride;\n if (layout) {\n stride = getStrideForLayout(layout);\n } else {\n for (let i = 0; i < nesting; ++i) {\n if (coordinates.length === 0) {\n this.layout = 'XY';\n this.stride = 2;\n return;\n }\n coordinates = /** @type {Array} */ (coordinates[0]);\n }\n stride = coordinates.length;\n layout = getLayoutForStride(stride);\n }\n this.layout = layout;\n this.stride = stride;\n }\n\n /**\n * Apply a transform function to the coordinates of the geometry.\n * The geometry is modified in place.\n * If you do not want the geometry modified in place, first `clone()` it and\n * then use this function on the clone.\n * @param {import(\"../proj.js\").TransformFunction} transformFn Transform function.\n * Called with a flat array of geometry coordinates.\n * @api\n */\n applyTransform(transformFn) {\n if (this.flatCoordinates) {\n transformFn(this.flatCoordinates, this.flatCoordinates, this.stride);\n this.changed();\n }\n }\n\n /**\n * Rotate the geometry around a given coordinate. This modifies the geometry\n * coordinates in place.\n * @param {number} angle Rotation angle in counter-clockwise radians.\n * @param {import(\"../coordinate.js\").Coordinate} anchor The rotation center.\n * @api\n */\n rotate(angle, anchor) {\n const flatCoordinates = this.getFlatCoordinates();\n if (flatCoordinates) {\n const stride = this.getStride();\n rotate(\n flatCoordinates,\n 0,\n flatCoordinates.length,\n stride,\n angle,\n anchor,\n flatCoordinates\n );\n this.changed();\n }\n }\n\n /**\n * Scale the geometry (with an optional origin). This modifies the geometry\n * coordinates in place.\n * @param {number} sx The scaling factor in the x-direction.\n * @param {number} [sy] The scaling factor in the y-direction (defaults to sx).\n * @param {import(\"../coordinate.js\").Coordinate} [anchor] The scale origin (defaults to the center\n * of the geometry extent).\n * @api\n */\n scale(sx, sy, anchor) {\n if (sy === undefined) {\n sy = sx;\n }\n if (!anchor) {\n anchor = getCenter(this.getExtent());\n }\n const flatCoordinates = this.getFlatCoordinates();\n if (flatCoordinates) {\n const stride = this.getStride();\n scale(\n flatCoordinates,\n 0,\n flatCoordinates.length,\n stride,\n sx,\n sy,\n anchor,\n flatCoordinates\n );\n this.changed();\n }\n }\n\n /**\n * Translate the geometry. This modifies the geometry coordinates in place. If\n * instead you want a new geometry, first `clone()` this geometry.\n * @param {number} deltaX Delta X.\n * @param {number} deltaY Delta Y.\n * @api\n */\n translate(deltaX, deltaY) {\n const flatCoordinates = this.getFlatCoordinates();\n if (flatCoordinates) {\n const stride = this.getStride();\n translate(\n flatCoordinates,\n 0,\n flatCoordinates.length,\n stride,\n deltaX,\n deltaY,\n flatCoordinates\n );\n this.changed();\n }\n }\n}\n\n/**\n * @param {number} stride Stride.\n * @return {import(\"./Geometry.js\").GeometryLayout} layout Layout.\n */\nfunction getLayoutForStride(stride) {\n let layout;\n if (stride == 2) {\n layout = 'XY';\n } else if (stride == 3) {\n layout = 'XYZ';\n } else if (stride == 4) {\n layout = 'XYZM';\n }\n return /** @type {import(\"./Geometry.js\").GeometryLayout} */ (layout);\n}\n\n/**\n * @param {import(\"./Geometry.js\").GeometryLayout} layout Layout.\n * @return {number} Stride.\n */\nexport function getStrideForLayout(layout) {\n let stride;\n if (layout == 'XY') {\n stride = 2;\n } else if (layout == 'XYZ' || layout == 'XYM') {\n stride = 3;\n } else if (layout == 'XYZM') {\n stride = 4;\n }\n return /** @type {number} */ (stride);\n}\n\n/**\n * @param {SimpleGeometry} simpleGeometry Simple geometry.\n * @param {import(\"../transform.js\").Transform} transform Transform.\n * @param {Array} [dest] Destination.\n * @return {Array} Transformed flat coordinates.\n */\nexport function transformGeom2D(simpleGeometry, transform, dest) {\n const flatCoordinates = simpleGeometry.getFlatCoordinates();\n if (!flatCoordinates) {\n return null;\n }\n const stride = simpleGeometry.getStride();\n return transform2D(\n flatCoordinates,\n 0,\n flatCoordinates.length,\n stride,\n transform,\n dest\n );\n}\n\nexport default SimpleGeometry;\n","/**\n * @module ol/geom/flat/closest\n */\nimport {lerp, squaredDistance as squaredDx} from '../../math.js';\n\n/**\n * Returns the point on the 2D line segment flatCoordinates[offset1] to\n * flatCoordinates[offset2] that is closest to the point (x, y). Extra\n * dimensions are linearly interpolated.\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset1 Offset 1.\n * @param {number} offset2 Offset 2.\n * @param {number} stride Stride.\n * @param {number} x X.\n * @param {number} y Y.\n * @param {Array} closestPoint Closest point.\n */\nfunction assignClosest(\n flatCoordinates,\n offset1,\n offset2,\n stride,\n x,\n y,\n closestPoint\n) {\n const x1 = flatCoordinates[offset1];\n const y1 = flatCoordinates[offset1 + 1];\n const dx = flatCoordinates[offset2] - x1;\n const dy = flatCoordinates[offset2 + 1] - y1;\n let offset;\n if (dx === 0 && dy === 0) {\n offset = offset1;\n } else {\n const t = ((x - x1) * dx + (y - y1) * dy) / (dx * dx + dy * dy);\n if (t > 1) {\n offset = offset2;\n } else if (t > 0) {\n for (let i = 0; i < stride; ++i) {\n closestPoint[i] = lerp(\n flatCoordinates[offset1 + i],\n flatCoordinates[offset2 + i],\n t\n );\n }\n closestPoint.length = stride;\n return;\n } else {\n offset = offset1;\n }\n }\n for (let i = 0; i < stride; ++i) {\n closestPoint[i] = flatCoordinates[offset + i];\n }\n closestPoint.length = stride;\n}\n\n/**\n * Return the squared of the largest distance between any pair of consecutive\n * coordinates.\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} max Max squared delta.\n * @return {number} Max squared delta.\n */\nexport function maxSquaredDelta(flatCoordinates, offset, end, stride, max) {\n let x1 = flatCoordinates[offset];\n let y1 = flatCoordinates[offset + 1];\n for (offset += stride; offset < end; offset += stride) {\n const x2 = flatCoordinates[offset];\n const y2 = flatCoordinates[offset + 1];\n const squaredDelta = squaredDx(x1, y1, x2, y2);\n if (squaredDelta > max) {\n max = squaredDelta;\n }\n x1 = x2;\n y1 = y2;\n }\n return max;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array} ends Ends.\n * @param {number} stride Stride.\n * @param {number} max Max squared delta.\n * @return {number} Max squared delta.\n */\nexport function arrayMaxSquaredDelta(\n flatCoordinates,\n offset,\n ends,\n stride,\n max\n) {\n for (let i = 0, ii = ends.length; i < ii; ++i) {\n const end = ends[i];\n max = maxSquaredDelta(flatCoordinates, offset, end, stride, max);\n offset = end;\n }\n return max;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array>} endss Endss.\n * @param {number} stride Stride.\n * @param {number} max Max squared delta.\n * @return {number} Max squared delta.\n */\nexport function multiArrayMaxSquaredDelta(\n flatCoordinates,\n offset,\n endss,\n stride,\n max\n) {\n for (let i = 0, ii = endss.length; i < ii; ++i) {\n const ends = endss[i];\n max = arrayMaxSquaredDelta(flatCoordinates, offset, ends, stride, max);\n offset = ends[ends.length - 1];\n }\n return max;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} maxDelta Max delta.\n * @param {boolean} isRing Is ring.\n * @param {number} x X.\n * @param {number} y Y.\n * @param {Array} closestPoint Closest point.\n * @param {number} minSquaredDistance Minimum squared distance.\n * @param {Array} [tmpPoint] Temporary point object.\n * @return {number} Minimum squared distance.\n */\nexport function assignClosestPoint(\n flatCoordinates,\n offset,\n end,\n stride,\n maxDelta,\n isRing,\n x,\n y,\n closestPoint,\n minSquaredDistance,\n tmpPoint\n) {\n if (offset == end) {\n return minSquaredDistance;\n }\n let i, squaredDistance;\n if (maxDelta === 0) {\n // All points are identical, so just test the first point.\n squaredDistance = squaredDx(\n x,\n y,\n flatCoordinates[offset],\n flatCoordinates[offset + 1]\n );\n if (squaredDistance < minSquaredDistance) {\n for (i = 0; i < stride; ++i) {\n closestPoint[i] = flatCoordinates[offset + i];\n }\n closestPoint.length = stride;\n return squaredDistance;\n }\n return minSquaredDistance;\n }\n tmpPoint = tmpPoint ? tmpPoint : [NaN, NaN];\n let index = offset + stride;\n while (index < end) {\n assignClosest(\n flatCoordinates,\n index - stride,\n index,\n stride,\n x,\n y,\n tmpPoint\n );\n squaredDistance = squaredDx(x, y, tmpPoint[0], tmpPoint[1]);\n if (squaredDistance < minSquaredDistance) {\n minSquaredDistance = squaredDistance;\n for (i = 0; i < stride; ++i) {\n closestPoint[i] = tmpPoint[i];\n }\n closestPoint.length = stride;\n index += stride;\n } else {\n // Skip ahead multiple points, because we know that all the skipped\n // points cannot be any closer than the closest point we have found so\n // far. We know this because we know how close the current point is, how\n // close the closest point we have found so far is, and the maximum\n // distance between consecutive points. For example, if we're currently\n // at distance 10, the best we've found so far is 3, and that the maximum\n // distance between consecutive points is 2, then we'll need to skip at\n // least (10 - 3) / 2 == 3 (rounded down) points to have any chance of\n // finding a closer point. We use Math.max(..., 1) to ensure that we\n // always advance at least one point, to avoid an infinite loop.\n index +=\n stride *\n Math.max(\n ((Math.sqrt(squaredDistance) - Math.sqrt(minSquaredDistance)) /\n maxDelta) |\n 0,\n 1\n );\n }\n }\n if (isRing) {\n // Check the closing segment.\n assignClosest(\n flatCoordinates,\n end - stride,\n offset,\n stride,\n x,\n y,\n tmpPoint\n );\n squaredDistance = squaredDx(x, y, tmpPoint[0], tmpPoint[1]);\n if (squaredDistance < minSquaredDistance) {\n minSquaredDistance = squaredDistance;\n for (i = 0; i < stride; ++i) {\n closestPoint[i] = tmpPoint[i];\n }\n closestPoint.length = stride;\n }\n }\n return minSquaredDistance;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array} ends Ends.\n * @param {number} stride Stride.\n * @param {number} maxDelta Max delta.\n * @param {boolean} isRing Is ring.\n * @param {number} x X.\n * @param {number} y Y.\n * @param {Array} closestPoint Closest point.\n * @param {number} minSquaredDistance Minimum squared distance.\n * @param {Array} [tmpPoint] Temporary point object.\n * @return {number} Minimum squared distance.\n */\nexport function assignClosestArrayPoint(\n flatCoordinates,\n offset,\n ends,\n stride,\n maxDelta,\n isRing,\n x,\n y,\n closestPoint,\n minSquaredDistance,\n tmpPoint\n) {\n tmpPoint = tmpPoint ? tmpPoint : [NaN, NaN];\n for (let i = 0, ii = ends.length; i < ii; ++i) {\n const end = ends[i];\n minSquaredDistance = assignClosestPoint(\n flatCoordinates,\n offset,\n end,\n stride,\n maxDelta,\n isRing,\n x,\n y,\n closestPoint,\n minSquaredDistance,\n tmpPoint\n );\n offset = end;\n }\n return minSquaredDistance;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array>} endss Endss.\n * @param {number} stride Stride.\n * @param {number} maxDelta Max delta.\n * @param {boolean} isRing Is ring.\n * @param {number} x X.\n * @param {number} y Y.\n * @param {Array} closestPoint Closest point.\n * @param {number} minSquaredDistance Minimum squared distance.\n * @param {Array} [tmpPoint] Temporary point object.\n * @return {number} Minimum squared distance.\n */\nexport function assignClosestMultiArrayPoint(\n flatCoordinates,\n offset,\n endss,\n stride,\n maxDelta,\n isRing,\n x,\n y,\n closestPoint,\n minSquaredDistance,\n tmpPoint\n) {\n tmpPoint = tmpPoint ? tmpPoint : [NaN, NaN];\n for (let i = 0, ii = endss.length; i < ii; ++i) {\n const ends = endss[i];\n minSquaredDistance = assignClosestArrayPoint(\n flatCoordinates,\n offset,\n ends,\n stride,\n maxDelta,\n isRing,\n x,\n y,\n closestPoint,\n minSquaredDistance,\n tmpPoint\n );\n offset = ends[ends.length - 1];\n }\n return minSquaredDistance;\n}\n","/**\n * @module ol/geom/flat/deflate\n */\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {import(\"../../coordinate.js\").Coordinate} coordinate Coordinate.\n * @param {number} stride Stride.\n * @return {number} offset Offset.\n */\nexport function deflateCoordinate(flatCoordinates, offset, coordinate, stride) {\n for (let i = 0, ii = coordinate.length; i < ii; ++i) {\n flatCoordinates[offset++] = coordinate[i];\n }\n return offset;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array} coordinates Coordinates.\n * @param {number} stride Stride.\n * @return {number} offset Offset.\n */\nexport function deflateCoordinates(\n flatCoordinates,\n offset,\n coordinates,\n stride\n) {\n for (let i = 0, ii = coordinates.length; i < ii; ++i) {\n const coordinate = coordinates[i];\n for (let j = 0; j < stride; ++j) {\n flatCoordinates[offset++] = coordinate[j];\n }\n }\n return offset;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array>} coordinatess Coordinatess.\n * @param {number} stride Stride.\n * @param {Array} [ends] Ends.\n * @return {Array} Ends.\n */\nexport function deflateCoordinatesArray(\n flatCoordinates,\n offset,\n coordinatess,\n stride,\n ends\n) {\n ends = ends ? ends : [];\n let i = 0;\n for (let j = 0, jj = coordinatess.length; j < jj; ++j) {\n const end = deflateCoordinates(\n flatCoordinates,\n offset,\n coordinatess[j],\n stride\n );\n ends[i++] = end;\n offset = end;\n }\n ends.length = i;\n return ends;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array>>} coordinatesss Coordinatesss.\n * @param {number} stride Stride.\n * @param {Array>} [endss] Endss.\n * @return {Array>} Endss.\n */\nexport function deflateMultiCoordinatesArray(\n flatCoordinates,\n offset,\n coordinatesss,\n stride,\n endss\n) {\n endss = endss ? endss : [];\n let i = 0;\n for (let j = 0, jj = coordinatesss.length; j < jj; ++j) {\n const ends = deflateCoordinatesArray(\n flatCoordinates,\n offset,\n coordinatesss[j],\n stride,\n endss[i]\n );\n if (ends.length === 0) {\n ends[0] = offset;\n }\n endss[i++] = ends;\n offset = ends[ends.length - 1];\n }\n endss.length = i;\n return endss;\n}\n","/**\n * @module ol/geom/flat/simplify\n */\n// Based on simplify-js https://github.com/mourner/simplify-js\n// Copyright (c) 2012, Vladimir Agafonkin\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are met:\n//\n// 1. Redistributions of source code must retain the above copyright notice,\n// this list of conditions and the following disclaimer.\n//\n// 2. Redistributions in binary form must reproduce the above copyright\n// notice, this list of conditions and the following disclaimer in the\n// documentation and/or other materials provided with the distribution.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n// POSSIBILITY OF SUCH DAMAGE.\n\nimport {squaredDistance, squaredSegmentDistance} from '../../math.js';\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} squaredTolerance Squared tolerance.\n * @param {boolean} highQuality Highest quality.\n * @param {Array} [simplifiedFlatCoordinates] Simplified flat\n * coordinates.\n * @return {Array} Simplified line string.\n */\nexport function simplifyLineString(\n flatCoordinates,\n offset,\n end,\n stride,\n squaredTolerance,\n highQuality,\n simplifiedFlatCoordinates\n) {\n simplifiedFlatCoordinates =\n simplifiedFlatCoordinates !== undefined ? simplifiedFlatCoordinates : [];\n if (!highQuality) {\n end = radialDistance(\n flatCoordinates,\n offset,\n end,\n stride,\n squaredTolerance,\n simplifiedFlatCoordinates,\n 0\n );\n flatCoordinates = simplifiedFlatCoordinates;\n offset = 0;\n stride = 2;\n }\n simplifiedFlatCoordinates.length = douglasPeucker(\n flatCoordinates,\n offset,\n end,\n stride,\n squaredTolerance,\n simplifiedFlatCoordinates,\n 0\n );\n return simplifiedFlatCoordinates;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} squaredTolerance Squared tolerance.\n * @param {Array} simplifiedFlatCoordinates Simplified flat\n * coordinates.\n * @param {number} simplifiedOffset Simplified offset.\n * @return {number} Simplified offset.\n */\nexport function douglasPeucker(\n flatCoordinates,\n offset,\n end,\n stride,\n squaredTolerance,\n simplifiedFlatCoordinates,\n simplifiedOffset\n) {\n const n = (end - offset) / stride;\n if (n < 3) {\n for (; offset < end; offset += stride) {\n simplifiedFlatCoordinates[simplifiedOffset++] = flatCoordinates[offset];\n simplifiedFlatCoordinates[simplifiedOffset++] =\n flatCoordinates[offset + 1];\n }\n return simplifiedOffset;\n }\n /** @type {Array} */\n const markers = new Array(n);\n markers[0] = 1;\n markers[n - 1] = 1;\n /** @type {Array} */\n const stack = [offset, end - stride];\n let index = 0;\n while (stack.length > 0) {\n const last = stack.pop();\n const first = stack.pop();\n let maxSquaredDistance = 0;\n const x1 = flatCoordinates[first];\n const y1 = flatCoordinates[first + 1];\n const x2 = flatCoordinates[last];\n const y2 = flatCoordinates[last + 1];\n for (let i = first + stride; i < last; i += stride) {\n const x = flatCoordinates[i];\n const y = flatCoordinates[i + 1];\n const squaredDistance = squaredSegmentDistance(x, y, x1, y1, x2, y2);\n if (squaredDistance > maxSquaredDistance) {\n index = i;\n maxSquaredDistance = squaredDistance;\n }\n }\n if (maxSquaredDistance > squaredTolerance) {\n markers[(index - offset) / stride] = 1;\n if (first + stride < index) {\n stack.push(first, index);\n }\n if (index + stride < last) {\n stack.push(index, last);\n }\n }\n }\n for (let i = 0; i < n; ++i) {\n if (markers[i]) {\n simplifiedFlatCoordinates[simplifiedOffset++] =\n flatCoordinates[offset + i * stride];\n simplifiedFlatCoordinates[simplifiedOffset++] =\n flatCoordinates[offset + i * stride + 1];\n }\n }\n return simplifiedOffset;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array} ends Ends.\n * @param {number} stride Stride.\n * @param {number} squaredTolerance Squared tolerance.\n * @param {Array} simplifiedFlatCoordinates Simplified flat\n * coordinates.\n * @param {number} simplifiedOffset Simplified offset.\n * @param {Array} simplifiedEnds Simplified ends.\n * @return {number} Simplified offset.\n */\nexport function douglasPeuckerArray(\n flatCoordinates,\n offset,\n ends,\n stride,\n squaredTolerance,\n simplifiedFlatCoordinates,\n simplifiedOffset,\n simplifiedEnds\n) {\n for (let i = 0, ii = ends.length; i < ii; ++i) {\n const end = ends[i];\n simplifiedOffset = douglasPeucker(\n flatCoordinates,\n offset,\n end,\n stride,\n squaredTolerance,\n simplifiedFlatCoordinates,\n simplifiedOffset\n );\n simplifiedEnds.push(simplifiedOffset);\n offset = end;\n }\n return simplifiedOffset;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array>} endss Endss.\n * @param {number} stride Stride.\n * @param {number} squaredTolerance Squared tolerance.\n * @param {Array} simplifiedFlatCoordinates Simplified flat\n * coordinates.\n * @param {number} simplifiedOffset Simplified offset.\n * @param {Array>} simplifiedEndss Simplified endss.\n * @return {number} Simplified offset.\n */\nexport function douglasPeuckerMultiArray(\n flatCoordinates,\n offset,\n endss,\n stride,\n squaredTolerance,\n simplifiedFlatCoordinates,\n simplifiedOffset,\n simplifiedEndss\n) {\n for (let i = 0, ii = endss.length; i < ii; ++i) {\n const ends = endss[i];\n const simplifiedEnds = [];\n simplifiedOffset = douglasPeuckerArray(\n flatCoordinates,\n offset,\n ends,\n stride,\n squaredTolerance,\n simplifiedFlatCoordinates,\n simplifiedOffset,\n simplifiedEnds\n );\n simplifiedEndss.push(simplifiedEnds);\n offset = ends[ends.length - 1];\n }\n return simplifiedOffset;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} squaredTolerance Squared tolerance.\n * @param {Array} simplifiedFlatCoordinates Simplified flat\n * coordinates.\n * @param {number} simplifiedOffset Simplified offset.\n * @return {number} Simplified offset.\n */\nexport function radialDistance(\n flatCoordinates,\n offset,\n end,\n stride,\n squaredTolerance,\n simplifiedFlatCoordinates,\n simplifiedOffset\n) {\n if (end <= offset + stride) {\n // zero or one point, no simplification possible, so copy and return\n for (; offset < end; offset += stride) {\n simplifiedFlatCoordinates[simplifiedOffset++] = flatCoordinates[offset];\n simplifiedFlatCoordinates[simplifiedOffset++] =\n flatCoordinates[offset + 1];\n }\n return simplifiedOffset;\n }\n let x1 = flatCoordinates[offset];\n let y1 = flatCoordinates[offset + 1];\n // copy first point\n simplifiedFlatCoordinates[simplifiedOffset++] = x1;\n simplifiedFlatCoordinates[simplifiedOffset++] = y1;\n let x2 = x1;\n let y2 = y1;\n for (offset += stride; offset < end; offset += stride) {\n x2 = flatCoordinates[offset];\n y2 = flatCoordinates[offset + 1];\n if (squaredDistance(x1, y1, x2, y2) > squaredTolerance) {\n // copy point at offset\n simplifiedFlatCoordinates[simplifiedOffset++] = x2;\n simplifiedFlatCoordinates[simplifiedOffset++] = y2;\n x1 = x2;\n y1 = y2;\n }\n }\n if (x2 != x1 || y2 != y1) {\n // copy last point\n simplifiedFlatCoordinates[simplifiedOffset++] = x2;\n simplifiedFlatCoordinates[simplifiedOffset++] = y2;\n }\n return simplifiedOffset;\n}\n\n/**\n * @param {number} value Value.\n * @param {number} tolerance Tolerance.\n * @return {number} Rounded value.\n */\nexport function snap(value, tolerance) {\n return tolerance * Math.round(value / tolerance);\n}\n\n/**\n * Simplifies a line string using an algorithm designed by Tim Schaub.\n * Coordinates are snapped to the nearest value in a virtual grid and\n * consecutive duplicate coordinates are discarded. This effectively preserves\n * topology as the simplification of any subsection of a line string is\n * independent of the rest of the line string. This means that, for examples,\n * the common edge between two polygons will be simplified to the same line\n * string independently in both polygons. This implementation uses a single\n * pass over the coordinates and eliminates intermediate collinear points.\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} tolerance Tolerance.\n * @param {Array} simplifiedFlatCoordinates Simplified flat\n * coordinates.\n * @param {number} simplifiedOffset Simplified offset.\n * @return {number} Simplified offset.\n */\nexport function quantize(\n flatCoordinates,\n offset,\n end,\n stride,\n tolerance,\n simplifiedFlatCoordinates,\n simplifiedOffset\n) {\n // do nothing if the line is empty\n if (offset == end) {\n return simplifiedOffset;\n }\n // snap the first coordinate (P1)\n let x1 = snap(flatCoordinates[offset], tolerance);\n let y1 = snap(flatCoordinates[offset + 1], tolerance);\n offset += stride;\n // add the first coordinate to the output\n simplifiedFlatCoordinates[simplifiedOffset++] = x1;\n simplifiedFlatCoordinates[simplifiedOffset++] = y1;\n // find the next coordinate that does not snap to the same value as the first\n // coordinate (P2)\n let x2, y2;\n do {\n x2 = snap(flatCoordinates[offset], tolerance);\n y2 = snap(flatCoordinates[offset + 1], tolerance);\n offset += stride;\n if (offset == end) {\n // all coordinates snap to the same value, the line collapses to a point\n // push the last snapped value anyway to ensure that the output contains\n // at least two points\n // FIXME should we really return at least two points anyway?\n simplifiedFlatCoordinates[simplifiedOffset++] = x2;\n simplifiedFlatCoordinates[simplifiedOffset++] = y2;\n return simplifiedOffset;\n }\n } while (x2 == x1 && y2 == y1);\n while (offset < end) {\n // snap the next coordinate (P3)\n const x3 = snap(flatCoordinates[offset], tolerance);\n const y3 = snap(flatCoordinates[offset + 1], tolerance);\n offset += stride;\n // skip P3 if it is equal to P2\n if (x3 == x2 && y3 == y2) {\n continue;\n }\n // calculate the delta between P1 and P2\n const dx1 = x2 - x1;\n const dy1 = y2 - y1;\n // calculate the delta between P3 and P1\n const dx2 = x3 - x1;\n const dy2 = y3 - y1;\n // if P1, P2, and P3 are colinear and P3 is further from P1 than P2 is from\n // P1 in the same direction then P2 is on the straight line between P1 and\n // P3\n if (\n dx1 * dy2 == dy1 * dx2 &&\n ((dx1 < 0 && dx2 < dx1) || dx1 == dx2 || (dx1 > 0 && dx2 > dx1)) &&\n ((dy1 < 0 && dy2 < dy1) || dy1 == dy2 || (dy1 > 0 && dy2 > dy1))\n ) {\n // discard P2 and set P2 = P3\n x2 = x3;\n y2 = y3;\n continue;\n }\n // either P1, P2, and P3 are not colinear, or they are colinear but P3 is\n // between P3 and P1 or on the opposite half of the line to P2. add P2,\n // and continue with P1 = P2 and P2 = P3\n simplifiedFlatCoordinates[simplifiedOffset++] = x2;\n simplifiedFlatCoordinates[simplifiedOffset++] = y2;\n x1 = x2;\n y1 = y2;\n x2 = x3;\n y2 = y3;\n }\n // add the last point (P2)\n simplifiedFlatCoordinates[simplifiedOffset++] = x2;\n simplifiedFlatCoordinates[simplifiedOffset++] = y2;\n return simplifiedOffset;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array} ends Ends.\n * @param {number} stride Stride.\n * @param {number} tolerance Tolerance.\n * @param {Array} simplifiedFlatCoordinates Simplified flat\n * coordinates.\n * @param {number} simplifiedOffset Simplified offset.\n * @param {Array} simplifiedEnds Simplified ends.\n * @return {number} Simplified offset.\n */\nexport function quantizeArray(\n flatCoordinates,\n offset,\n ends,\n stride,\n tolerance,\n simplifiedFlatCoordinates,\n simplifiedOffset,\n simplifiedEnds\n) {\n for (let i = 0, ii = ends.length; i < ii; ++i) {\n const end = ends[i];\n simplifiedOffset = quantize(\n flatCoordinates,\n offset,\n end,\n stride,\n tolerance,\n simplifiedFlatCoordinates,\n simplifiedOffset\n );\n simplifiedEnds.push(simplifiedOffset);\n offset = end;\n }\n return simplifiedOffset;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array>} endss Endss.\n * @param {number} stride Stride.\n * @param {number} tolerance Tolerance.\n * @param {Array} simplifiedFlatCoordinates Simplified flat\n * coordinates.\n * @param {number} simplifiedOffset Simplified offset.\n * @param {Array>} simplifiedEndss Simplified endss.\n * @return {number} Simplified offset.\n */\nexport function quantizeMultiArray(\n flatCoordinates,\n offset,\n endss,\n stride,\n tolerance,\n simplifiedFlatCoordinates,\n simplifiedOffset,\n simplifiedEndss\n) {\n for (let i = 0, ii = endss.length; i < ii; ++i) {\n const ends = endss[i];\n const simplifiedEnds = [];\n simplifiedOffset = quantizeArray(\n flatCoordinates,\n offset,\n ends,\n stride,\n tolerance,\n simplifiedFlatCoordinates,\n simplifiedOffset,\n simplifiedEnds\n );\n simplifiedEndss.push(simplifiedEnds);\n offset = ends[ends.length - 1];\n }\n return simplifiedOffset;\n}\n","/**\n * @module ol/geom/flat/inflate\n */\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {Array} [coordinates] Coordinates.\n * @return {Array} Coordinates.\n */\nexport function inflateCoordinates(\n flatCoordinates,\n offset,\n end,\n stride,\n coordinates\n) {\n coordinates = coordinates !== undefined ? coordinates : [];\n let i = 0;\n for (let j = offset; j < end; j += stride) {\n coordinates[i++] = flatCoordinates.slice(j, j + stride);\n }\n coordinates.length = i;\n return coordinates;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array} ends Ends.\n * @param {number} stride Stride.\n * @param {Array>} [coordinatess] Coordinatess.\n * @return {Array>} Coordinatess.\n */\nexport function inflateCoordinatesArray(\n flatCoordinates,\n offset,\n ends,\n stride,\n coordinatess\n) {\n coordinatess = coordinatess !== undefined ? coordinatess : [];\n let i = 0;\n for (let j = 0, jj = ends.length; j < jj; ++j) {\n const end = ends[j];\n coordinatess[i++] = inflateCoordinates(\n flatCoordinates,\n offset,\n end,\n stride,\n coordinatess[i]\n );\n offset = end;\n }\n coordinatess.length = i;\n return coordinatess;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array>} endss Endss.\n * @param {number} stride Stride.\n * @param {Array>>} [coordinatesss]\n * Coordinatesss.\n * @return {Array>>} Coordinatesss.\n */\nexport function inflateMultiCoordinatesArray(\n flatCoordinates,\n offset,\n endss,\n stride,\n coordinatesss\n) {\n coordinatesss = coordinatesss !== undefined ? coordinatesss : [];\n let i = 0;\n for (let j = 0, jj = endss.length; j < jj; ++j) {\n const ends = endss[j];\n coordinatesss[i++] =\n ends.length === 1 && ends[0] === offset\n ? []\n : inflateCoordinatesArray(\n flatCoordinates,\n offset,\n ends,\n stride,\n coordinatesss[i]\n );\n offset = ends[ends.length - 1];\n }\n coordinatesss.length = i;\n return coordinatesss;\n}\n","/**\n * @module ol/geom/flat/area\n */\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @return {number} Area.\n */\nexport function linearRing(flatCoordinates, offset, end, stride) {\n let twiceArea = 0;\n let x1 = flatCoordinates[end - stride];\n let y1 = flatCoordinates[end - stride + 1];\n for (; offset < end; offset += stride) {\n const x2 = flatCoordinates[offset];\n const y2 = flatCoordinates[offset + 1];\n twiceArea += y1 * x2 - x1 * y2;\n x1 = x2;\n y1 = y2;\n }\n return twiceArea / 2;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array} ends Ends.\n * @param {number} stride Stride.\n * @return {number} Area.\n */\nexport function linearRings(flatCoordinates, offset, ends, stride) {\n let area = 0;\n for (let i = 0, ii = ends.length; i < ii; ++i) {\n const end = ends[i];\n area += linearRing(flatCoordinates, offset, end, stride);\n offset = end;\n }\n return area;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array>} endss Endss.\n * @param {number} stride Stride.\n * @return {number} Area.\n */\nexport function linearRingss(flatCoordinates, offset, endss, stride) {\n let area = 0;\n for (let i = 0, ii = endss.length; i < ii; ++i) {\n const ends = endss[i];\n area += linearRings(flatCoordinates, offset, ends, stride);\n offset = ends[ends.length - 1];\n }\n return area;\n}\n","/**\n * @module ol/geom/LinearRing\n */\nimport SimpleGeometry from './SimpleGeometry.js';\nimport {assignClosestPoint, maxSquaredDelta} from './flat/closest.js';\nimport {closestSquaredDistanceXY} from '../extent.js';\nimport {deflateCoordinates} from './flat/deflate.js';\nimport {douglasPeucker} from './flat/simplify.js';\nimport {inflateCoordinates} from './flat/inflate.js';\nimport {linearRing as linearRingArea} from './flat/area.js';\n\n/**\n * @classdesc\n * Linear ring geometry. Only used as part of polygon; cannot be rendered\n * on its own.\n *\n * @api\n */\nclass LinearRing extends SimpleGeometry {\n /**\n * @param {Array|Array} coordinates Coordinates.\n * For internal use, flat coordinates in combination with `layout` are also accepted.\n * @param {import(\"./Geometry.js\").GeometryLayout} [layout] Layout.\n */\n constructor(coordinates, layout) {\n super();\n\n /**\n * @private\n * @type {number}\n */\n this.maxDelta_ = -1;\n\n /**\n * @private\n * @type {number}\n */\n this.maxDeltaRevision_ = -1;\n\n if (layout !== undefined && !Array.isArray(coordinates[0])) {\n this.setFlatCoordinates(\n layout,\n /** @type {Array} */ (coordinates)\n );\n } else {\n this.setCoordinates(\n /** @type {Array} */ (\n coordinates\n ),\n layout\n );\n }\n }\n\n /**\n * Make a complete copy of the geometry.\n * @return {!LinearRing} Clone.\n * @api\n */\n clone() {\n return new LinearRing(this.flatCoordinates.slice(), this.layout);\n }\n\n /**\n * @param {number} x X.\n * @param {number} y Y.\n * @param {import(\"../coordinate.js\").Coordinate} closestPoint Closest point.\n * @param {number} minSquaredDistance Minimum squared distance.\n * @return {number} Minimum squared distance.\n */\n closestPointXY(x, y, closestPoint, minSquaredDistance) {\n if (minSquaredDistance < closestSquaredDistanceXY(this.getExtent(), x, y)) {\n return minSquaredDistance;\n }\n if (this.maxDeltaRevision_ != this.getRevision()) {\n this.maxDelta_ = Math.sqrt(\n maxSquaredDelta(\n this.flatCoordinates,\n 0,\n this.flatCoordinates.length,\n this.stride,\n 0\n )\n );\n this.maxDeltaRevision_ = this.getRevision();\n }\n return assignClosestPoint(\n this.flatCoordinates,\n 0,\n this.flatCoordinates.length,\n this.stride,\n this.maxDelta_,\n true,\n x,\n y,\n closestPoint,\n minSquaredDistance\n );\n }\n\n /**\n * Return the area of the linear ring on projected plane.\n * @return {number} Area (on projected plane).\n * @api\n */\n getArea() {\n return linearRingArea(\n this.flatCoordinates,\n 0,\n this.flatCoordinates.length,\n this.stride\n );\n }\n\n /**\n * Return the coordinates of the linear ring.\n * @return {Array} Coordinates.\n * @api\n */\n getCoordinates() {\n return inflateCoordinates(\n this.flatCoordinates,\n 0,\n this.flatCoordinates.length,\n this.stride\n );\n }\n\n /**\n * @param {number} squaredTolerance Squared tolerance.\n * @return {LinearRing} Simplified LinearRing.\n * @protected\n */\n getSimplifiedGeometryInternal(squaredTolerance) {\n const simplifiedFlatCoordinates = [];\n simplifiedFlatCoordinates.length = douglasPeucker(\n this.flatCoordinates,\n 0,\n this.flatCoordinates.length,\n this.stride,\n squaredTolerance,\n simplifiedFlatCoordinates,\n 0\n );\n return new LinearRing(simplifiedFlatCoordinates, 'XY');\n }\n\n /**\n * Get the type of this geometry.\n * @return {import(\"./Geometry.js\").Type} Geometry type.\n * @api\n */\n getType() {\n return 'LinearRing';\n }\n\n /**\n * Test if the geometry and the passed extent intersect.\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @return {boolean} `true` if the geometry and the extent intersect.\n * @api\n */\n intersectsExtent(extent) {\n return false;\n }\n\n /**\n * Set the coordinates of the linear ring.\n * @param {!Array} coordinates Coordinates.\n * @param {import(\"./Geometry.js\").GeometryLayout} [layout] Layout.\n * @api\n */\n setCoordinates(coordinates, layout) {\n this.setLayout(layout, coordinates, 1);\n if (!this.flatCoordinates) {\n this.flatCoordinates = [];\n }\n this.flatCoordinates.length = deflateCoordinates(\n this.flatCoordinates,\n 0,\n coordinates,\n this.stride\n );\n this.changed();\n }\n}\n\nexport default LinearRing;\n","/**\n * @module ol/geom/Point\n */\nimport SimpleGeometry from './SimpleGeometry.js';\nimport {containsXY, createOrUpdateFromCoordinate} from '../extent.js';\nimport {deflateCoordinate} from './flat/deflate.js';\nimport {squaredDistance as squaredDx} from '../math.js';\n\n/**\n * @classdesc\n * Point geometry.\n *\n * @api\n */\nclass Point extends SimpleGeometry {\n /**\n * @param {import(\"../coordinate.js\").Coordinate} coordinates Coordinates.\n * @param {import(\"./Geometry.js\").GeometryLayout} [layout] Layout.\n */\n constructor(coordinates, layout) {\n super();\n this.setCoordinates(coordinates, layout);\n }\n\n /**\n * Make a complete copy of the geometry.\n * @return {!Point} Clone.\n * @api\n */\n clone() {\n const point = new Point(this.flatCoordinates.slice(), this.layout);\n point.applyProperties(this);\n return point;\n }\n\n /**\n * @param {number} x X.\n * @param {number} y Y.\n * @param {import(\"../coordinate.js\").Coordinate} closestPoint Closest point.\n * @param {number} minSquaredDistance Minimum squared distance.\n * @return {number} Minimum squared distance.\n */\n closestPointXY(x, y, closestPoint, minSquaredDistance) {\n const flatCoordinates = this.flatCoordinates;\n const squaredDistance = squaredDx(\n x,\n y,\n flatCoordinates[0],\n flatCoordinates[1]\n );\n if (squaredDistance < minSquaredDistance) {\n const stride = this.stride;\n for (let i = 0; i < stride; ++i) {\n closestPoint[i] = flatCoordinates[i];\n }\n closestPoint.length = stride;\n return squaredDistance;\n }\n return minSquaredDistance;\n }\n\n /**\n * Return the coordinate of the point.\n * @return {import(\"../coordinate.js\").Coordinate} Coordinates.\n * @api\n */\n getCoordinates() {\n return !this.flatCoordinates ? [] : this.flatCoordinates.slice();\n }\n\n /**\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @protected\n * @return {import(\"../extent.js\").Extent} extent Extent.\n */\n computeExtent(extent) {\n return createOrUpdateFromCoordinate(this.flatCoordinates, extent);\n }\n\n /**\n * Get the type of this geometry.\n * @return {import(\"./Geometry.js\").Type} Geometry type.\n * @api\n */\n getType() {\n return 'Point';\n }\n\n /**\n * Test if the geometry and the passed extent intersect.\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @return {boolean} `true` if the geometry and the extent intersect.\n * @api\n */\n intersectsExtent(extent) {\n return containsXY(extent, this.flatCoordinates[0], this.flatCoordinates[1]);\n }\n\n /**\n * @param {!Array<*>} coordinates Coordinates.\n * @param {import(\"./Geometry.js\").GeometryLayout} [layout] Layout.\n * @api\n */\n setCoordinates(coordinates, layout) {\n this.setLayout(layout, coordinates, 0);\n if (!this.flatCoordinates) {\n this.flatCoordinates = [];\n }\n this.flatCoordinates.length = deflateCoordinate(\n this.flatCoordinates,\n 0,\n coordinates,\n this.stride\n );\n this.changed();\n }\n}\n\nexport default Point;\n","/**\n * @module ol/geom/flat/contains\n */\nimport {forEachCorner} from '../../extent.js';\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {import(\"../../extent.js\").Extent} extent Extent.\n * @return {boolean} Contains extent.\n */\nexport function linearRingContainsExtent(\n flatCoordinates,\n offset,\n end,\n stride,\n extent\n) {\n const outside = forEachCorner(\n extent,\n /**\n * @param {import(\"../../coordinate.js\").Coordinate} coordinate Coordinate.\n * @return {boolean} Contains (x, y).\n */\n function (coordinate) {\n return !linearRingContainsXY(\n flatCoordinates,\n offset,\n end,\n stride,\n coordinate[0],\n coordinate[1]\n );\n }\n );\n return !outside;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {number} x X.\n * @param {number} y Y.\n * @return {boolean} Contains (x, y).\n */\nexport function linearRingContainsXY(\n flatCoordinates,\n offset,\n end,\n stride,\n x,\n y\n) {\n // https://geomalgorithms.com/a03-_inclusion.html\n // Copyright 2000 softSurfer, 2012 Dan Sunday\n // This code may be freely used and modified for any purpose\n // providing that this copyright notice is included with it.\n // SoftSurfer makes no warranty for this code, and cannot be held\n // liable for any real or imagined damage resulting from its use.\n // Users of this code must verify correctness for their application.\n let wn = 0;\n let x1 = flatCoordinates[end - stride];\n let y1 = flatCoordinates[end - stride + 1];\n for (; offset < end; offset += stride) {\n const x2 = flatCoordinates[offset];\n const y2 = flatCoordinates[offset + 1];\n if (y1 <= y) {\n if (y2 > y && (x2 - x1) * (y - y1) - (x - x1) * (y2 - y1) > 0) {\n wn++;\n }\n } else if (y2 <= y && (x2 - x1) * (y - y1) - (x - x1) * (y2 - y1) < 0) {\n wn--;\n }\n x1 = x2;\n y1 = y2;\n }\n return wn !== 0;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array} ends Ends.\n * @param {number} stride Stride.\n * @param {number} x X.\n * @param {number} y Y.\n * @return {boolean} Contains (x, y).\n */\nexport function linearRingsContainsXY(\n flatCoordinates,\n offset,\n ends,\n stride,\n x,\n y\n) {\n if (ends.length === 0) {\n return false;\n }\n if (!linearRingContainsXY(flatCoordinates, offset, ends[0], stride, x, y)) {\n return false;\n }\n for (let i = 1, ii = ends.length; i < ii; ++i) {\n if (\n linearRingContainsXY(flatCoordinates, ends[i - 1], ends[i], stride, x, y)\n ) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array>} endss Endss.\n * @param {number} stride Stride.\n * @param {number} x X.\n * @param {number} y Y.\n * @return {boolean} Contains (x, y).\n */\nexport function linearRingssContainsXY(\n flatCoordinates,\n offset,\n endss,\n stride,\n x,\n y\n) {\n if (endss.length === 0) {\n return false;\n }\n for (let i = 0, ii = endss.length; i < ii; ++i) {\n const ends = endss[i];\n if (linearRingsContainsXY(flatCoordinates, offset, ends, stride, x, y)) {\n return true;\n }\n offset = ends[ends.length - 1];\n }\n return false;\n}\n","/**\n * @module ol/geom/flat/interiorpoint\n */\nimport {ascending} from '../../array.js';\nimport {linearRingsContainsXY} from './contains.js';\n\n/**\n * Calculates a point that is likely to lie in the interior of the linear rings.\n * Inspired by JTS's com.vividsolutions.jts.geom.Geometry#getInteriorPoint.\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array} ends Ends.\n * @param {number} stride Stride.\n * @param {Array} flatCenters Flat centers.\n * @param {number} flatCentersOffset Flat center offset.\n * @param {Array} [dest] Destination.\n * @return {Array} Destination point as XYM coordinate, where M is the\n * length of the horizontal intersection that the point belongs to.\n */\nexport function getInteriorPointOfArray(\n flatCoordinates,\n offset,\n ends,\n stride,\n flatCenters,\n flatCentersOffset,\n dest\n) {\n let i, ii, x, x1, x2, y1, y2;\n const y = flatCenters[flatCentersOffset + 1];\n /** @type {Array} */\n const intersections = [];\n // Calculate intersections with the horizontal line\n for (let r = 0, rr = ends.length; r < rr; ++r) {\n const end = ends[r];\n x1 = flatCoordinates[end - stride];\n y1 = flatCoordinates[end - stride + 1];\n for (i = offset; i < end; i += stride) {\n x2 = flatCoordinates[i];\n y2 = flatCoordinates[i + 1];\n if ((y <= y1 && y2 <= y) || (y1 <= y && y <= y2)) {\n x = ((y - y1) / (y2 - y1)) * (x2 - x1) + x1;\n intersections.push(x);\n }\n x1 = x2;\n y1 = y2;\n }\n }\n // Find the longest segment of the horizontal line that has its center point\n // inside the linear ring.\n let pointX = NaN;\n let maxSegmentLength = -Infinity;\n intersections.sort(ascending);\n x1 = intersections[0];\n for (i = 1, ii = intersections.length; i < ii; ++i) {\n x2 = intersections[i];\n const segmentLength = Math.abs(x2 - x1);\n if (segmentLength > maxSegmentLength) {\n x = (x1 + x2) / 2;\n if (linearRingsContainsXY(flatCoordinates, offset, ends, stride, x, y)) {\n pointX = x;\n maxSegmentLength = segmentLength;\n }\n }\n x1 = x2;\n }\n if (isNaN(pointX)) {\n // There is no horizontal line that has its center point inside the linear\n // ring. Use the center of the the linear ring's extent.\n pointX = flatCenters[flatCentersOffset];\n }\n if (dest) {\n dest.push(pointX, y, maxSegmentLength);\n return dest;\n }\n return [pointX, y, maxSegmentLength];\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array>} endss Endss.\n * @param {number} stride Stride.\n * @param {Array} flatCenters Flat centers.\n * @return {Array} Interior points as XYM coordinates, where M is the\n * length of the horizontal intersection that the point belongs to.\n */\nexport function getInteriorPointsOfMultiArray(\n flatCoordinates,\n offset,\n endss,\n stride,\n flatCenters\n) {\n let interiorPoints = [];\n for (let i = 0, ii = endss.length; i < ii; ++i) {\n const ends = endss[i];\n interiorPoints = getInteriorPointOfArray(\n flatCoordinates,\n offset,\n ends,\n stride,\n flatCenters,\n 2 * i,\n interiorPoints\n );\n offset = ends[ends.length - 1];\n }\n return interiorPoints;\n}\n","/**\n * @module ol/geom/flat/segments\n */\n\n/**\n * This function calls `callback` for each segment of the flat coordinates\n * array. If the callback returns a truthy value the function returns that\n * value immediately. Otherwise the function returns `false`.\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {function(import(\"../../coordinate.js\").Coordinate, import(\"../../coordinate.js\").Coordinate): T} callback Function\n * called for each segment.\n * @return {T|boolean} Value.\n * @template T\n */\nexport function forEach(flatCoordinates, offset, end, stride, callback) {\n let ret;\n offset += stride;\n for (; offset < end; offset += stride) {\n ret = callback(\n flatCoordinates.slice(offset - stride, offset),\n flatCoordinates.slice(offset, offset + stride)\n );\n if (ret) {\n return ret;\n }\n }\n return false;\n}\n","/**\n * @module ol/geom/flat/intersectsextent\n */\nimport {\n containsExtent,\n createEmpty,\n extendFlatCoordinates,\n intersects,\n intersectsSegment,\n} from '../../extent.js';\nimport {forEach as forEachSegment} from './segments.js';\nimport {linearRingContainsExtent, linearRingContainsXY} from './contains.js';\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {import(\"../../extent.js\").Extent} extent Extent.\n * @return {boolean} True if the geometry and the extent intersect.\n */\nexport function intersectsLineString(\n flatCoordinates,\n offset,\n end,\n stride,\n extent\n) {\n const coordinatesExtent = extendFlatCoordinates(\n createEmpty(),\n flatCoordinates,\n offset,\n end,\n stride\n );\n if (!intersects(extent, coordinatesExtent)) {\n return false;\n }\n if (containsExtent(extent, coordinatesExtent)) {\n return true;\n }\n if (coordinatesExtent[0] >= extent[0] && coordinatesExtent[2] <= extent[2]) {\n return true;\n }\n if (coordinatesExtent[1] >= extent[1] && coordinatesExtent[3] <= extent[3]) {\n return true;\n }\n return forEachSegment(\n flatCoordinates,\n offset,\n end,\n stride,\n /**\n * @param {import(\"../../coordinate.js\").Coordinate} point1 Start point.\n * @param {import(\"../../coordinate.js\").Coordinate} point2 End point.\n * @return {boolean} `true` if the segment and the extent intersect,\n * `false` otherwise.\n */\n function (point1, point2) {\n return intersectsSegment(extent, point1, point2);\n }\n );\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array} ends Ends.\n * @param {number} stride Stride.\n * @param {import(\"../../extent.js\").Extent} extent Extent.\n * @return {boolean} True if the geometry and the extent intersect.\n */\nexport function intersectsLineStringArray(\n flatCoordinates,\n offset,\n ends,\n stride,\n extent\n) {\n for (let i = 0, ii = ends.length; i < ii; ++i) {\n if (\n intersectsLineString(flatCoordinates, offset, ends[i], stride, extent)\n ) {\n return true;\n }\n offset = ends[i];\n }\n return false;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {import(\"../../extent.js\").Extent} extent Extent.\n * @return {boolean} True if the geometry and the extent intersect.\n */\nexport function intersectsLinearRing(\n flatCoordinates,\n offset,\n end,\n stride,\n extent\n) {\n if (intersectsLineString(flatCoordinates, offset, end, stride, extent)) {\n return true;\n }\n if (\n linearRingContainsXY(\n flatCoordinates,\n offset,\n end,\n stride,\n extent[0],\n extent[1]\n )\n ) {\n return true;\n }\n if (\n linearRingContainsXY(\n flatCoordinates,\n offset,\n end,\n stride,\n extent[0],\n extent[3]\n )\n ) {\n return true;\n }\n if (\n linearRingContainsXY(\n flatCoordinates,\n offset,\n end,\n stride,\n extent[2],\n extent[1]\n )\n ) {\n return true;\n }\n if (\n linearRingContainsXY(\n flatCoordinates,\n offset,\n end,\n stride,\n extent[2],\n extent[3]\n )\n ) {\n return true;\n }\n return false;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array} ends Ends.\n * @param {number} stride Stride.\n * @param {import(\"../../extent.js\").Extent} extent Extent.\n * @return {boolean} True if the geometry and the extent intersect.\n */\nexport function intersectsLinearRingArray(\n flatCoordinates,\n offset,\n ends,\n stride,\n extent\n) {\n if (!intersectsLinearRing(flatCoordinates, offset, ends[0], stride, extent)) {\n return false;\n }\n if (ends.length === 1) {\n return true;\n }\n for (let i = 1, ii = ends.length; i < ii; ++i) {\n if (\n linearRingContainsExtent(\n flatCoordinates,\n ends[i - 1],\n ends[i],\n stride,\n extent\n )\n ) {\n if (\n !intersectsLineString(\n flatCoordinates,\n ends[i - 1],\n ends[i],\n stride,\n extent\n )\n ) {\n return false;\n }\n }\n }\n return true;\n}\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array>} endss Endss.\n * @param {number} stride Stride.\n * @param {import(\"../../extent.js\").Extent} extent Extent.\n * @return {boolean} True if the geometry and the extent intersect.\n */\nexport function intersectsLinearRingMultiArray(\n flatCoordinates,\n offset,\n endss,\n stride,\n extent\n) {\n for (let i = 0, ii = endss.length; i < ii; ++i) {\n const ends = endss[i];\n if (\n intersectsLinearRingArray(flatCoordinates, offset, ends, stride, extent)\n ) {\n return true;\n }\n offset = ends[ends.length - 1];\n }\n return false;\n}\n","/**\n * @module ol/geom/flat/reverse\n */\n\n/**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n */\nexport function coordinates(flatCoordinates, offset, end, stride) {\n while (offset < end - stride) {\n for (let i = 0; i < stride; ++i) {\n const tmp = flatCoordinates[offset + i];\n flatCoordinates[offset + i] = flatCoordinates[end - stride + i];\n flatCoordinates[end - stride + i] = tmp;\n }\n offset += stride;\n end -= stride;\n }\n}\n","/**\n * @module ol/geom/flat/orient\n */\nimport {coordinates as reverseCoordinates} from './reverse.js';\n\n/**\n * Is the linear ring oriented clockwise in a coordinate system with a bottom-left\n * coordinate origin? For a coordinate system with a top-left coordinate origin,\n * the ring's orientation is clockwise when this function returns false.\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @return {boolean} Is clockwise.\n */\nexport function linearRingIsClockwise(flatCoordinates, offset, end, stride) {\n // https://stackoverflow.com/q/1165647/clockwise-method#1165943\n // https://github.com/OSGeo/gdal/blob/master/gdal/ogr/ogrlinearring.cpp\n let edge = 0;\n let x1 = flatCoordinates[end - stride];\n let y1 = flatCoordinates[end - stride + 1];\n for (; offset < end; offset += stride) {\n const x2 = flatCoordinates[offset];\n const y2 = flatCoordinates[offset + 1];\n edge += (x2 - x1) * (y2 + y1);\n x1 = x2;\n y1 = y2;\n }\n return edge === 0 ? undefined : edge > 0;\n}\n\n/**\n * Determines if linear rings are oriented. By default, left-hand orientation\n * is tested (first ring must be clockwise, remaining rings counter-clockwise).\n * To test for right-hand orientation, use the `right` argument.\n *\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array} ends Array of end indexes.\n * @param {number} stride Stride.\n * @param {boolean} [right] Test for right-hand orientation\n * (counter-clockwise exterior ring and clockwise interior rings).\n * @return {boolean} Rings are correctly oriented.\n */\nexport function linearRingsAreOriented(\n flatCoordinates,\n offset,\n ends,\n stride,\n right\n) {\n right = right !== undefined ? right : false;\n for (let i = 0, ii = ends.length; i < ii; ++i) {\n const end = ends[i];\n const isClockwise = linearRingIsClockwise(\n flatCoordinates,\n offset,\n end,\n stride\n );\n if (i === 0) {\n if ((right && isClockwise) || (!right && !isClockwise)) {\n return false;\n }\n } else {\n if ((right && !isClockwise) || (!right && isClockwise)) {\n return false;\n }\n }\n offset = end;\n }\n return true;\n}\n\n/**\n * Determines if linear rings are oriented. By default, left-hand orientation\n * is tested (first ring must be clockwise, remaining rings counter-clockwise).\n * To test for right-hand orientation, use the `right` argument.\n *\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array>} endss Array of array of end indexes.\n * @param {number} stride Stride.\n * @param {boolean} [right] Test for right-hand orientation\n * (counter-clockwise exterior ring and clockwise interior rings).\n * @return {boolean} Rings are correctly oriented.\n */\nexport function linearRingssAreOriented(\n flatCoordinates,\n offset,\n endss,\n stride,\n right\n) {\n for (let i = 0, ii = endss.length; i < ii; ++i) {\n const ends = endss[i];\n if (!linearRingsAreOriented(flatCoordinates, offset, ends, stride, right)) {\n return false;\n }\n if (ends.length) {\n offset = ends[ends.length - 1];\n }\n }\n return true;\n}\n\n/**\n * Orient coordinates in a flat array of linear rings. By default, rings\n * are oriented following the left-hand rule (clockwise for exterior and\n * counter-clockwise for interior rings). To orient according to the\n * right-hand rule, use the `right` argument.\n *\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array} ends Ends.\n * @param {number} stride Stride.\n * @param {boolean} [right] Follow the right-hand rule for orientation.\n * @return {number} End.\n */\nexport function orientLinearRings(\n flatCoordinates,\n offset,\n ends,\n stride,\n right\n) {\n right = right !== undefined ? right : false;\n for (let i = 0, ii = ends.length; i < ii; ++i) {\n const end = ends[i];\n const isClockwise = linearRingIsClockwise(\n flatCoordinates,\n offset,\n end,\n stride\n );\n const reverse =\n i === 0\n ? (right && isClockwise) || (!right && !isClockwise)\n : (right && !isClockwise) || (!right && isClockwise);\n if (reverse) {\n reverseCoordinates(flatCoordinates, offset, end, stride);\n }\n offset = end;\n }\n return offset;\n}\n\n/**\n * Orient coordinates in a flat array of linear rings. By default, rings\n * are oriented following the left-hand rule (clockwise for exterior and\n * counter-clockwise for interior rings). To orient according to the\n * right-hand rule, use the `right` argument.\n *\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array>} endss Array of array of end indexes.\n * @param {number} stride Stride.\n * @param {boolean} [right] Follow the right-hand rule for orientation.\n * @return {number} End.\n */\nexport function orientLinearRingsArray(\n flatCoordinates,\n offset,\n endss,\n stride,\n right\n) {\n for (let i = 0, ii = endss.length; i < ii; ++i) {\n offset = orientLinearRings(\n flatCoordinates,\n offset,\n endss[i],\n stride,\n right\n );\n }\n return offset;\n}\n\n/**\n * Return a two-dimensional endss\n * @param {Array} flatCoordinates Flat coordinates\n * @param {Array} ends Linear ring end indexes\n * @return {Array>} Two dimensional endss array that can\n * be used to construct a MultiPolygon\n */\nexport function inflateEnds(flatCoordinates, ends) {\n const endss = [];\n let offset = 0;\n let prevEndIndex = 0;\n for (let i = 0, ii = ends.length; i < ii; ++i) {\n const end = ends[i];\n // classifies an array of rings into polygons with outer rings and holes\n if (!linearRingIsClockwise(flatCoordinates, offset, end, 2)) {\n endss.push(ends.slice(prevEndIndex, i + 1));\n } else {\n if (endss.length === 0) {\n continue;\n }\n endss[endss.length - 1].push(ends[prevEndIndex]);\n }\n prevEndIndex = i + 1;\n offset = end;\n }\n return endss;\n}\n","/**\n * @module ol/geom/Polygon\n */\nimport LinearRing from './LinearRing.js';\nimport Point from './Point.js';\nimport SimpleGeometry from './SimpleGeometry.js';\nimport {arrayMaxSquaredDelta, assignClosestArrayPoint} from './flat/closest.js';\nimport {closestSquaredDistanceXY, getCenter, isEmpty} from '../extent.js';\nimport {deflateCoordinatesArray} from './flat/deflate.js';\nimport {extend} from '../array.js';\nimport {getInteriorPointOfArray} from './flat/interiorpoint.js';\nimport {inflateCoordinatesArray} from './flat/inflate.js';\nimport {intersectsLinearRingArray} from './flat/intersectsextent.js';\nimport {linearRingsAreOriented, orientLinearRings} from './flat/orient.js';\nimport {linearRings as linearRingsArea} from './flat/area.js';\nimport {linearRingsContainsXY} from './flat/contains.js';\nimport {modulo} from '../math.js';\nimport {quantizeArray} from './flat/simplify.js';\nimport {offset as sphereOffset} from '../sphere.js';\n\n/**\n * @classdesc\n * Polygon geometry.\n *\n * @api\n */\nclass Polygon extends SimpleGeometry {\n /**\n * @param {!Array>|!Array} coordinates\n * Array of linear rings that define the polygon. The first linear ring of the\n * array defines the outer-boundary or surface of the polygon. Each subsequent\n * linear ring defines a hole in the surface of the polygon. A linear ring is\n * an array of vertices' coordinates where the first coordinate and the last are\n * equivalent. (For internal use, flat coordinates in combination with\n * `layout` and `ends` are also accepted.)\n * @param {import(\"./Geometry.js\").GeometryLayout} [layout] Layout.\n * @param {Array} [ends] Ends (for internal use with flat coordinates).\n */\n constructor(coordinates, layout, ends) {\n super();\n\n /**\n * @type {Array}\n * @private\n */\n this.ends_ = [];\n\n /**\n * @private\n * @type {number}\n */\n this.flatInteriorPointRevision_ = -1;\n\n /**\n * @private\n * @type {import(\"../coordinate.js\").Coordinate}\n */\n this.flatInteriorPoint_ = null;\n\n /**\n * @private\n * @type {number}\n */\n this.maxDelta_ = -1;\n\n /**\n * @private\n * @type {number}\n */\n this.maxDeltaRevision_ = -1;\n\n /**\n * @private\n * @type {number}\n */\n this.orientedRevision_ = -1;\n\n /**\n * @private\n * @type {Array}\n */\n this.orientedFlatCoordinates_ = null;\n\n if (layout !== undefined && ends) {\n this.setFlatCoordinates(\n layout,\n /** @type {Array} */ (coordinates)\n );\n this.ends_ = ends;\n } else {\n this.setCoordinates(\n /** @type {Array>} */ (\n coordinates\n ),\n layout\n );\n }\n }\n\n /**\n * Append the passed linear ring to this polygon.\n * @param {LinearRing} linearRing Linear ring.\n * @api\n */\n appendLinearRing(linearRing) {\n if (!this.flatCoordinates) {\n this.flatCoordinates = linearRing.getFlatCoordinates().slice();\n } else {\n extend(this.flatCoordinates, linearRing.getFlatCoordinates());\n }\n this.ends_.push(this.flatCoordinates.length);\n this.changed();\n }\n\n /**\n * Make a complete copy of the geometry.\n * @return {!Polygon} Clone.\n * @api\n */\n clone() {\n const polygon = new Polygon(\n this.flatCoordinates.slice(),\n this.layout,\n this.ends_.slice()\n );\n polygon.applyProperties(this);\n return polygon;\n }\n\n /**\n * @param {number} x X.\n * @param {number} y Y.\n * @param {import(\"../coordinate.js\").Coordinate} closestPoint Closest point.\n * @param {number} minSquaredDistance Minimum squared distance.\n * @return {number} Minimum squared distance.\n */\n closestPointXY(x, y, closestPoint, minSquaredDistance) {\n if (minSquaredDistance < closestSquaredDistanceXY(this.getExtent(), x, y)) {\n return minSquaredDistance;\n }\n if (this.maxDeltaRevision_ != this.getRevision()) {\n this.maxDelta_ = Math.sqrt(\n arrayMaxSquaredDelta(\n this.flatCoordinates,\n 0,\n this.ends_,\n this.stride,\n 0\n )\n );\n this.maxDeltaRevision_ = this.getRevision();\n }\n return assignClosestArrayPoint(\n this.flatCoordinates,\n 0,\n this.ends_,\n this.stride,\n this.maxDelta_,\n true,\n x,\n y,\n closestPoint,\n minSquaredDistance\n );\n }\n\n /**\n * @param {number} x X.\n * @param {number} y Y.\n * @return {boolean} Contains (x, y).\n */\n containsXY(x, y) {\n return linearRingsContainsXY(\n this.getOrientedFlatCoordinates(),\n 0,\n this.ends_,\n this.stride,\n x,\n y\n );\n }\n\n /**\n * Return the area of the polygon on projected plane.\n * @return {number} Area (on projected plane).\n * @api\n */\n getArea() {\n return linearRingsArea(\n this.getOrientedFlatCoordinates(),\n 0,\n this.ends_,\n this.stride\n );\n }\n\n /**\n * Get the coordinate array for this geometry. This array has the structure\n * of a GeoJSON coordinate array for polygons.\n *\n * @param {boolean} [right] Orient coordinates according to the right-hand\n * rule (counter-clockwise for exterior and clockwise for interior rings).\n * If `false`, coordinates will be oriented according to the left-hand rule\n * (clockwise for exterior and counter-clockwise for interior rings).\n * By default, coordinate orientation will depend on how the geometry was\n * constructed.\n * @return {Array>} Coordinates.\n * @api\n */\n getCoordinates(right) {\n let flatCoordinates;\n if (right !== undefined) {\n flatCoordinates = this.getOrientedFlatCoordinates().slice();\n orientLinearRings(flatCoordinates, 0, this.ends_, this.stride, right);\n } else {\n flatCoordinates = this.flatCoordinates;\n }\n\n return inflateCoordinatesArray(flatCoordinates, 0, this.ends_, this.stride);\n }\n\n /**\n * @return {Array} Ends.\n */\n getEnds() {\n return this.ends_;\n }\n\n /**\n * @return {Array} Interior point.\n */\n getFlatInteriorPoint() {\n if (this.flatInteriorPointRevision_ != this.getRevision()) {\n const flatCenter = getCenter(this.getExtent());\n this.flatInteriorPoint_ = getInteriorPointOfArray(\n this.getOrientedFlatCoordinates(),\n 0,\n this.ends_,\n this.stride,\n flatCenter,\n 0\n );\n this.flatInteriorPointRevision_ = this.getRevision();\n }\n return this.flatInteriorPoint_;\n }\n\n /**\n * Return an interior point of the polygon.\n * @return {Point} Interior point as XYM coordinate, where M is the\n * length of the horizontal intersection that the point belongs to.\n * @api\n */\n getInteriorPoint() {\n return new Point(this.getFlatInteriorPoint(), 'XYM');\n }\n\n /**\n * Return the number of rings of the polygon, this includes the exterior\n * ring and any interior rings.\n *\n * @return {number} Number of rings.\n * @api\n */\n getLinearRingCount() {\n return this.ends_.length;\n }\n\n /**\n * Return the Nth linear ring of the polygon geometry. Return `null` if the\n * given index is out of range.\n * The exterior linear ring is available at index `0` and the interior rings\n * at index `1` and beyond.\n *\n * @param {number} index Index.\n * @return {LinearRing|null} Linear ring.\n * @api\n */\n getLinearRing(index) {\n if (index < 0 || this.ends_.length <= index) {\n return null;\n }\n return new LinearRing(\n this.flatCoordinates.slice(\n index === 0 ? 0 : this.ends_[index - 1],\n this.ends_[index]\n ),\n this.layout\n );\n }\n\n /**\n * Return the linear rings of the polygon.\n * @return {Array} Linear rings.\n * @api\n */\n getLinearRings() {\n const layout = this.layout;\n const flatCoordinates = this.flatCoordinates;\n const ends = this.ends_;\n const linearRings = [];\n let offset = 0;\n for (let i = 0, ii = ends.length; i < ii; ++i) {\n const end = ends[i];\n const linearRing = new LinearRing(\n flatCoordinates.slice(offset, end),\n layout\n );\n linearRings.push(linearRing);\n offset = end;\n }\n return linearRings;\n }\n\n /**\n * @return {Array} Oriented flat coordinates.\n */\n getOrientedFlatCoordinates() {\n if (this.orientedRevision_ != this.getRevision()) {\n const flatCoordinates = this.flatCoordinates;\n if (linearRingsAreOriented(flatCoordinates, 0, this.ends_, this.stride)) {\n this.orientedFlatCoordinates_ = flatCoordinates;\n } else {\n this.orientedFlatCoordinates_ = flatCoordinates.slice();\n this.orientedFlatCoordinates_.length = orientLinearRings(\n this.orientedFlatCoordinates_,\n 0,\n this.ends_,\n this.stride\n );\n }\n this.orientedRevision_ = this.getRevision();\n }\n return this.orientedFlatCoordinates_;\n }\n\n /**\n * @param {number} squaredTolerance Squared tolerance.\n * @return {Polygon} Simplified Polygon.\n * @protected\n */\n getSimplifiedGeometryInternal(squaredTolerance) {\n const simplifiedFlatCoordinates = [];\n const simplifiedEnds = [];\n simplifiedFlatCoordinates.length = quantizeArray(\n this.flatCoordinates,\n 0,\n this.ends_,\n this.stride,\n Math.sqrt(squaredTolerance),\n simplifiedFlatCoordinates,\n 0,\n simplifiedEnds\n );\n return new Polygon(simplifiedFlatCoordinates, 'XY', simplifiedEnds);\n }\n\n /**\n * Get the type of this geometry.\n * @return {import(\"./Geometry.js\").Type} Geometry type.\n * @api\n */\n getType() {\n return 'Polygon';\n }\n\n /**\n * Test if the geometry and the passed extent intersect.\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @return {boolean} `true` if the geometry and the extent intersect.\n * @api\n */\n intersectsExtent(extent) {\n return intersectsLinearRingArray(\n this.getOrientedFlatCoordinates(),\n 0,\n this.ends_,\n this.stride,\n extent\n );\n }\n\n /**\n * Set the coordinates of the polygon.\n * @param {!Array>} coordinates Coordinates.\n * @param {import(\"./Geometry.js\").GeometryLayout} [layout] Layout.\n * @api\n */\n setCoordinates(coordinates, layout) {\n this.setLayout(layout, coordinates, 2);\n if (!this.flatCoordinates) {\n this.flatCoordinates = [];\n }\n const ends = deflateCoordinatesArray(\n this.flatCoordinates,\n 0,\n coordinates,\n this.stride,\n this.ends_\n );\n this.flatCoordinates.length = ends.length === 0 ? 0 : ends[ends.length - 1];\n this.changed();\n }\n}\n\nexport default Polygon;\n\n/**\n * Create an approximation of a circle on the surface of a sphere.\n * @param {import(\"../coordinate.js\").Coordinate} center Center (`[lon, lat]` in degrees).\n * @param {number} radius The great-circle distance from the center to\n * the polygon vertices in meters.\n * @param {number} [n] Optional number of vertices for the resulting\n * polygon. Default is `32`.\n * @param {number} [sphereRadius] Optional radius for the sphere (defaults to\n * the Earth's mean radius using the WGS84 ellipsoid).\n * @return {Polygon} The \"circular\" polygon.\n * @api\n */\nexport function circular(center, radius, n, sphereRadius) {\n n = n ? n : 32;\n /** @type {Array} */\n const flatCoordinates = [];\n for (let i = 0; i < n; ++i) {\n extend(\n flatCoordinates,\n sphereOffset(center, radius, (2 * Math.PI * i) / n, sphereRadius)\n );\n }\n flatCoordinates.push(flatCoordinates[0], flatCoordinates[1]);\n return new Polygon(flatCoordinates, 'XY', [flatCoordinates.length]);\n}\n\n/**\n * Create a polygon from an extent. The layout used is `XY`.\n * @param {import(\"../extent.js\").Extent} extent The extent.\n * @return {Polygon} The polygon.\n * @api\n */\nexport function fromExtent(extent) {\n if (isEmpty(extent)) {\n throw new Error('Cannot create polygon from empty extent');\n }\n const minX = extent[0];\n const minY = extent[1];\n const maxX = extent[2];\n const maxY = extent[3];\n const flatCoordinates = [\n minX,\n minY,\n minX,\n maxY,\n maxX,\n maxY,\n maxX,\n minY,\n minX,\n minY,\n ];\n return new Polygon(flatCoordinates, 'XY', [flatCoordinates.length]);\n}\n\n/**\n * Create a regular polygon from a circle.\n * @param {import(\"./Circle.js\").default} circle Circle geometry.\n * @param {number} [sides] Number of sides of the polygon. Default is 32.\n * @param {number} [angle] Start angle for the first vertex of the polygon in\n * counter-clockwise radians. 0 means East. Default is 0.\n * @return {Polygon} Polygon geometry.\n * @api\n */\nexport function fromCircle(circle, sides, angle) {\n sides = sides ? sides : 32;\n const stride = circle.getStride();\n const layout = circle.getLayout();\n const center = circle.getCenter();\n const arrayLength = stride * (sides + 1);\n const flatCoordinates = new Array(arrayLength);\n for (let i = 0; i < arrayLength; i += stride) {\n flatCoordinates[i] = 0;\n flatCoordinates[i + 1] = 0;\n for (let j = 2; j < stride; j++) {\n flatCoordinates[i + j] = center[j];\n }\n }\n const ends = [flatCoordinates.length];\n const polygon = new Polygon(flatCoordinates, layout, ends);\n makeRegular(polygon, center, circle.getRadius(), angle);\n return polygon;\n}\n\n/**\n * Modify the coordinates of a polygon to make it a regular polygon.\n * @param {Polygon} polygon Polygon geometry.\n * @param {import(\"../coordinate.js\").Coordinate} center Center of the regular polygon.\n * @param {number} radius Radius of the regular polygon.\n * @param {number} [angle] Start angle for the first vertex of the polygon in\n * counter-clockwise radians. 0 means East. Default is 0.\n */\nexport function makeRegular(polygon, center, radius, angle) {\n const flatCoordinates = polygon.getFlatCoordinates();\n const stride = polygon.getStride();\n const sides = flatCoordinates.length / stride - 1;\n const startAngle = angle ? angle : 0;\n for (let i = 0; i <= sides; ++i) {\n const offset = i * stride;\n const angle = startAngle + (modulo(i, sides) * 2 * Math.PI) / sides;\n flatCoordinates[offset] = center[0] + radius * Math.cos(angle);\n flatCoordinates[offset + 1] = center[1] + radius * Math.sin(angle);\n }\n polygon.changed();\n}\n","/**\n * @module ol/Geolocation\n */\nimport BaseEvent from './events/Event.js';\nimport BaseObject from './Object.js';\nimport {circular as circularPolygon} from './geom/Polygon.js';\nimport {\n get as getProjection,\n getTransformFromProjections,\n identityTransform,\n} from './proj.js';\nimport {toRadians} from './math.js';\n\n/**\n * @enum {string}\n */\nconst Property = {\n ACCURACY: 'accuracy',\n ACCURACY_GEOMETRY: 'accuracyGeometry',\n ALTITUDE: 'altitude',\n ALTITUDE_ACCURACY: 'altitudeAccuracy',\n HEADING: 'heading',\n POSITION: 'position',\n PROJECTION: 'projection',\n SPEED: 'speed',\n TRACKING: 'tracking',\n TRACKING_OPTIONS: 'trackingOptions',\n};\n\n/**\n * @enum string\n */\nconst GeolocationErrorType = {\n /**\n * Triggered when a `GeolocationPositionError` occurs.\n * @event module:ol/Geolocation.GeolocationError#error\n * @api\n */\n ERROR: 'error',\n};\n\n/**\n * @classdesc\n * Events emitted on [GeolocationPositionError](https://developer.mozilla.org/en-US/docs/Web/API/GeolocationPositionError).\n */\nexport class GeolocationError extends BaseEvent {\n /**\n * @param {GeolocationPositionError} error error object.\n */\n constructor(error) {\n super(GeolocationErrorType.ERROR);\n\n /**\n * Code of the underlying `GeolocationPositionError`.\n * @type {number}\n * @api\n */\n this.code = error.code;\n\n /**\n * Message of the underlying `GeolocationPositionError`.\n * @type {string}\n * @api\n */\n this.message = error.message;\n }\n}\n\n/**\n * @typedef {Object} Options\n * @property {boolean} [tracking=false] Start Tracking right after\n * instantiation.\n * @property {PositionOptions} [trackingOptions] Tracking options.\n * See https://www.w3.org/TR/geolocation-API/#position_options_interface.\n * @property {import(\"./proj.js\").ProjectionLike} [projection] The projection the position\n * is reported in.\n */\n\n/**\n * @typedef {import(\"./ObjectEventType\").Types|'change:accuracy'|'change:accuracyGeometry'|'change:altitude'|\n * 'change:altitudeAccuracy'|'change:heading'|'change:position'|'change:projection'|'change:speed'|'change:tracking'|\n * 'change:trackingOptions'} GeolocationObjectEventTypes\n */\n\n/***\n * @template Return\n * @typedef {import(\"./Observable\").OnSignature &\n * import(\"./Observable\").OnSignature<'error', GeolocationError, Return> &\n * import(\"./Observable\").CombinedOnSignature &\n * import(\"./Observable\").OnSignature} GeolocationOnSignature\n */\n\n/**\n * @classdesc\n * Helper class for providing HTML5 Geolocation capabilities.\n * The [Geolocation API](https://www.w3.org/TR/geolocation-API/)\n * is used to locate a user's position.\n *\n * To get notified of position changes and errors, register listeners for the generic\n * `change` event and the `error` event on your instance of {@link module:ol/Geolocation~Geolocation}.\n *\n * Example:\n *\n * const geolocation = new Geolocation({\n * // take the projection to use from the map's view\n * projection: view.getProjection()\n * });\n * // listen to changes in position\n * geolocation.on('change', function(evt) {\n * console.log(geolocation.getPosition());\n * });\n * // listen to error\n * geolocation.on('error', function(evt) {\n * window.console.log(evt.message);\n * });\n *\n * @fires GeolocationError\n * @api\n */\nclass Geolocation extends BaseObject {\n /**\n * @param {Options} [options] Options.\n */\n constructor(options) {\n super();\n\n /***\n * @type {GeolocationOnSignature}\n */\n this.on;\n\n /***\n * @type {GeolocationOnSignature}\n */\n this.once;\n\n /***\n * @type {GeolocationOnSignature}\n */\n this.un;\n\n options = options || {};\n\n /**\n * The unprojected (EPSG:4326) device position.\n * @private\n * @type {?import(\"./coordinate.js\").Coordinate}\n */\n this.position_ = null;\n\n /**\n * @private\n * @type {import(\"./proj.js\").TransformFunction}\n */\n this.transform_ = identityTransform;\n\n /**\n * @private\n * @type {number|undefined}\n */\n this.watchId_ = undefined;\n\n this.addChangeListener(Property.PROJECTION, this.handleProjectionChanged_);\n this.addChangeListener(Property.TRACKING, this.handleTrackingChanged_);\n\n if (options.projection !== undefined) {\n this.setProjection(options.projection);\n }\n if (options.trackingOptions !== undefined) {\n this.setTrackingOptions(options.trackingOptions);\n }\n\n this.setTracking(options.tracking !== undefined ? options.tracking : false);\n }\n\n /**\n * Clean up.\n */\n disposeInternal() {\n this.setTracking(false);\n super.disposeInternal();\n }\n\n /**\n * @private\n */\n handleProjectionChanged_() {\n const projection = this.getProjection();\n if (projection) {\n this.transform_ = getTransformFromProjections(\n getProjection('EPSG:4326'),\n projection\n );\n if (this.position_) {\n this.set(Property.POSITION, this.transform_(this.position_));\n }\n }\n }\n\n /**\n * @private\n */\n handleTrackingChanged_() {\n if ('geolocation' in navigator) {\n const tracking = this.getTracking();\n if (tracking && this.watchId_ === undefined) {\n this.watchId_ = navigator.geolocation.watchPosition(\n this.positionChange_.bind(this),\n this.positionError_.bind(this),\n this.getTrackingOptions()\n );\n } else if (!tracking && this.watchId_ !== undefined) {\n navigator.geolocation.clearWatch(this.watchId_);\n this.watchId_ = undefined;\n }\n }\n }\n\n /**\n * @private\n * @param {GeolocationPosition} position position event.\n */\n positionChange_(position) {\n const coords = position.coords;\n this.set(Property.ACCURACY, coords.accuracy);\n this.set(\n Property.ALTITUDE,\n coords.altitude === null ? undefined : coords.altitude\n );\n this.set(\n Property.ALTITUDE_ACCURACY,\n coords.altitudeAccuracy === null ? undefined : coords.altitudeAccuracy\n );\n this.set(\n Property.HEADING,\n coords.heading === null ? undefined : toRadians(coords.heading)\n );\n if (!this.position_) {\n this.position_ = [coords.longitude, coords.latitude];\n } else {\n this.position_[0] = coords.longitude;\n this.position_[1] = coords.latitude;\n }\n const projectedPosition = this.transform_(this.position_);\n this.set(Property.POSITION, projectedPosition.slice());\n this.set(Property.SPEED, coords.speed === null ? undefined : coords.speed);\n const geometry = circularPolygon(this.position_, coords.accuracy);\n geometry.applyTransform(this.transform_);\n this.set(Property.ACCURACY_GEOMETRY, geometry);\n this.changed();\n }\n\n /**\n * @private\n * @param {GeolocationPositionError} error error object.\n */\n positionError_(error) {\n this.dispatchEvent(new GeolocationError(error));\n }\n\n /**\n * Get the accuracy of the position in meters.\n * @return {number|undefined} The accuracy of the position measurement in\n * meters.\n * @observable\n * @api\n */\n getAccuracy() {\n return /** @type {number|undefined} */ (this.get(Property.ACCURACY));\n }\n\n /**\n * Get a geometry of the position accuracy.\n * @return {?import(\"./geom/Polygon.js\").default} A geometry of the position accuracy.\n * @observable\n * @api\n */\n getAccuracyGeometry() {\n return /** @type {?import(\"./geom/Polygon.js\").default} */ (\n this.get(Property.ACCURACY_GEOMETRY) || null\n );\n }\n\n /**\n * Get the altitude associated with the position.\n * @return {number|undefined} The altitude of the position in meters above mean\n * sea level.\n * @observable\n * @api\n */\n getAltitude() {\n return /** @type {number|undefined} */ (this.get(Property.ALTITUDE));\n }\n\n /**\n * Get the altitude accuracy of the position.\n * @return {number|undefined} The accuracy of the altitude measurement in\n * meters.\n * @observable\n * @api\n */\n getAltitudeAccuracy() {\n return /** @type {number|undefined} */ (\n this.get(Property.ALTITUDE_ACCURACY)\n );\n }\n\n /**\n * Get the heading as radians clockwise from North.\n * Note: depending on the browser, the heading is only defined if the `enableHighAccuracy`\n * is set to `true` in the tracking options.\n * @return {number|undefined} The heading of the device in radians from north.\n * @observable\n * @api\n */\n getHeading() {\n return /** @type {number|undefined} */ (this.get(Property.HEADING));\n }\n\n /**\n * Get the position of the device.\n * @return {import(\"./coordinate.js\").Coordinate|undefined} The current position of the device reported\n * in the current projection.\n * @observable\n * @api\n */\n getPosition() {\n return /** @type {import(\"./coordinate.js\").Coordinate|undefined} */ (\n this.get(Property.POSITION)\n );\n }\n\n /**\n * Get the projection associated with the position.\n * @return {import(\"./proj/Projection.js\").default|undefined} The projection the position is\n * reported in.\n * @observable\n * @api\n */\n getProjection() {\n return /** @type {import(\"./proj/Projection.js\").default|undefined} */ (\n this.get(Property.PROJECTION)\n );\n }\n\n /**\n * Get the speed in meters per second.\n * @return {number|undefined} The instantaneous speed of the device in meters\n * per second.\n * @observable\n * @api\n */\n getSpeed() {\n return /** @type {number|undefined} */ (this.get(Property.SPEED));\n }\n\n /**\n * Determine if the device location is being tracked.\n * @return {boolean} The device location is being tracked.\n * @observable\n * @api\n */\n getTracking() {\n return /** @type {boolean} */ (this.get(Property.TRACKING));\n }\n\n /**\n * Get the tracking options.\n * See https://www.w3.org/TR/geolocation-API/#position-options.\n * @return {PositionOptions|undefined} PositionOptions as defined by\n * the [HTML5 Geolocation spec\n * ](https://www.w3.org/TR/geolocation-API/#position_options_interface).\n * @observable\n * @api\n */\n getTrackingOptions() {\n return /** @type {PositionOptions|undefined} */ (\n this.get(Property.TRACKING_OPTIONS)\n );\n }\n\n /**\n * Set the projection to use for transforming the coordinates.\n * @param {import(\"./proj.js\").ProjectionLike} projection The projection the position is\n * reported in.\n * @observable\n * @api\n */\n setProjection(projection) {\n this.set(Property.PROJECTION, getProjection(projection));\n }\n\n /**\n * Enable or disable tracking.\n * @param {boolean} tracking Enable tracking.\n * @observable\n * @api\n */\n setTracking(tracking) {\n this.set(Property.TRACKING, tracking);\n }\n\n /**\n * Set the tracking options.\n * See http://www.w3.org/TR/geolocation-API/#position-options.\n * @param {PositionOptions} options PositionOptions as defined by the\n * [HTML5 Geolocation spec\n * ](http://www.w3.org/TR/geolocation-API/#position_options_interface).\n * @observable\n * @api\n */\n setTrackingOptions(options) {\n this.set(Property.TRACKING_OPTIONS, options);\n }\n}\n\nexport default Geolocation;\n","/**\n * @module ol/ImageBase\n */\nimport EventTarget from './events/Target.js';\nimport EventType from './events/EventType.js';\nimport {abstract} from './util.js';\n\n/**\n * @abstract\n */\nclass ImageBase extends EventTarget {\n /**\n * @param {import(\"./extent.js\").Extent} extent Extent.\n * @param {number|undefined} resolution Resolution.\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"./ImageState.js\").default} state State.\n */\n constructor(extent, resolution, pixelRatio, state) {\n super();\n\n /**\n * @protected\n * @type {import(\"./extent.js\").Extent}\n */\n this.extent = extent;\n\n /**\n * @private\n * @type {number}\n */\n this.pixelRatio_ = pixelRatio;\n\n /**\n * @protected\n * @type {number|undefined}\n */\n this.resolution = resolution;\n\n /**\n * @protected\n * @type {import(\"./ImageState.js\").default}\n */\n this.state = state;\n }\n\n /**\n * @protected\n */\n changed() {\n this.dispatchEvent(EventType.CHANGE);\n }\n\n /**\n * @return {import(\"./extent.js\").Extent} Extent.\n */\n getExtent() {\n return this.extent;\n }\n\n /**\n * @abstract\n * @return {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} Image.\n */\n getImage() {\n return abstract();\n }\n\n /**\n * @return {number} PixelRatio.\n */\n getPixelRatio() {\n return this.pixelRatio_;\n }\n\n /**\n * @return {number} Resolution.\n */\n getResolution() {\n return /** @type {number} */ (this.resolution);\n }\n\n /**\n * @return {import(\"./ImageState.js\").default} State.\n */\n getState() {\n return this.state;\n }\n\n /**\n * Load not yet loaded URI.\n * @abstract\n */\n load() {\n abstract();\n }\n}\n\nexport default ImageBase;\n","/**\n * @module ol/ImageState\n */\n\n/**\n * @enum {number}\n */\nexport default {\n IDLE: 0,\n LOADING: 1,\n LOADED: 2,\n ERROR: 3,\n EMPTY: 4,\n};\n","/**\n * @module ol/Image\n */\nimport EventType from './events/EventType.js';\nimport ImageBase from './ImageBase.js';\nimport ImageState from './ImageState.js';\nimport {IMAGE_DECODE} from './has.js';\nimport {getHeight} from './extent.js';\nimport {listenOnce, unlistenByKey} from './events.js';\n\n/**\n * A function that takes an {@link module:ol/Image~ImageWrapper} for the image and a\n * `{string}` for the src as arguments. It is supposed to make it so the\n * underlying image {@link module:ol/Image~ImageWrapper#getImage} is assigned the\n * content specified by the src. If not specified, the default is\n *\n * function(image, src) {\n * image.getImage().src = src;\n * }\n *\n * Providing a custom `imageLoadFunction` can be useful to load images with\n * post requests or - in general - through XHR requests, where the src of the\n * image element would be set to a data URI when the content is loaded.\n *\n * @typedef {function(ImageWrapper, string): void} LoadFunction\n * @api\n */\n\nclass ImageWrapper extends ImageBase {\n /**\n * @param {import(\"./extent.js\").Extent} extent Extent.\n * @param {number|undefined} resolution Resolution.\n * @param {number} pixelRatio Pixel ratio.\n * @param {string} src Image source URI.\n * @param {?string} crossOrigin Cross origin.\n * @param {LoadFunction} imageLoadFunction Image load function.\n * @param {CanvasRenderingContext2D} [context] Canvas context. When provided, the image will be\n * drawn into the context's canvas, and `getImage()` will return the canvas once the image\n * has finished loading.\n */\n constructor(\n extent,\n resolution,\n pixelRatio,\n src,\n crossOrigin,\n imageLoadFunction,\n context\n ) {\n super(extent, resolution, pixelRatio, ImageState.IDLE);\n\n /**\n * @private\n * @type {string}\n */\n this.src_ = src;\n\n /**\n * @private\n * @type {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement}\n */\n this.image_ = new Image();\n if (crossOrigin !== null) {\n this.image_.crossOrigin = crossOrigin;\n }\n\n /**\n * @private\n * @type {CanvasRenderingContext2D}\n */\n this.context_ = context;\n\n /**\n * @private\n * @type {?function():void}\n */\n this.unlisten_ = null;\n\n /**\n * @protected\n * @type {import(\"./ImageState.js\").default}\n */\n this.state = ImageState.IDLE;\n\n /**\n * @private\n * @type {LoadFunction}\n */\n this.imageLoadFunction_ = imageLoadFunction;\n }\n\n /**\n * @return {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} Image.\n * @api\n */\n getImage() {\n if (\n this.state == ImageState.LOADED &&\n this.context_ &&\n !(this.image_ instanceof HTMLCanvasElement)\n ) {\n const canvas = this.context_.canvas;\n canvas.width = this.image_.width;\n canvas.height = this.image_.height;\n this.context_.drawImage(this.image_, 0, 0);\n this.image_ = this.context_.canvas;\n }\n return this.image_;\n }\n\n /**\n * Tracks loading or read errors.\n *\n * @private\n */\n handleImageError_() {\n this.state = ImageState.ERROR;\n this.unlistenImage_();\n this.changed();\n }\n\n /**\n * Tracks successful image load.\n *\n * @private\n */\n handleImageLoad_() {\n if (this.resolution === undefined) {\n this.resolution = getHeight(this.extent) / this.image_.height;\n }\n this.state = ImageState.LOADED;\n this.unlistenImage_();\n this.changed();\n }\n\n /**\n * Load the image or retry if loading previously failed.\n * Loading is taken care of by the tile queue, and calling this method is\n * only needed for preloading or for reloading in case of an error.\n * @api\n */\n load() {\n if (this.state == ImageState.IDLE || this.state == ImageState.ERROR) {\n this.state = ImageState.LOADING;\n this.changed();\n this.imageLoadFunction_(this, this.src_);\n this.unlisten_ = listenImage(\n this.image_,\n this.handleImageLoad_.bind(this),\n this.handleImageError_.bind(this)\n );\n }\n }\n\n /**\n * @param {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} image Image.\n */\n setImage(image) {\n this.image_ = image;\n this.resolution = getHeight(this.extent) / this.image_.height;\n }\n\n /**\n * Discards event handlers which listen for load completion or errors.\n *\n * @private\n */\n unlistenImage_() {\n if (this.unlisten_) {\n this.unlisten_();\n this.unlisten_ = null;\n }\n }\n}\n\n/**\n * @param {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} image Image element.\n * @param {function():any} loadHandler Load callback function.\n * @param {function():any} errorHandler Error callback function.\n * @return {function():void} Callback to stop listening.\n */\nexport function listenImage(image, loadHandler, errorHandler) {\n const img = /** @type {HTMLImageElement} */ (image);\n let listening = true;\n let decoding = false;\n let loaded = false;\n\n const listenerKeys = [\n listenOnce(img, EventType.LOAD, function () {\n loaded = true;\n if (!decoding) {\n loadHandler();\n }\n }),\n ];\n\n if (img.src && IMAGE_DECODE) {\n decoding = true;\n img\n .decode()\n .then(function () {\n if (listening) {\n loadHandler();\n }\n })\n .catch(function (error) {\n if (listening) {\n if (loaded) {\n loadHandler();\n } else {\n errorHandler();\n }\n }\n });\n } else {\n listenerKeys.push(listenOnce(img, EventType.ERROR, errorHandler));\n }\n\n return function unlisten() {\n listening = false;\n listenerKeys.forEach(unlistenByKey);\n };\n}\n\nexport default ImageWrapper;\n","/**\n * @module ol/ImageCanvas\n */\nimport ImageBase from './ImageBase.js';\nimport ImageState from './ImageState.js';\n\n/**\n * A function that is called to trigger asynchronous canvas drawing. It is\n * called with a \"done\" callback that should be called when drawing is done.\n * If any error occurs during drawing, the \"done\" callback should be called with\n * that error.\n *\n * @typedef {function(function(Error=): void): void} Loader\n */\n\nclass ImageCanvas extends ImageBase {\n /**\n * @param {import(\"./extent.js\").Extent} extent Extent.\n * @param {number} resolution Resolution.\n * @param {number} pixelRatio Pixel ratio.\n * @param {HTMLCanvasElement} canvas Canvas.\n * @param {Loader} [loader] Optional loader function to\n * support asynchronous canvas drawing.\n */\n constructor(extent, resolution, pixelRatio, canvas, loader) {\n const state = loader !== undefined ? ImageState.IDLE : ImageState.LOADED;\n\n super(extent, resolution, pixelRatio, state);\n\n /**\n * Optional canvas loader function.\n * @type {?Loader}\n * @private\n */\n this.loader_ = loader !== undefined ? loader : null;\n\n /**\n * @private\n * @type {HTMLCanvasElement}\n */\n this.canvas_ = canvas;\n\n /**\n * @private\n * @type {?Error}\n */\n this.error_ = null;\n }\n\n /**\n * Get any error associated with asynchronous rendering.\n * @return {?Error} Any error that occurred during rendering.\n */\n getError() {\n return this.error_;\n }\n\n /**\n * Handle async drawing complete.\n * @param {Error} [err] Any error during drawing.\n * @private\n */\n handleLoad_(err) {\n if (err) {\n this.error_ = err;\n this.state = ImageState.ERROR;\n } else {\n this.state = ImageState.LOADED;\n }\n this.changed();\n }\n\n /**\n * Load not yet loaded URI.\n */\n load() {\n if (this.state == ImageState.IDLE) {\n this.state = ImageState.LOADING;\n this.changed();\n this.loader_(this.handleLoad_.bind(this));\n }\n }\n\n /**\n * @return {HTMLCanvasElement} Canvas element.\n */\n getImage() {\n return this.canvas_;\n }\n}\n\nexport default ImageCanvas;\n","/**\n * @module ol/ImageTile\n */\nimport Tile from './Tile.js';\nimport TileState from './TileState.js';\nimport {createCanvasContext2D} from './dom.js';\nimport {listenImage} from './Image.js';\n\nclass ImageTile extends Tile {\n /**\n * @param {import(\"./tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n * @param {import(\"./TileState.js\").default} state State.\n * @param {string} src Image source URI.\n * @param {?string} crossOrigin Cross origin.\n * @param {import(\"./Tile.js\").LoadFunction} tileLoadFunction Tile load function.\n * @param {import(\"./Tile.js\").Options} [options] Tile options.\n */\n constructor(tileCoord, state, src, crossOrigin, tileLoadFunction, options) {\n super(tileCoord, state, options);\n\n /**\n * @private\n * @type {?string}\n */\n this.crossOrigin_ = crossOrigin;\n\n /**\n * Image URI\n *\n * @private\n * @type {string}\n */\n this.src_ = src;\n\n this.key = src;\n\n /**\n * @private\n * @type {HTMLImageElement|HTMLCanvasElement}\n */\n this.image_ = new Image();\n if (crossOrigin !== null) {\n this.image_.crossOrigin = crossOrigin;\n }\n\n /**\n * @private\n * @type {?function():void}\n */\n this.unlisten_ = null;\n\n /**\n * @private\n * @type {import(\"./Tile.js\").LoadFunction}\n */\n this.tileLoadFunction_ = tileLoadFunction;\n }\n\n /**\n * Get the HTML image element for this tile (may be a Canvas, Image, or Video).\n * @return {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} Image.\n * @api\n */\n getImage() {\n return this.image_;\n }\n\n /**\n * Sets an HTML image element for this tile (may be a Canvas or preloaded Image).\n * @param {HTMLCanvasElement|HTMLImageElement} element Element.\n */\n setImage(element) {\n this.image_ = element;\n this.state = TileState.LOADED;\n this.unlistenImage_();\n this.changed();\n }\n\n /**\n * Tracks loading or read errors.\n *\n * @private\n */\n handleImageError_() {\n this.state = TileState.ERROR;\n this.unlistenImage_();\n this.image_ = getBlankImage();\n this.changed();\n }\n\n /**\n * Tracks successful image load.\n *\n * @private\n */\n handleImageLoad_() {\n const image = /** @type {HTMLImageElement} */ (this.image_);\n if (image.naturalWidth && image.naturalHeight) {\n this.state = TileState.LOADED;\n } else {\n this.state = TileState.EMPTY;\n }\n this.unlistenImage_();\n this.changed();\n }\n\n /**\n * Load the image or retry if loading previously failed.\n * Loading is taken care of by the tile queue, and calling this method is\n * only needed for preloading or for reloading in case of an error.\n *\n * To retry loading tiles on failed requests, use a custom `tileLoadFunction`\n * that checks for error status codes and reloads only when the status code is\n * 408, 429, 500, 502, 503 and 504, and only when not too many retries have been\n * made already:\n *\n * ```js\n * const retryCodes = [408, 429, 500, 502, 503, 504];\n * const retries = {};\n * source.setTileLoadFunction((tile, src) => {\n * const image = tile.getImage();\n * fetch(src)\n * .then((response) => {\n * if (retryCodes.includes(response.status)) {\n * retries[src] = (retries[src] || 0) + 1;\n * if (retries[src] <= 3) {\n * setTimeout(() => tile.load(), retries[src] * 1000);\n * }\n * return Promise.reject();\n * }\n * return response.blob();\n * })\n * .then((blob) => {\n * const imageUrl = URL.createObjectURL(blob);\n * image.src = imageUrl;\n * setTimeout(() => URL.revokeObjectURL(imageUrl), 5000);\n * })\n * .catch(() => tile.setState(3)); // error\n * });\n * ```\n *\n * @api\n */\n load() {\n if (this.state == TileState.ERROR) {\n this.state = TileState.IDLE;\n this.image_ = new Image();\n if (this.crossOrigin_ !== null) {\n this.image_.crossOrigin = this.crossOrigin_;\n }\n }\n if (this.state == TileState.IDLE) {\n this.state = TileState.LOADING;\n this.changed();\n this.tileLoadFunction_(this, this.src_);\n this.unlisten_ = listenImage(\n this.image_,\n this.handleImageLoad_.bind(this),\n this.handleImageError_.bind(this)\n );\n }\n }\n\n /**\n * Discards event handlers which listen for load completion or errors.\n *\n * @private\n */\n unlistenImage_() {\n if (this.unlisten_) {\n this.unlisten_();\n this.unlisten_ = null;\n }\n }\n}\n\n/**\n * Get a 1-pixel blank image.\n * @return {HTMLCanvasElement} Blank image.\n */\nfunction getBlankImage() {\n const ctx = createCanvasContext2D(1, 1);\n ctx.fillStyle = 'rgba(0,0,0,0)';\n ctx.fillRect(0, 0, 1, 1);\n return ctx.canvas;\n}\n\nexport default ImageTile;\n","/**\n * @module ol/Kinetic\n */\n\n/**\n * @classdesc\n * Implementation of inertial deceleration for map movement.\n *\n * @api\n */\nclass Kinetic {\n /**\n * @param {number} decay Rate of decay (must be negative).\n * @param {number} minVelocity Minimum velocity (pixels/millisecond).\n * @param {number} delay Delay to consider to calculate the kinetic\n * initial values (milliseconds).\n */\n constructor(decay, minVelocity, delay) {\n /**\n * @private\n * @type {number}\n */\n this.decay_ = decay;\n\n /**\n * @private\n * @type {number}\n */\n this.minVelocity_ = minVelocity;\n\n /**\n * @private\n * @type {number}\n */\n this.delay_ = delay;\n\n /**\n * @private\n * @type {Array}\n */\n this.points_ = [];\n\n /**\n * @private\n * @type {number}\n */\n this.angle_ = 0;\n\n /**\n * @private\n * @type {number}\n */\n this.initialVelocity_ = 0;\n }\n\n /**\n * FIXME empty description for jsdoc\n */\n begin() {\n this.points_.length = 0;\n this.angle_ = 0;\n this.initialVelocity_ = 0;\n }\n\n /**\n * @param {number} x X.\n * @param {number} y Y.\n */\n update(x, y) {\n this.points_.push(x, y, Date.now());\n }\n\n /**\n * @return {boolean} Whether we should do kinetic animation.\n */\n end() {\n if (this.points_.length < 6) {\n // at least 2 points are required (i.e. there must be at least 6 elements\n // in the array)\n return false;\n }\n const delay = Date.now() - this.delay_;\n const lastIndex = this.points_.length - 3;\n if (this.points_[lastIndex + 2] < delay) {\n // the last tracked point is too old, which means that the user stopped\n // panning before releasing the map\n return false;\n }\n\n // get the first point which still falls into the delay time\n let firstIndex = lastIndex - 3;\n while (firstIndex > 0 && this.points_[firstIndex + 2] > delay) {\n firstIndex -= 3;\n }\n\n const duration = this.points_[lastIndex + 2] - this.points_[firstIndex + 2];\n // we don't want a duration of 0 (divide by zero)\n // we also make sure the user panned for a duration of at least one frame\n // (1/60s) to compute sane displacement values\n if (duration < 1000 / 60) {\n return false;\n }\n\n const dx = this.points_[lastIndex] - this.points_[firstIndex];\n const dy = this.points_[lastIndex + 1] - this.points_[firstIndex + 1];\n this.angle_ = Math.atan2(dy, dx);\n this.initialVelocity_ = Math.sqrt(dx * dx + dy * dy) / duration;\n return this.initialVelocity_ > this.minVelocity_;\n }\n\n /**\n * @return {number} Total distance travelled (pixels).\n */\n getDistance() {\n return (this.minVelocity_ - this.initialVelocity_) / this.decay_;\n }\n\n /**\n * @return {number} Angle of the kinetic panning animation (radians).\n */\n getAngle() {\n return this.angle_;\n }\n}\n\nexport default Kinetic;\n","/**\n * @module ol/color\n */\nimport {assert} from './asserts.js';\nimport {clamp} from './math.js';\n\n/**\n * A color represented as a short array [red, green, blue, alpha].\n * red, green, and blue should be integers in the range 0..255 inclusive.\n * alpha should be a float in the range 0..1 inclusive. If no alpha value is\n * given then `1` will be used.\n * @typedef {Array} Color\n * @api\n */\n\n/**\n * This RegExp matches # followed by 3, 4, 6, or 8 hex digits.\n * @const\n * @type {RegExp}\n * @private\n */\nconst HEX_COLOR_RE_ = /^#([a-f0-9]{3}|[a-f0-9]{4}(?:[a-f0-9]{2}){0,2})$/i;\n\n/**\n * Regular expression for matching potential named color style strings.\n * @const\n * @type {RegExp}\n * @private\n */\nconst NAMED_COLOR_RE_ = /^([a-z]*)$|^hsla?\\(.*\\)$/i;\n\n/**\n * Return the color as an rgba string.\n * @param {Color|string} color Color.\n * @return {string} Rgba string.\n * @api\n */\nexport function asString(color) {\n if (typeof color === 'string') {\n return color;\n }\n return toString(color);\n}\n\n/**\n * Return named color as an rgba string.\n * @param {string} color Named color.\n * @return {string} Rgb string.\n */\nfunction fromNamed(color) {\n const el = document.createElement('div');\n el.style.color = color;\n if (el.style.color !== '') {\n document.body.appendChild(el);\n const rgb = getComputedStyle(el).color;\n document.body.removeChild(el);\n return rgb;\n }\n return '';\n}\n\n/**\n * @param {string} s String.\n * @return {Color} Color.\n */\nexport const fromString = (function () {\n // We maintain a small cache of parsed strings. To provide cheap LRU-like\n // semantics, whenever the cache grows too large we simply delete an\n // arbitrary 25% of the entries.\n\n /**\n * @const\n * @type {number}\n */\n const MAX_CACHE_SIZE = 1024;\n\n /**\n * @type {Object}\n */\n const cache = {};\n\n /**\n * @type {number}\n */\n let cacheSize = 0;\n\n return (\n /**\n * @param {string} s String.\n * @return {Color} Color.\n */\n function (s) {\n let color;\n if (cache.hasOwnProperty(s)) {\n color = cache[s];\n } else {\n if (cacheSize >= MAX_CACHE_SIZE) {\n let i = 0;\n for (const key in cache) {\n if ((i++ & 3) === 0) {\n delete cache[key];\n --cacheSize;\n }\n }\n }\n color = fromStringInternal_(s);\n cache[s] = color;\n ++cacheSize;\n }\n return color;\n }\n );\n})();\n\n/**\n * Return the color as an array. This function maintains a cache of calculated\n * arrays which means the result should not be modified.\n * @param {Color|string} color Color.\n * @return {Color} Color.\n * @api\n */\nexport function asArray(color) {\n if (Array.isArray(color)) {\n return color;\n }\n return fromString(color);\n}\n\n/**\n * @param {string} s String.\n * @private\n * @return {Color} Color.\n */\nfunction fromStringInternal_(s) {\n let r, g, b, a, color;\n\n if (NAMED_COLOR_RE_.exec(s)) {\n s = fromNamed(s);\n }\n\n if (HEX_COLOR_RE_.exec(s)) {\n // hex\n const n = s.length - 1; // number of hex digits\n let d; // number of digits per channel\n if (n <= 4) {\n d = 1;\n } else {\n d = 2;\n }\n const hasAlpha = n === 4 || n === 8;\n r = parseInt(s.substr(1 + 0 * d, d), 16);\n g = parseInt(s.substr(1 + 1 * d, d), 16);\n b = parseInt(s.substr(1 + 2 * d, d), 16);\n if (hasAlpha) {\n a = parseInt(s.substr(1 + 3 * d, d), 16);\n } else {\n a = 255;\n }\n if (d == 1) {\n r = (r << 4) + r;\n g = (g << 4) + g;\n b = (b << 4) + b;\n if (hasAlpha) {\n a = (a << 4) + a;\n }\n }\n color = [r, g, b, a / 255];\n } else if (s.startsWith('rgba(')) {\n // rgba()\n color = s.slice(5, -1).split(',').map(Number);\n normalize(color);\n } else if (s.startsWith('rgb(')) {\n // rgb()\n color = s.slice(4, -1).split(',').map(Number);\n color.push(1);\n normalize(color);\n } else {\n assert(false, 14); // Invalid color\n }\n return color;\n}\n\n/**\n * TODO this function is only used in the test, we probably shouldn't export it\n * @param {Color} color Color.\n * @return {Color} Clamped color.\n */\nexport function normalize(color) {\n color[0] = clamp((color[0] + 0.5) | 0, 0, 255);\n color[1] = clamp((color[1] + 0.5) | 0, 0, 255);\n color[2] = clamp((color[2] + 0.5) | 0, 0, 255);\n color[3] = clamp(color[3], 0, 1);\n return color;\n}\n\n/**\n * @param {Color} color Color.\n * @return {string} String.\n */\nexport function toString(color) {\n let r = color[0];\n if (r != (r | 0)) {\n r = (r + 0.5) | 0;\n }\n let g = color[1];\n if (g != (g | 0)) {\n g = (g + 0.5) | 0;\n }\n let b = color[2];\n if (b != (b | 0)) {\n b = (b + 0.5) | 0;\n }\n const a = color[3] === undefined ? 1 : Math.round(color[3] * 100) / 100;\n return 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';\n}\n\n/**\n * @param {string} s String.\n * @return {boolean} Whether the string is actually a valid color\n */\nexport function isStringColor(s) {\n if (NAMED_COLOR_RE_.test(s)) {\n s = fromNamed(s);\n }\n return HEX_COLOR_RE_.test(s) || s.startsWith('rgba(') || s.startsWith('rgb(');\n}\n","/**\n * @module ol/style/IconImageCache\n */\nimport {asString} from '../color.js';\n\n/**\n * @classdesc\n * Singleton class. Available through {@link module:ol/style/IconImageCache.shared}.\n */\nclass IconImageCache {\n constructor() {\n /**\n * @type {!Object}\n * @private\n */\n this.cache_ = {};\n\n /**\n * @type {number}\n * @private\n */\n this.cacheSize_ = 0;\n\n /**\n * @type {number}\n * @private\n */\n this.maxCacheSize_ = 32;\n }\n\n /**\n * FIXME empty description for jsdoc\n */\n clear() {\n this.cache_ = {};\n this.cacheSize_ = 0;\n }\n\n /**\n * @return {boolean} Can expire cache.\n */\n canExpireCache() {\n return this.cacheSize_ > this.maxCacheSize_;\n }\n\n /**\n * FIXME empty description for jsdoc\n */\n expire() {\n if (this.canExpireCache()) {\n let i = 0;\n for (const key in this.cache_) {\n const iconImage = this.cache_[key];\n if ((i++ & 3) === 0 && !iconImage.hasListener()) {\n delete this.cache_[key];\n --this.cacheSize_;\n }\n }\n }\n }\n\n /**\n * @param {string} src Src.\n * @param {?string} crossOrigin Cross origin.\n * @param {import(\"../color.js\").Color} color Color.\n * @return {import(\"./IconImage.js\").default} Icon image.\n */\n get(src, crossOrigin, color) {\n const key = getKey(src, crossOrigin, color);\n return key in this.cache_ ? this.cache_[key] : null;\n }\n\n /**\n * @param {string} src Src.\n * @param {?string} crossOrigin Cross origin.\n * @param {import(\"../color.js\").Color} color Color.\n * @param {import(\"./IconImage.js\").default} iconImage Icon image.\n */\n set(src, crossOrigin, color, iconImage) {\n const key = getKey(src, crossOrigin, color);\n this.cache_[key] = iconImage;\n ++this.cacheSize_;\n }\n\n /**\n * Set the cache size of the icon cache. Default is `32`. Change this value when\n * your map uses more than 32 different icon images and you are not caching icon\n * styles on the application level.\n * @param {number} maxCacheSize Cache max size.\n * @api\n */\n setSize(maxCacheSize) {\n this.maxCacheSize_ = maxCacheSize;\n this.expire();\n }\n}\n\n/**\n * @param {string} src Src.\n * @param {?string} crossOrigin Cross origin.\n * @param {import(\"../color.js\").Color} color Color.\n * @return {string} Cache key.\n */\nfunction getKey(src, crossOrigin, color) {\n const colorString = color ? asString(color) : 'null';\n return crossOrigin + ':' + src + ':' + colorString;\n}\n\nexport default IconImageCache;\n\n/**\n * The {@link module:ol/style/IconImageCache~IconImageCache} for\n * {@link module:ol/style/Icon~Icon} images.\n * @api\n */\nexport const shared = new IconImageCache();\n","/**\n * @module ol/layer/Property\n */\n\n/**\n * @enum {string}\n */\nexport default {\n OPACITY: 'opacity',\n VISIBLE: 'visible',\n EXTENT: 'extent',\n Z_INDEX: 'zIndex',\n MAX_RESOLUTION: 'maxResolution',\n MIN_RESOLUTION: 'minResolution',\n MAX_ZOOM: 'maxZoom',\n MIN_ZOOM: 'minZoom',\n SOURCE: 'source',\n MAP: 'map',\n};\n","/**\n * @module ol/layer/Base\n */\nimport BaseObject from '../Object.js';\nimport LayerProperty from './Property.js';\nimport {abstract} from '../util.js';\nimport {assert} from '../asserts.js';\nimport {clamp} from '../math.js';\n\n/**\n * A css color, or a function called with a view resolution returning a css color.\n *\n * @typedef {string|function(number):string} BackgroundColor\n * @api\n */\n\n/**\n * @typedef {import(\"../ObjectEventType\").Types|'change:extent'|'change:maxResolution'|'change:maxZoom'|\n * 'change:minResolution'|'change:minZoom'|'change:opacity'|'change:visible'|'change:zIndex'} BaseLayerObjectEventTypes\n */\n\n/***\n * @template Return\n * @typedef {import(\"../Observable\").OnSignature &\n * import(\"../Observable\").OnSignature &\n * import(\"../Observable\").CombinedOnSignature} BaseLayerOnSignature\n */\n\n/**\n * @typedef {Object} Options\n * @property {string} [className='ol-layer'] A CSS class name to set to the layer element.\n * @property {number} [opacity=1] Opacity (0, 1).\n * @property {boolean} [visible=true] Visibility.\n * @property {import(\"../extent.js\").Extent} [extent] The bounding extent for layer rendering. The layer will not be\n * rendered outside of this extent.\n * @property {number} [zIndex] The z-index for layer rendering. At rendering time, the layers\n * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed\n * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`\n * method was used.\n * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be\n * visible.\n * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will\n * be visible.\n * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be\n * visible.\n * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will\n * be visible.\n * @property {BackgroundColor} [background] Background color for the layer. If not specified, no background\n * will be rendered.\n * @property {Object} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.\n */\n\n/**\n * @classdesc\n * Abstract base class; normally only used for creating subclasses and not\n * instantiated in apps.\n * Note that with {@link module:ol/layer/Base~BaseLayer} and all its subclasses, any property set in\n * the options is set as a {@link module:ol/Object~BaseObject} property on the layer object, so\n * is observable, and has get/set accessors.\n *\n * @api\n */\nclass BaseLayer extends BaseObject {\n /**\n * @param {Options} options Layer options.\n */\n constructor(options) {\n super();\n\n /***\n * @type {BaseLayerOnSignature}\n */\n this.on;\n\n /***\n * @type {BaseLayerOnSignature}\n */\n this.once;\n\n /***\n * @type {BaseLayerOnSignature}\n */\n this.un;\n\n /**\n * @type {BackgroundColor|false}\n * @private\n */\n this.background_ = options.background;\n\n /**\n * @type {Object}\n */\n const properties = Object.assign({}, options);\n if (typeof options.properties === 'object') {\n delete properties.properties;\n Object.assign(properties, options.properties);\n }\n\n properties[LayerProperty.OPACITY] =\n options.opacity !== undefined ? options.opacity : 1;\n assert(typeof properties[LayerProperty.OPACITY] === 'number', 64); // Layer opacity must be a number\n\n properties[LayerProperty.VISIBLE] =\n options.visible !== undefined ? options.visible : true;\n properties[LayerProperty.Z_INDEX] = options.zIndex;\n properties[LayerProperty.MAX_RESOLUTION] =\n options.maxResolution !== undefined ? options.maxResolution : Infinity;\n properties[LayerProperty.MIN_RESOLUTION] =\n options.minResolution !== undefined ? options.minResolution : 0;\n properties[LayerProperty.MIN_ZOOM] =\n options.minZoom !== undefined ? options.minZoom : -Infinity;\n properties[LayerProperty.MAX_ZOOM] =\n options.maxZoom !== undefined ? options.maxZoom : Infinity;\n\n /**\n * @type {string}\n * @private\n */\n this.className_ =\n properties.className !== undefined ? properties.className : 'ol-layer';\n delete properties.className;\n\n this.setProperties(properties);\n\n /**\n * @type {import(\"./Layer.js\").State}\n * @private\n */\n this.state_ = null;\n }\n\n /**\n * Get the background for this layer.\n * @return {BackgroundColor|false} Layer background.\n */\n getBackground() {\n return this.background_;\n }\n\n /**\n * @return {string} CSS class name.\n */\n getClassName() {\n return this.className_;\n }\n\n /**\n * This method is not meant to be called by layers or layer renderers because the state\n * is incorrect if the layer is included in a layer group.\n *\n * @param {boolean} [managed] Layer is managed.\n * @return {import(\"./Layer.js\").State} Layer state.\n */\n getLayerState(managed) {\n /** @type {import(\"./Layer.js\").State} */\n const state =\n this.state_ ||\n /** @type {?} */ ({\n layer: this,\n managed: managed === undefined ? true : managed,\n });\n const zIndex = this.getZIndex();\n state.opacity = clamp(Math.round(this.getOpacity() * 100) / 100, 0, 1);\n state.visible = this.getVisible();\n state.extent = this.getExtent();\n state.zIndex = zIndex === undefined && !state.managed ? Infinity : zIndex;\n state.maxResolution = this.getMaxResolution();\n state.minResolution = Math.max(this.getMinResolution(), 0);\n state.minZoom = this.getMinZoom();\n state.maxZoom = this.getMaxZoom();\n this.state_ = state;\n\n return state;\n }\n\n /**\n * @abstract\n * @param {Array} [array] Array of layers (to be\n * modified in place).\n * @return {Array} Array of layers.\n */\n getLayersArray(array) {\n return abstract();\n }\n\n /**\n * @abstract\n * @param {Array} [states] Optional list of layer\n * states (to be modified in place).\n * @return {Array} List of layer states.\n */\n getLayerStatesArray(states) {\n return abstract();\n }\n\n /**\n * Return the {@link module:ol/extent~Extent extent} of the layer or `undefined` if it\n * will be visible regardless of extent.\n * @return {import(\"../extent.js\").Extent|undefined} The layer extent.\n * @observable\n * @api\n */\n getExtent() {\n return /** @type {import(\"../extent.js\").Extent|undefined} */ (\n this.get(LayerProperty.EXTENT)\n );\n }\n\n /**\n * Return the maximum resolution of the layer.\n * @return {number} The maximum resolution of the layer.\n * @observable\n * @api\n */\n getMaxResolution() {\n return /** @type {number} */ (this.get(LayerProperty.MAX_RESOLUTION));\n }\n\n /**\n * Return the minimum resolution of the layer.\n * @return {number} The minimum resolution of the layer.\n * @observable\n * @api\n */\n getMinResolution() {\n return /** @type {number} */ (this.get(LayerProperty.MIN_RESOLUTION));\n }\n\n /**\n * Return the minimum zoom level of the layer.\n * @return {number} The minimum zoom level of the layer.\n * @observable\n * @api\n */\n getMinZoom() {\n return /** @type {number} */ (this.get(LayerProperty.MIN_ZOOM));\n }\n\n /**\n * Return the maximum zoom level of the layer.\n * @return {number} The maximum zoom level of the layer.\n * @observable\n * @api\n */\n getMaxZoom() {\n return /** @type {number} */ (this.get(LayerProperty.MAX_ZOOM));\n }\n\n /**\n * Return the opacity of the layer (between 0 and 1).\n * @return {number} The opacity of the layer.\n * @observable\n * @api\n */\n getOpacity() {\n return /** @type {number} */ (this.get(LayerProperty.OPACITY));\n }\n\n /**\n * @abstract\n * @return {import(\"../source/Source.js\").State} Source state.\n */\n getSourceState() {\n return abstract();\n }\n\n /**\n * Return the value of this layer's `visible` property. To find out whether the layer\n * is visible on a map, use `isVisible()` instead.\n * @return {boolean} The value of the `visible` property of the layer.\n * @observable\n * @api\n */\n getVisible() {\n return /** @type {boolean} */ (this.get(LayerProperty.VISIBLE));\n }\n\n /**\n * Return the Z-index of the layer, which is used to order layers before\n * rendering. The default Z-index is 0.\n * @return {number} The Z-index of the layer.\n * @observable\n * @api\n */\n getZIndex() {\n return /** @type {number} */ (this.get(LayerProperty.Z_INDEX));\n }\n\n /**\n * Sets the background color.\n * @param {BackgroundColor} [background] Background color.\n */\n setBackground(background) {\n this.background_ = background;\n this.changed();\n }\n\n /**\n * Set the extent at which the layer is visible. If `undefined`, the layer\n * will be visible at all extents.\n * @param {import(\"../extent.js\").Extent|undefined} extent The extent of the layer.\n * @observable\n * @api\n */\n setExtent(extent) {\n this.set(LayerProperty.EXTENT, extent);\n }\n\n /**\n * Set the maximum resolution at which the layer is visible.\n * @param {number} maxResolution The maximum resolution of the layer.\n * @observable\n * @api\n */\n setMaxResolution(maxResolution) {\n this.set(LayerProperty.MAX_RESOLUTION, maxResolution);\n }\n\n /**\n * Set the minimum resolution at which the layer is visible.\n * @param {number} minResolution The minimum resolution of the layer.\n * @observable\n * @api\n */\n setMinResolution(minResolution) {\n this.set(LayerProperty.MIN_RESOLUTION, minResolution);\n }\n\n /**\n * Set the maximum zoom (exclusive) at which the layer is visible.\n * Note that the zoom levels for layer visibility are based on the\n * view zoom level, which may be different from a tile source zoom level.\n * @param {number} maxZoom The maximum zoom of the layer.\n * @observable\n * @api\n */\n setMaxZoom(maxZoom) {\n this.set(LayerProperty.MAX_ZOOM, maxZoom);\n }\n\n /**\n * Set the minimum zoom (inclusive) at which the layer is visible.\n * Note that the zoom levels for layer visibility are based on the\n * view zoom level, which may be different from a tile source zoom level.\n * @param {number} minZoom The minimum zoom of the layer.\n * @observable\n * @api\n */\n setMinZoom(minZoom) {\n this.set(LayerProperty.MIN_ZOOM, minZoom);\n }\n\n /**\n * Set the opacity of the layer, allowed values range from 0 to 1.\n * @param {number} opacity The opacity of the layer.\n * @observable\n * @api\n */\n setOpacity(opacity) {\n assert(typeof opacity === 'number', 64); // Layer opacity must be a number\n this.set(LayerProperty.OPACITY, opacity);\n }\n\n /**\n * Set the visibility of the layer (`true` or `false`).\n * @param {boolean} visible The visibility of the layer.\n * @observable\n * @api\n */\n setVisible(visible) {\n this.set(LayerProperty.VISIBLE, visible);\n }\n\n /**\n * Set Z-index of the layer, which is used to order layers before rendering.\n * The default Z-index is 0.\n * @param {number} zindex The z-index of the layer.\n * @observable\n * @api\n */\n setZIndex(zindex) {\n this.set(LayerProperty.Z_INDEX, zindex);\n }\n\n /**\n * Clean up.\n */\n disposeInternal() {\n if (this.state_) {\n this.state_.layer = null;\n this.state_ = null;\n }\n super.disposeInternal();\n }\n}\n\nexport default BaseLayer;\n","/**\n * @module ol/render/EventType\n */\n\n/**\n * @enum {string}\n */\nexport default {\n /**\n * Triggered before a layer is rendered.\n * @event module:ol/render/Event~RenderEvent#prerender\n * @api\n */\n PRERENDER: 'prerender',\n\n /**\n * Triggered after a layer is rendered.\n * @event module:ol/render/Event~RenderEvent#postrender\n * @api\n */\n POSTRENDER: 'postrender',\n\n /**\n * Triggered before layers are composed. When dispatched by the map, the event object will not have\n * a `context` set. When dispatched by a layer, the event object will have a `context` set. Only\n * WebGL layers currently dispatch this event.\n * @event module:ol/render/Event~RenderEvent#precompose\n * @api\n */\n PRECOMPOSE: 'precompose',\n\n /**\n * Triggered after layers are composed. When dispatched by the map, the event object will not have\n * a `context` set. When dispatched by a layer, the event object will have a `context` set. Only\n * WebGL layers currently dispatch this event.\n * @event module:ol/render/Event~RenderEvent#postcompose\n * @api\n */\n POSTCOMPOSE: 'postcompose',\n\n /**\n * Triggered when rendering is complete, i.e. all sources and tiles have\n * finished loading for the current viewport, and all tiles are faded in.\n * The event object will not have a `context` set.\n * @event module:ol/render/Event~RenderEvent#rendercomplete\n * @api\n */\n RENDERCOMPLETE: 'rendercomplete',\n};\n\n/**\n * @typedef {'postrender'|'precompose'|'postcompose'|'rendercomplete'} MapRenderEventTypes\n */\n\n/**\n * @typedef {'postrender'|'prerender'} LayerRenderEventTypes\n */\n","/**\n * @module ol/ViewHint\n */\n\n/**\n * @enum {number}\n */\nexport default {\n ANIMATING: 0,\n INTERACTING: 1,\n};\n","/**\n * @module ol/ViewProperty\n */\n\n/**\n * @enum {string}\n */\nexport default {\n CENTER: 'center',\n RESOLUTION: 'resolution',\n ROTATION: 'rotation',\n};\n","/**\n * @module ol/tilegrid/common\n */\n\n/**\n * Default maximum zoom for default tile grids.\n * @type {number}\n */\nexport const DEFAULT_MAX_ZOOM = 42;\n\n/**\n * Default tile size.\n * @type {number}\n */\nexport const DEFAULT_TILE_SIZE = 256;\n","/**\n * @module ol/centerconstraint\n */\nimport {clamp} from './math.js';\n\n/**\n * @typedef {function((import(\"./coordinate.js\").Coordinate|undefined), number, import(\"./size.js\").Size, boolean=, Array=): (import(\"./coordinate.js\").Coordinate|undefined)} Type\n */\n\n/**\n * @param {import(\"./extent.js\").Extent} extent Extent.\n * @param {boolean} onlyCenter If true, the constraint will only apply to the view center.\n * @param {boolean} smooth If true, the view will be able to go slightly out of the given extent\n * (only during interaction and animation).\n * @return {Type} The constraint.\n */\nexport function createExtent(extent, onlyCenter, smooth) {\n return (\n /**\n * @param {import(\"./coordinate.js\").Coordinate|undefined} center Center.\n * @param {number|undefined} resolution Resolution.\n * @param {import(\"./size.js\").Size} size Viewport size; unused if `onlyCenter` was specified.\n * @param {boolean} [isMoving] True if an interaction or animation is in progress.\n * @param {Array} [centerShift] Shift between map center and viewport center.\n * @return {import(\"./coordinate.js\").Coordinate|undefined} Center.\n */\n function (center, resolution, size, isMoving, centerShift) {\n if (!center) {\n return undefined;\n }\n if (!resolution && !onlyCenter) {\n return center;\n }\n const viewWidth = onlyCenter ? 0 : size[0] * resolution;\n const viewHeight = onlyCenter ? 0 : size[1] * resolution;\n const shiftX = centerShift ? centerShift[0] : 0;\n const shiftY = centerShift ? centerShift[1] : 0;\n let minX = extent[0] + viewWidth / 2 + shiftX;\n let maxX = extent[2] - viewWidth / 2 + shiftX;\n let minY = extent[1] + viewHeight / 2 + shiftY;\n let maxY = extent[3] - viewHeight / 2 + shiftY;\n\n // note: when zooming out of bounds, min and max values for x and y may\n // end up inverted (min > max); this has to be accounted for\n if (minX > maxX) {\n minX = (maxX + minX) / 2;\n maxX = minX;\n }\n if (minY > maxY) {\n minY = (maxY + minY) / 2;\n maxY = minY;\n }\n\n let x = clamp(center[0], minX, maxX);\n let y = clamp(center[1], minY, maxY);\n\n // during an interaction, allow some overscroll\n if (isMoving && smooth && resolution) {\n const ratio = 30 * resolution;\n x +=\n -ratio * Math.log(1 + Math.max(0, minX - center[0]) / ratio) +\n ratio * Math.log(1 + Math.max(0, center[0] - maxX) / ratio);\n y +=\n -ratio * Math.log(1 + Math.max(0, minY - center[1]) / ratio) +\n ratio * Math.log(1 + Math.max(0, center[1] - maxY) / ratio);\n }\n\n return [x, y];\n }\n );\n}\n\n/**\n * @param {import(\"./coordinate.js\").Coordinate} [center] Center.\n * @return {import(\"./coordinate.js\").Coordinate|undefined} Center.\n */\nexport function none(center) {\n return center;\n}\n","/**\n * @module ol/resolutionconstraint\n */\nimport {clamp} from './math.js';\nimport {getHeight, getWidth} from './extent.js';\nimport {linearFindNearest} from './array.js';\n\n/**\n * @typedef {function((number|undefined), number, import(\"./size.js\").Size, boolean=): (number|undefined)} Type\n */\n\n/**\n * Returns a modified resolution taking into account the viewport size and maximum\n * allowed extent.\n * @param {number} resolution Resolution\n * @param {import(\"./extent.js\").Extent} maxExtent Maximum allowed extent.\n * @param {import(\"./size.js\").Size} viewportSize Viewport size.\n * @param {boolean} showFullExtent Whether to show the full extent.\n * @return {number} Capped resolution.\n */\nfunction getViewportClampedResolution(\n resolution,\n maxExtent,\n viewportSize,\n showFullExtent\n) {\n const xResolution = getWidth(maxExtent) / viewportSize[0];\n const yResolution = getHeight(maxExtent) / viewportSize[1];\n\n if (showFullExtent) {\n return Math.min(resolution, Math.max(xResolution, yResolution));\n }\n return Math.min(resolution, Math.min(xResolution, yResolution));\n}\n\n/**\n * Returns a modified resolution to be between maxResolution and minResolution while\n * still allowing the value to be slightly out of bounds.\n * Note: the computation is based on the logarithm function (ln):\n * - at 1, ln(x) is 0\n * - above 1, ln(x) keeps increasing but at a much slower pace than x\n * The final result is clamped to prevent getting too far away from bounds.\n * @param {number} resolution Resolution.\n * @param {number} maxResolution Max resolution.\n * @param {number} minResolution Min resolution.\n * @return {number} Smoothed resolution.\n */\nfunction getSmoothClampedResolution(resolution, maxResolution, minResolution) {\n let result = Math.min(resolution, maxResolution);\n const ratio = 50;\n\n result *=\n Math.log(1 + ratio * Math.max(0, resolution / maxResolution - 1)) / ratio +\n 1;\n if (minResolution) {\n result = Math.max(result, minResolution);\n result /=\n Math.log(1 + ratio * Math.max(0, minResolution / resolution - 1)) /\n ratio +\n 1;\n }\n return clamp(result, minResolution / 2, maxResolution * 2);\n}\n\n/**\n * @param {Array} resolutions Resolutions.\n * @param {boolean} [smooth] If true, the view will be able to slightly exceed resolution limits. Default: true.\n * @param {import(\"./extent.js\").Extent} [maxExtent] Maximum allowed extent.\n * @param {boolean} [showFullExtent] If true, allows us to show the full extent. Default: false.\n * @return {Type} Zoom function.\n */\nexport function createSnapToResolutions(\n resolutions,\n smooth,\n maxExtent,\n showFullExtent\n) {\n smooth = smooth !== undefined ? smooth : true;\n return (\n /**\n * @param {number|undefined} resolution Resolution.\n * @param {number} direction Direction.\n * @param {import(\"./size.js\").Size} size Viewport size.\n * @param {boolean} [isMoving] True if an interaction or animation is in progress.\n * @return {number|undefined} Resolution.\n */\n function (resolution, direction, size, isMoving) {\n if (resolution !== undefined) {\n const maxResolution = resolutions[0];\n const minResolution = resolutions[resolutions.length - 1];\n const cappedMaxRes = maxExtent\n ? getViewportClampedResolution(\n maxResolution,\n maxExtent,\n size,\n showFullExtent\n )\n : maxResolution;\n\n // during interacting or animating, allow intermediary values\n if (isMoving) {\n if (!smooth) {\n return clamp(resolution, minResolution, cappedMaxRes);\n }\n return getSmoothClampedResolution(\n resolution,\n cappedMaxRes,\n minResolution\n );\n }\n\n const capped = Math.min(cappedMaxRes, resolution);\n const z = Math.floor(linearFindNearest(resolutions, capped, direction));\n if (resolutions[z] > cappedMaxRes && z < resolutions.length - 1) {\n return resolutions[z + 1];\n }\n return resolutions[z];\n }\n return undefined;\n }\n );\n}\n\n/**\n * @param {number} power Power.\n * @param {number} maxResolution Maximum resolution.\n * @param {number} [minResolution] Minimum resolution.\n * @param {boolean} [smooth] If true, the view will be able to slightly exceed resolution limits. Default: true.\n * @param {import(\"./extent.js\").Extent} [maxExtent] Maximum allowed extent.\n * @param {boolean} [showFullExtent] If true, allows us to show the full extent. Default: false.\n * @return {Type} Zoom function.\n */\nexport function createSnapToPower(\n power,\n maxResolution,\n minResolution,\n smooth,\n maxExtent,\n showFullExtent\n) {\n smooth = smooth !== undefined ? smooth : true;\n minResolution = minResolution !== undefined ? minResolution : 0;\n\n return (\n /**\n * @param {number|undefined} resolution Resolution.\n * @param {number} direction Direction.\n * @param {import(\"./size.js\").Size} size Viewport size.\n * @param {boolean} [isMoving] True if an interaction or animation is in progress.\n * @return {number|undefined} Resolution.\n */\n function (resolution, direction, size, isMoving) {\n if (resolution !== undefined) {\n const cappedMaxRes = maxExtent\n ? getViewportClampedResolution(\n maxResolution,\n maxExtent,\n size,\n showFullExtent\n )\n : maxResolution;\n\n // during interacting or animating, allow intermediary values\n if (isMoving) {\n if (!smooth) {\n return clamp(resolution, minResolution, cappedMaxRes);\n }\n return getSmoothClampedResolution(\n resolution,\n cappedMaxRes,\n minResolution\n );\n }\n\n const tolerance = 1e-9;\n const minZoomLevel = Math.ceil(\n Math.log(maxResolution / cappedMaxRes) / Math.log(power) - tolerance\n );\n const offset = -direction * (0.5 - tolerance) + 0.5;\n const capped = Math.min(cappedMaxRes, resolution);\n const cappedZoomLevel = Math.floor(\n Math.log(maxResolution / capped) / Math.log(power) + offset\n );\n const zoomLevel = Math.max(minZoomLevel, cappedZoomLevel);\n const newResolution = maxResolution / Math.pow(power, zoomLevel);\n return clamp(newResolution, minResolution, cappedMaxRes);\n }\n return undefined;\n }\n );\n}\n\n/**\n * @param {number} maxResolution Max resolution.\n * @param {number} minResolution Min resolution.\n * @param {boolean} [smooth] If true, the view will be able to slightly exceed resolution limits. Default: true.\n * @param {import(\"./extent.js\").Extent} [maxExtent] Maximum allowed extent.\n * @param {boolean} [showFullExtent] If true, allows us to show the full extent. Default: false.\n * @return {Type} Zoom function.\n */\nexport function createMinMaxResolution(\n maxResolution,\n minResolution,\n smooth,\n maxExtent,\n showFullExtent\n) {\n smooth = smooth !== undefined ? smooth : true;\n\n return (\n /**\n * @param {number|undefined} resolution Resolution.\n * @param {number} direction Direction.\n * @param {import(\"./size.js\").Size} size Viewport size.\n * @param {boolean} [isMoving] True if an interaction or animation is in progress.\n * @return {number|undefined} Resolution.\n */\n function (resolution, direction, size, isMoving) {\n if (resolution !== undefined) {\n const cappedMaxRes = maxExtent\n ? getViewportClampedResolution(\n maxResolution,\n maxExtent,\n size,\n showFullExtent\n )\n : maxResolution;\n\n if (!smooth || !isMoving) {\n return clamp(resolution, minResolution, cappedMaxRes);\n }\n return getSmoothClampedResolution(\n resolution,\n cappedMaxRes,\n minResolution\n );\n }\n return undefined;\n }\n );\n}\n","/**\n * @module ol/rotationconstraint\n */\nimport {toRadians} from './math.js';\n\n/**\n * @typedef {function((number|undefined), boolean=): (number|undefined)} Type\n */\n\n/**\n * @param {number|undefined} rotation Rotation.\n * @return {number|undefined} Rotation.\n */\nexport function disable(rotation) {\n if (rotation !== undefined) {\n return 0;\n }\n return undefined;\n}\n\n/**\n * @param {number|undefined} rotation Rotation.\n * @return {number|undefined} Rotation.\n */\nexport function none(rotation) {\n if (rotation !== undefined) {\n return rotation;\n }\n return undefined;\n}\n\n/**\n * @param {number} n N.\n * @return {Type} Rotation constraint.\n */\nexport function createSnapToN(n) {\n const theta = (2 * Math.PI) / n;\n return (\n /**\n * @param {number|undefined} rotation Rotation.\n * @param {boolean} [isMoving] True if an interaction or animation is in progress.\n * @return {number|undefined} Rotation.\n */\n function (rotation, isMoving) {\n if (isMoving) {\n return rotation;\n }\n\n if (rotation !== undefined) {\n rotation = Math.floor(rotation / theta + 0.5) * theta;\n return rotation;\n }\n return undefined;\n }\n );\n}\n\n/**\n * @param {number} [tolerance] Tolerance.\n * @return {Type} Rotation constraint.\n */\nexport function createSnapToZero(tolerance) {\n tolerance = tolerance || toRadians(5);\n return (\n /**\n * @param {number|undefined} rotation Rotation.\n * @param {boolean} [isMoving] True if an interaction or animation is in progress.\n * @return {number|undefined} Rotation.\n */\n function (rotation, isMoving) {\n if (isMoving) {\n return rotation;\n }\n\n if (rotation !== undefined) {\n if (Math.abs(rotation) <= tolerance) {\n return 0;\n }\n return rotation;\n }\n return undefined;\n }\n );\n}\n","/**\n * @module ol/View\n */\nimport BaseObject from './Object.js';\nimport ViewHint from './ViewHint.js';\nimport ViewProperty from './ViewProperty.js';\nimport {DEFAULT_TILE_SIZE} from './tilegrid/common.js';\nimport {\n METERS_PER_UNIT,\n createProjection,\n disableCoordinateWarning,\n fromUserCoordinate,\n fromUserExtent,\n getUserProjection,\n toUserCoordinate,\n toUserExtent,\n} from './proj.js';\nimport {VOID} from './functions.js';\nimport {\n add as addCoordinate,\n equals as coordinatesEqual,\n equals,\n rotate as rotateCoordinate,\n} from './coordinate.js';\nimport {assert} from './asserts.js';\nimport {none as centerNone, createExtent} from './centerconstraint.js';\nimport {clamp, modulo} from './math.js';\nimport {\n createMinMaxResolution,\n createSnapToPower,\n createSnapToResolutions,\n} from './resolutionconstraint.js';\nimport {\n createSnapToN,\n createSnapToZero,\n disable,\n none as rotationNone,\n} from './rotationconstraint.js';\nimport {easeOut, inAndOut} from './easing.js';\nimport {\n getCenter,\n getForViewAndSize,\n getHeight,\n getWidth,\n isEmpty,\n} from './extent.js';\nimport {linearFindNearest} from './array.js';\nimport {fromExtent as polygonFromExtent} from './geom/Polygon.js';\n\n/**\n * An animation configuration\n *\n * @typedef {Object} Animation\n * @property {import(\"./coordinate.js\").Coordinate} [sourceCenter] Source center.\n * @property {import(\"./coordinate.js\").Coordinate} [targetCenter] Target center.\n * @property {number} [sourceResolution] Source resolution.\n * @property {number} [targetResolution] Target resolution.\n * @property {number} [sourceRotation] Source rotation.\n * @property {number} [targetRotation] Target rotation.\n * @property {import(\"./coordinate.js\").Coordinate} [anchor] Anchor.\n * @property {number} start Start.\n * @property {number} duration Duration.\n * @property {boolean} complete Complete.\n * @property {function(number):number} easing Easing.\n * @property {function(boolean):void} callback Callback.\n */\n\n/**\n * @typedef {Object} Constraints\n * @property {import(\"./centerconstraint.js\").Type} center Center.\n * @property {import(\"./resolutionconstraint.js\").Type} resolution Resolution.\n * @property {import(\"./rotationconstraint.js\").Type} rotation Rotation.\n */\n\n/**\n * @typedef {Object} FitOptions\n * @property {import(\"./size.js\").Size} [size] The size in pixels of the box to fit\n * the extent into. Default is the current size of the first map in the DOM that\n * uses this view, or `[100, 100]` if no such map is found.\n * @property {!Array} [padding=[0, 0, 0, 0]] Padding (in pixels) to be\n * cleared inside the view. Values in the array are top, right, bottom and left\n * padding.\n * @property {boolean} [nearest=false] If the view `constrainResolution` option is `true`,\n * get the nearest extent instead of the closest that actually fits the view.\n * @property {number} [minResolution=0] Minimum resolution that we zoom to.\n * @property {number} [maxZoom] Maximum zoom level that we zoom to. If\n * `minResolution` is given, this property is ignored.\n * @property {number} [duration] The duration of the animation in milliseconds.\n * By default, there is no animation to the target extent.\n * @property {function(number):number} [easing] The easing function used during\n * the animation (defaults to {@link module:ol/easing.inAndOut}).\n * The function will be called for each frame with a number representing a\n * fraction of the animation's duration. The function should return a number\n * between 0 and 1 representing the progress toward the destination state.\n * @property {function(boolean):void} [callback] Function called when the view is in\n * its final position. The callback will be called with `true` if the animation\n * series completed on its own or `false` if it was cancelled.\n */\n\n/**\n * @typedef {Object} ViewOptions\n * @property {import(\"./coordinate.js\").Coordinate} [center] The initial center for\n * the view. If a user projection is not set, the coordinate system for the center is\n * specified with the `projection` option. Layer sources will not be fetched if this\n * is not set, but the center can be set later with {@link #setCenter}.\n * @property {boolean|number} [constrainRotation=true] Rotation constraint.\n * `false` means no constraint. `true` means no constraint, but snap to zero\n * near zero. A number constrains the rotation to that number of values. For\n * example, `4` will constrain the rotation to 0, 90, 180, and 270 degrees.\n * @property {boolean} [enableRotation=true] Enable rotation.\n * If `false`, a rotation constraint that always sets the rotation to zero is\n * used. The `constrainRotation` option has no effect if `enableRotation` is\n * `false`.\n * @property {import(\"./extent.js\").Extent} [extent] The extent that constrains the\n * view, in other words, nothing outside of this extent can be visible on the map.\n * @property {boolean} [constrainOnlyCenter=false] If true, the extent\n * constraint will only apply to the view center and not the whole extent.\n * @property {boolean} [smoothExtentConstraint=true] If true, the extent\n * constraint will be applied smoothly, i.e. allow the view to go slightly outside\n * of the given `extent`.\n * @property {number} [maxResolution] The maximum resolution used to determine\n * the resolution constraint. It is used together with `minResolution` (or\n * `maxZoom`) and `zoomFactor`. If unspecified it is calculated in such a way\n * that the projection's validity extent fits in a 256x256 px tile. If the\n * projection is Spherical Mercator (the default) then `maxResolution` defaults\n * to `40075016.68557849 / 256 = 156543.03392804097`.\n * @property {number} [minResolution] The minimum resolution used to determine\n * the resolution constraint. It is used together with `maxResolution` (or\n * `minZoom`) and `zoomFactor`. If unspecified it is calculated assuming 29\n * zoom levels (with a factor of 2). If the projection is Spherical Mercator\n * (the default) then `minResolution` defaults to\n * `40075016.68557849 / 256 / Math.pow(2, 28) = 0.0005831682455839253`.\n * @property {number} [maxZoom=28] The maximum zoom level used to determine the\n * resolution constraint. It is used together with `minZoom` (or\n * `maxResolution`) and `zoomFactor`. Note that if `minResolution` is also\n * provided, it is given precedence over `maxZoom`.\n * @property {number} [minZoom=0] The minimum zoom level used to determine the\n * resolution constraint. It is used together with `maxZoom` (or\n * `minResolution`) and `zoomFactor`. Note that if `maxResolution` is also\n * provided, it is given precedence over `minZoom`.\n * @property {boolean} [multiWorld=false] If `false` the view is constrained so\n * only one world is visible, and you cannot pan off the edge. If `true` the map\n * may show multiple worlds at low zoom levels. Only used if the `projection` is\n * global. Note that if `extent` is also provided it is given precedence.\n * @property {boolean} [constrainResolution=false] If true, the view will always\n * animate to the closest zoom level after an interaction; false means\n * intermediary zoom levels are allowed.\n * @property {boolean} [smoothResolutionConstraint=true] If true, the resolution\n * min/max values will be applied smoothly, i. e. allow the view to exceed slightly\n * the given resolution or zoom bounds.\n * @property {boolean} [showFullExtent=false] Allow the view to be zoomed out to\n * show the full configured extent. By default, when a view is configured with an\n * extent, users will not be able to zoom out so the viewport exceeds the extent in\n * either dimension. This means the full extent may not be visible if the viewport\n * is taller or wider than the aspect ratio of the configured extent. If\n * showFullExtent is true, the user will be able to zoom out so that the viewport\n * exceeds the height or width of the configured extent, but not both, allowing the\n * full extent to be shown.\n * @property {import(\"./proj.js\").ProjectionLike} [projection='EPSG:3857'] The\n * projection. The default is Spherical Mercator.\n * @property {number} [resolution] The initial resolution for the view. The\n * units are `projection` units per pixel (e.g. meters per pixel). An\n * alternative to setting this is to set `zoom`. Layer sources will not be\n * fetched if neither this nor `zoom` are defined, but they can be set later\n * with {@link #setZoom} or {@link #setResolution}.\n * @property {Array} [resolutions] Resolutions that determine the\n * zoom levels if specified. The index in the array corresponds to the zoom level,\n * therefore the resolution values have to be in descending order. It also constrains\n * the resolution by the minimum and maximum value. If set the `maxResolution`,\n * `minResolution`, `minZoom`, `maxZoom`, and `zoomFactor` options are ignored.\n * @property {number} [rotation=0] The initial rotation for the view in radians\n * (positive rotation clockwise, 0 means North).\n * @property {number} [zoom] Only used if `resolution` is not defined. Zoom\n * level used to calculate the initial resolution for the view.\n * @property {number} [zoomFactor=2] The zoom factor used to compute the\n * corresponding resolution.\n * @property {!Array} [padding=[0, 0, 0, 0]] Padding (in css pixels).\n * If the map viewport is partially covered with other content (overlays) along\n * its edges, this setting allows to shift the center of the viewport away from\n * that content. The order of the values is top, right, bottom, left.\n */\n\n/**\n * @typedef {Object} AnimationOptions\n * @property {import(\"./coordinate.js\").Coordinate} [center] The center of the view at the end of\n * the animation.\n * @property {number} [zoom] The zoom level of the view at the end of the\n * animation. This takes precedence over `resolution`.\n * @property {number} [resolution] The resolution of the view at the end\n * of the animation. If `zoom` is also provided, this option will be ignored.\n * @property {number} [rotation] The rotation of the view at the end of\n * the animation.\n * @property {import(\"./coordinate.js\").Coordinate} [anchor] Optional anchor to remain fixed\n * during a rotation or resolution animation.\n * @property {number} [duration=1000] The duration of the animation in milliseconds.\n * @property {function(number):number} [easing] The easing function used\n * during the animation (defaults to {@link module:ol/easing.inAndOut}).\n * The function will be called for each frame with a number representing a\n * fraction of the animation's duration. The function should return a number\n * between 0 and 1 representing the progress toward the destination state.\n */\n\n/**\n * @typedef {Object} State\n * @property {import(\"./coordinate.js\").Coordinate} center Center (in view projection coordinates).\n * @property {import(\"./proj/Projection.js\").default} projection Projection.\n * @property {number} resolution Resolution.\n * @property {import(\"./coordinate.js\").Coordinate} [nextCenter] The next center during an animation series.\n * @property {number} [nextResolution] The next resolution during an animation series.\n * @property {number} [nextRotation] The next rotation during an animation series.\n * @property {number} rotation Rotation.\n * @property {number} zoom Zoom.\n */\n\n/**\n * Like {@link import(\"./Map.js\").FrameState}, but just `viewState` and `extent`.\n * @typedef {Object} ViewStateLayerStateExtent\n * @property {State} viewState View state.\n * @property {import(\"./extent.js\").Extent} extent Extent (in user projection coordinates).\n * @property {Array} [layerStatesArray] Layer states.\n */\n\n/**\n * Default min zoom level for the map view.\n * @type {number}\n */\nconst DEFAULT_MIN_ZOOM = 0;\n\n/**\n * @typedef {import(\"./ObjectEventType\").Types|'change:center'|'change:resolution'|'change:rotation'} ViewObjectEventTypes\n */\n\n/***\n * @template Return\n * @typedef {import(\"./Observable\").OnSignature &\n * import(\"./Observable\").OnSignature &\n * import(\"./Observable\").CombinedOnSignature} ViewOnSignature\n */\n\n/**\n * @classdesc\n * A View object represents a simple 2D view of the map.\n *\n * This is the object to act upon to change the center, resolution,\n * and rotation of the map.\n *\n * A View has a `projection`. The projection determines the\n * coordinate system of the center, and its units determine the units of the\n * resolution (projection units per pixel). The default projection is\n * Web Mercator (EPSG:3857).\n *\n * ### The view states\n *\n * A View is determined by three states: `center`, `resolution`,\n * and `rotation`. Each state has a corresponding getter and setter, e.g.\n * `getCenter` and `setCenter` for the `center` state.\n *\n * The `zoom` state is actually not saved on the view: all computations\n * internally use the `resolution` state. Still, the `setZoom` and `getZoom`\n * methods are available, as well as `getResolutionForZoom` and\n * `getZoomForResolution` to switch from one system to the other.\n *\n * ### The constraints\n *\n * `setCenter`, `setResolution` and `setRotation` can be used to change the\n * states of the view, but any constraint defined in the constructor will\n * be applied along the way.\n *\n * A View object can have a *resolution constraint*, a *rotation constraint*\n * and a *center constraint*.\n *\n * The *resolution constraint* typically restricts min/max values and\n * snaps to specific resolutions. It is determined by the following\n * options: `resolutions`, `maxResolution`, `maxZoom` and `zoomFactor`.\n * If `resolutions` is set, the other three options are ignored. See\n * documentation for each option for more information. By default, the view\n * only has a min/max restriction and allow intermediary zoom levels when\n * pinch-zooming for example.\n *\n * The *rotation constraint* snaps to specific angles. It is determined\n * by the following options: `enableRotation` and `constrainRotation`.\n * By default rotation is allowed and its value is snapped to zero when approaching the\n * horizontal.\n *\n * The *center constraint* is determined by the `extent` option. By\n * default the view center is not constrained at all.\n *\n * ### Changing the view state\n *\n * It is important to note that `setZoom`, `setResolution`, `setCenter` and\n * `setRotation` are subject to the above mentioned constraints. As such, it\n * may sometimes not be possible to know in advance the resulting state of the\n * View. For example, calling `setResolution(10)` does not guarantee that\n * `getResolution()` will return `10`.\n *\n * A consequence of this is that, when applying a delta on the view state, one\n * should use `adjustCenter`, `adjustRotation`, `adjustZoom` and `adjustResolution`\n * rather than the corresponding setters. This will let view do its internal\n * computations. Besides, the `adjust*` methods also take an `anchor`\n * argument which allows specifying an origin for the transformation.\n *\n * ### Interacting with the view\n *\n * View constraints are usually only applied when the view is *at rest*, meaning that\n * no interaction or animation is ongoing. As such, if the user puts the view in a\n * state that is not equivalent to a constrained one (e.g. rotating the view when\n * the snap angle is 0), an animation will be triggered at the interaction end to\n * put back the view to a stable state;\n *\n * @api\n */\nclass View extends BaseObject {\n /**\n * @param {ViewOptions} [options] View options.\n */\n constructor(options) {\n super();\n\n /***\n * @type {ViewOnSignature}\n */\n this.on;\n\n /***\n * @type {ViewOnSignature}\n */\n this.once;\n\n /***\n * @type {ViewOnSignature}\n */\n this.un;\n\n options = Object.assign({}, options);\n\n /**\n * @private\n * @type {Array}\n */\n this.hints_ = [0, 0];\n\n /**\n * @private\n * @type {Array>}\n */\n this.animations_ = [];\n\n /**\n * @private\n * @type {number|undefined}\n */\n this.updateAnimationKey_;\n\n /**\n * @private\n * @const\n * @type {import(\"./proj/Projection.js\").default}\n */\n this.projection_ = createProjection(options.projection, 'EPSG:3857');\n\n /**\n * @private\n * @type {import(\"./size.js\").Size}\n */\n this.viewportSize_ = [100, 100];\n\n /**\n * @private\n * @type {import(\"./coordinate.js\").Coordinate|undefined}\n */\n this.targetCenter_ = null;\n\n /**\n * @private\n * @type {number|undefined}\n */\n this.targetResolution_;\n\n /**\n * @private\n * @type {number|undefined}\n */\n this.targetRotation_;\n\n /**\n * @private\n * @type {import(\"./coordinate.js\").Coordinate}\n */\n this.nextCenter_ = null;\n\n /**\n * @private\n * @type {number}\n */\n this.nextResolution_;\n\n /**\n * @private\n * @type {number}\n */\n this.nextRotation_;\n\n /**\n * @private\n * @type {import(\"./coordinate.js\").Coordinate|undefined}\n */\n this.cancelAnchor_ = undefined;\n\n if (options.projection) {\n disableCoordinateWarning();\n }\n if (options.center) {\n options.center = fromUserCoordinate(options.center, this.projection_);\n }\n if (options.extent) {\n options.extent = fromUserExtent(options.extent, this.projection_);\n }\n\n this.applyOptions_(options);\n }\n\n /**\n * Set up the view with the given options.\n * @param {ViewOptions} options View options.\n */\n applyOptions_(options) {\n const properties = Object.assign({}, options);\n for (const key in ViewProperty) {\n delete properties[key];\n }\n this.setProperties(properties, true);\n\n const resolutionConstraintInfo = createResolutionConstraint(options);\n\n /**\n * @private\n * @type {number}\n */\n this.maxResolution_ = resolutionConstraintInfo.maxResolution;\n\n /**\n * @private\n * @type {number}\n */\n this.minResolution_ = resolutionConstraintInfo.minResolution;\n\n /**\n * @private\n * @type {number}\n */\n this.zoomFactor_ = resolutionConstraintInfo.zoomFactor;\n\n /**\n * @private\n * @type {Array|undefined}\n */\n this.resolutions_ = options.resolutions;\n\n /**\n * @type {Array|undefined}\n * @private\n */\n this.padding_ = options.padding;\n\n /**\n * @private\n * @type {number}\n */\n this.minZoom_ = resolutionConstraintInfo.minZoom;\n\n const centerConstraint = createCenterConstraint(options);\n const resolutionConstraint = resolutionConstraintInfo.constraint;\n const rotationConstraint = createRotationConstraint(options);\n\n /**\n * @private\n * @type {Constraints}\n */\n this.constraints_ = {\n center: centerConstraint,\n resolution: resolutionConstraint,\n rotation: rotationConstraint,\n };\n\n this.setRotation(options.rotation !== undefined ? options.rotation : 0);\n this.setCenterInternal(\n options.center !== undefined ? options.center : null\n );\n if (options.resolution !== undefined) {\n this.setResolution(options.resolution);\n } else if (options.zoom !== undefined) {\n this.setZoom(options.zoom);\n }\n }\n\n /**\n * Padding (in css pixels).\n * If the map viewport is partially covered with other content (overlays) along\n * its edges, this setting allows to shift the center of the viewport away from that\n * content. The order of the values in the array is top, right, bottom, left.\n * The default is no padding, which is equivalent to `[0, 0, 0, 0]`.\n * @type {Array|undefined}\n * @api\n */\n get padding() {\n return this.padding_;\n }\n set padding(padding) {\n let oldPadding = this.padding_;\n this.padding_ = padding;\n const center = this.getCenterInternal();\n if (center) {\n const newPadding = padding || [0, 0, 0, 0];\n oldPadding = oldPadding || [0, 0, 0, 0];\n const resolution = this.getResolution();\n const offsetX =\n (resolution / 2) *\n (newPadding[3] - oldPadding[3] + oldPadding[1] - newPadding[1]);\n const offsetY =\n (resolution / 2) *\n (newPadding[0] - oldPadding[0] + oldPadding[2] - newPadding[2]);\n this.setCenterInternal([center[0] + offsetX, center[1] - offsetY]);\n }\n }\n\n /**\n * Get an updated version of the view options used to construct the view. The\n * current resolution (or zoom), center, and rotation are applied to any stored\n * options. The provided options can be used to apply new min/max zoom or\n * resolution limits.\n * @param {ViewOptions} newOptions New options to be applied.\n * @return {ViewOptions} New options updated with the current view state.\n */\n getUpdatedOptions_(newOptions) {\n const options = this.getProperties();\n\n // preserve resolution (or zoom)\n if (options.resolution !== undefined) {\n options.resolution = this.getResolution();\n } else {\n options.zoom = this.getZoom();\n }\n\n // preserve center\n options.center = this.getCenterInternal();\n\n // preserve rotation\n options.rotation = this.getRotation();\n\n return Object.assign({}, options, newOptions);\n }\n\n /**\n * Animate the view. The view's center, zoom (or resolution), and rotation\n * can be animated for smooth transitions between view states. For example,\n * to animate the view to a new zoom level:\n *\n * view.animate({zoom: view.getZoom() + 1});\n *\n * By default, the animation lasts one second and uses in-and-out easing. You\n * can customize this behavior by including `duration` (in milliseconds) and\n * `easing` options (see {@link module:ol/easing}).\n *\n * To chain together multiple animations, call the method with multiple\n * animation objects. For example, to first zoom and then pan:\n *\n * view.animate({zoom: 10}, {center: [0, 0]});\n *\n * If you provide a function as the last argument to the animate method, it\n * will get called at the end of an animation series. The callback will be\n * called with `true` if the animation series completed on its own or `false`\n * if it was cancelled.\n *\n * Animations are cancelled by user interactions (e.g. dragging the map) or by\n * calling `view.setCenter()`, `view.setResolution()`, or `view.setRotation()`\n * (or another method that calls one of these).\n *\n * @param {...(AnimationOptions|function(boolean): void)} var_args Animation\n * options. Multiple animations can be run in series by passing multiple\n * options objects. To run multiple animations in parallel, call the method\n * multiple times. An optional callback can be provided as a final\n * argument. The callback will be called with a boolean indicating whether\n * the animation completed without being cancelled.\n * @api\n */\n animate(var_args) {\n if (this.isDef() && !this.getAnimating()) {\n this.resolveConstraints(0);\n }\n const args = new Array(arguments.length);\n for (let i = 0; i < args.length; ++i) {\n let options = arguments[i];\n if (options.center) {\n options = Object.assign({}, options);\n options.center = fromUserCoordinate(\n options.center,\n this.getProjection()\n );\n }\n if (options.anchor) {\n options = Object.assign({}, options);\n options.anchor = fromUserCoordinate(\n options.anchor,\n this.getProjection()\n );\n }\n args[i] = options;\n }\n this.animateInternal.apply(this, args);\n }\n\n /**\n * @param {...(AnimationOptions|function(boolean): void)} var_args Animation options.\n */\n animateInternal(var_args) {\n let animationCount = arguments.length;\n let callback;\n if (\n animationCount > 1 &&\n typeof arguments[animationCount - 1] === 'function'\n ) {\n callback = arguments[animationCount - 1];\n --animationCount;\n }\n\n let i = 0;\n for (; i < animationCount && !this.isDef(); ++i) {\n // if view properties are not yet set, shortcut to the final state\n const state = arguments[i];\n if (state.center) {\n this.setCenterInternal(state.center);\n }\n if (state.zoom !== undefined) {\n this.setZoom(state.zoom);\n } else if (state.resolution) {\n this.setResolution(state.resolution);\n }\n if (state.rotation !== undefined) {\n this.setRotation(state.rotation);\n }\n }\n if (i === animationCount) {\n if (callback) {\n animationCallback(callback, true);\n }\n return;\n }\n\n let start = Date.now();\n let center = this.targetCenter_.slice();\n let resolution = this.targetResolution_;\n let rotation = this.targetRotation_;\n const series = [];\n for (; i < animationCount; ++i) {\n const options = /** @type {AnimationOptions} */ (arguments[i]);\n\n const animation = {\n start: start,\n complete: false,\n anchor: options.anchor,\n duration: options.duration !== undefined ? options.duration : 1000,\n easing: options.easing || inAndOut,\n callback: callback,\n };\n\n if (options.center) {\n animation.sourceCenter = center;\n animation.targetCenter = options.center.slice();\n center = animation.targetCenter;\n }\n\n if (options.zoom !== undefined) {\n animation.sourceResolution = resolution;\n animation.targetResolution = this.getResolutionForZoom(options.zoom);\n resolution = animation.targetResolution;\n } else if (options.resolution) {\n animation.sourceResolution = resolution;\n animation.targetResolution = options.resolution;\n resolution = animation.targetResolution;\n }\n\n if (options.rotation !== undefined) {\n animation.sourceRotation = rotation;\n const delta =\n modulo(options.rotation - rotation + Math.PI, 2 * Math.PI) - Math.PI;\n animation.targetRotation = rotation + delta;\n rotation = animation.targetRotation;\n }\n\n // check if animation is a no-op\n if (isNoopAnimation(animation)) {\n animation.complete = true;\n // we still push it onto the series for callback handling\n } else {\n start += animation.duration;\n }\n series.push(animation);\n }\n this.animations_.push(series);\n this.setHint(ViewHint.ANIMATING, 1);\n this.updateAnimations_();\n }\n\n /**\n * Determine if the view is being animated.\n * @return {boolean} The view is being animated.\n * @api\n */\n getAnimating() {\n return this.hints_[ViewHint.ANIMATING] > 0;\n }\n\n /**\n * Determine if the user is interacting with the view, such as panning or zooming.\n * @return {boolean} The view is being interacted with.\n * @api\n */\n getInteracting() {\n return this.hints_[ViewHint.INTERACTING] > 0;\n }\n\n /**\n * Cancel any ongoing animations.\n * @api\n */\n cancelAnimations() {\n this.setHint(ViewHint.ANIMATING, -this.hints_[ViewHint.ANIMATING]);\n let anchor;\n for (let i = 0, ii = this.animations_.length; i < ii; ++i) {\n const series = this.animations_[i];\n if (series[0].callback) {\n animationCallback(series[0].callback, false);\n }\n if (!anchor) {\n for (let j = 0, jj = series.length; j < jj; ++j) {\n const animation = series[j];\n if (!animation.complete) {\n anchor = animation.anchor;\n break;\n }\n }\n }\n }\n this.animations_.length = 0;\n this.cancelAnchor_ = anchor;\n this.nextCenter_ = null;\n this.nextResolution_ = NaN;\n this.nextRotation_ = NaN;\n }\n\n /**\n * Update all animations.\n */\n updateAnimations_() {\n if (this.updateAnimationKey_ !== undefined) {\n cancelAnimationFrame(this.updateAnimationKey_);\n this.updateAnimationKey_ = undefined;\n }\n if (!this.getAnimating()) {\n return;\n }\n const now = Date.now();\n let more = false;\n for (let i = this.animations_.length - 1; i >= 0; --i) {\n const series = this.animations_[i];\n let seriesComplete = true;\n for (let j = 0, jj = series.length; j < jj; ++j) {\n const animation = series[j];\n if (animation.complete) {\n continue;\n }\n const elapsed = now - animation.start;\n let fraction =\n animation.duration > 0 ? elapsed / animation.duration : 1;\n if (fraction >= 1) {\n animation.complete = true;\n fraction = 1;\n } else {\n seriesComplete = false;\n }\n const progress = animation.easing(fraction);\n if (animation.sourceCenter) {\n const x0 = animation.sourceCenter[0];\n const y0 = animation.sourceCenter[1];\n const x1 = animation.targetCenter[0];\n const y1 = animation.targetCenter[1];\n this.nextCenter_ = animation.targetCenter;\n const x = x0 + progress * (x1 - x0);\n const y = y0 + progress * (y1 - y0);\n this.targetCenter_ = [x, y];\n }\n if (animation.sourceResolution && animation.targetResolution) {\n const resolution =\n progress === 1\n ? animation.targetResolution\n : animation.sourceResolution +\n progress *\n (animation.targetResolution - animation.sourceResolution);\n if (animation.anchor) {\n const size = this.getViewportSize_(this.getRotation());\n const constrainedResolution = this.constraints_.resolution(\n resolution,\n 0,\n size,\n true\n );\n this.targetCenter_ = this.calculateCenterZoom(\n constrainedResolution,\n animation.anchor\n );\n }\n this.nextResolution_ = animation.targetResolution;\n this.targetResolution_ = resolution;\n this.applyTargetState_(true);\n }\n if (\n animation.sourceRotation !== undefined &&\n animation.targetRotation !== undefined\n ) {\n const rotation =\n progress === 1\n ? modulo(animation.targetRotation + Math.PI, 2 * Math.PI) -\n Math.PI\n : animation.sourceRotation +\n progress *\n (animation.targetRotation - animation.sourceRotation);\n if (animation.anchor) {\n const constrainedRotation = this.constraints_.rotation(\n rotation,\n true\n );\n this.targetCenter_ = this.calculateCenterRotate(\n constrainedRotation,\n animation.anchor\n );\n }\n this.nextRotation_ = animation.targetRotation;\n this.targetRotation_ = rotation;\n }\n this.applyTargetState_(true);\n more = true;\n if (!animation.complete) {\n break;\n }\n }\n if (seriesComplete) {\n this.animations_[i] = null;\n this.setHint(ViewHint.ANIMATING, -1);\n this.nextCenter_ = null;\n this.nextResolution_ = NaN;\n this.nextRotation_ = NaN;\n const callback = series[0].callback;\n if (callback) {\n animationCallback(callback, true);\n }\n }\n }\n // prune completed series\n this.animations_ = this.animations_.filter(Boolean);\n if (more && this.updateAnimationKey_ === undefined) {\n this.updateAnimationKey_ = requestAnimationFrame(\n this.updateAnimations_.bind(this)\n );\n }\n }\n\n /**\n * @param {number} rotation Target rotation.\n * @param {import(\"./coordinate.js\").Coordinate} anchor Rotation anchor.\n * @return {import(\"./coordinate.js\").Coordinate|undefined} Center for rotation and anchor.\n */\n calculateCenterRotate(rotation, anchor) {\n let center;\n const currentCenter = this.getCenterInternal();\n if (currentCenter !== undefined) {\n center = [currentCenter[0] - anchor[0], currentCenter[1] - anchor[1]];\n rotateCoordinate(center, rotation - this.getRotation());\n addCoordinate(center, anchor);\n }\n return center;\n }\n\n /**\n * @param {number} resolution Target resolution.\n * @param {import(\"./coordinate.js\").Coordinate} anchor Zoom anchor.\n * @return {import(\"./coordinate.js\").Coordinate|undefined} Center for resolution and anchor.\n */\n calculateCenterZoom(resolution, anchor) {\n let center;\n const currentCenter = this.getCenterInternal();\n const currentResolution = this.getResolution();\n if (currentCenter !== undefined && currentResolution !== undefined) {\n const x =\n anchor[0] -\n (resolution * (anchor[0] - currentCenter[0])) / currentResolution;\n const y =\n anchor[1] -\n (resolution * (anchor[1] - currentCenter[1])) / currentResolution;\n center = [x, y];\n }\n return center;\n }\n\n /**\n * Returns the current viewport size.\n * @private\n * @param {number} [rotation] Take into account the rotation of the viewport when giving the size\n * @return {import(\"./size.js\").Size} Viewport size or `[100, 100]` when no viewport is found.\n */\n getViewportSize_(rotation) {\n const size = this.viewportSize_;\n if (rotation) {\n const w = size[0];\n const h = size[1];\n return [\n Math.abs(w * Math.cos(rotation)) + Math.abs(h * Math.sin(rotation)),\n Math.abs(w * Math.sin(rotation)) + Math.abs(h * Math.cos(rotation)),\n ];\n }\n return size;\n }\n\n /**\n * Stores the viewport size on the view. The viewport size is not read every time from the DOM\n * to avoid performance hit and layout reflow.\n * This should be done on map size change.\n * Note: the constraints are not resolved during an animation to avoid stopping it\n * @param {import(\"./size.js\").Size} [size] Viewport size; if undefined, [100, 100] is assumed\n */\n setViewportSize(size) {\n this.viewportSize_ = Array.isArray(size) ? size.slice() : [100, 100];\n if (!this.getAnimating()) {\n this.resolveConstraints(0);\n }\n }\n\n /**\n * Get the view center.\n * @return {import(\"./coordinate.js\").Coordinate|undefined} The center of the view.\n * @observable\n * @api\n */\n getCenter() {\n const center = this.getCenterInternal();\n if (!center) {\n return center;\n }\n return toUserCoordinate(center, this.getProjection());\n }\n\n /**\n * Get the view center without transforming to user projection.\n * @return {import(\"./coordinate.js\").Coordinate|undefined} The center of the view.\n */\n getCenterInternal() {\n return /** @type {import(\"./coordinate.js\").Coordinate|undefined} */ (\n this.get(ViewProperty.CENTER)\n );\n }\n\n /**\n * @return {Constraints} Constraints.\n */\n getConstraints() {\n return this.constraints_;\n }\n\n /**\n * @return {boolean} Resolution constraint is set\n */\n getConstrainResolution() {\n return this.get('constrainResolution');\n }\n\n /**\n * @param {Array} [hints] Destination array.\n * @return {Array} Hint.\n */\n getHints(hints) {\n if (hints !== undefined) {\n hints[0] = this.hints_[0];\n hints[1] = this.hints_[1];\n return hints;\n }\n return this.hints_.slice();\n }\n\n /**\n * Calculate the extent for the current view state and the passed size.\n * The size is the pixel dimensions of the box into which the calculated extent\n * should fit. In most cases you want to get the extent of the entire map,\n * that is `map.getSize()`.\n * @param {import(\"./size.js\").Size} [size] Box pixel size. If not provided, the size\n * of the map that uses this view will be used.\n * @return {import(\"./extent.js\").Extent} Extent.\n * @api\n */\n calculateExtent(size) {\n const extent = this.calculateExtentInternal(size);\n return toUserExtent(extent, this.getProjection());\n }\n\n /**\n * @param {import(\"./size.js\").Size} [size] Box pixel size. If not provided,\n * the map's last known viewport size will be used.\n * @return {import(\"./extent.js\").Extent} Extent.\n */\n calculateExtentInternal(size) {\n size = size || this.getViewportSizeMinusPadding_();\n const center = /** @type {!import(\"./coordinate.js\").Coordinate} */ (\n this.getCenterInternal()\n );\n assert(center, 1); // The view center is not defined\n const resolution = /** @type {!number} */ (this.getResolution());\n assert(resolution !== undefined, 2); // The view resolution is not defined\n const rotation = /** @type {!number} */ (this.getRotation());\n assert(rotation !== undefined, 3); // The view rotation is not defined\n\n return getForViewAndSize(center, resolution, rotation, size);\n }\n\n /**\n * Get the maximum resolution of the view.\n * @return {number} The maximum resolution of the view.\n * @api\n */\n getMaxResolution() {\n return this.maxResolution_;\n }\n\n /**\n * Get the minimum resolution of the view.\n * @return {number} The minimum resolution of the view.\n * @api\n */\n getMinResolution() {\n return this.minResolution_;\n }\n\n /**\n * Get the maximum zoom level for the view.\n * @return {number} The maximum zoom level.\n * @api\n */\n getMaxZoom() {\n return /** @type {number} */ (\n this.getZoomForResolution(this.minResolution_)\n );\n }\n\n /**\n * Set a new maximum zoom level for the view.\n * @param {number} zoom The maximum zoom level.\n * @api\n */\n setMaxZoom(zoom) {\n this.applyOptions_(this.getUpdatedOptions_({maxZoom: zoom}));\n }\n\n /**\n * Get the minimum zoom level for the view.\n * @return {number} The minimum zoom level.\n * @api\n */\n getMinZoom() {\n return /** @type {number} */ (\n this.getZoomForResolution(this.maxResolution_)\n );\n }\n\n /**\n * Set a new minimum zoom level for the view.\n * @param {number} zoom The minimum zoom level.\n * @api\n */\n setMinZoom(zoom) {\n this.applyOptions_(this.getUpdatedOptions_({minZoom: zoom}));\n }\n\n /**\n * Set whether the view should allow intermediary zoom levels.\n * @param {boolean} enabled Whether the resolution is constrained.\n * @api\n */\n setConstrainResolution(enabled) {\n this.applyOptions_(this.getUpdatedOptions_({constrainResolution: enabled}));\n }\n\n /**\n * Get the view projection.\n * @return {import(\"./proj/Projection.js\").default} The projection of the view.\n * @api\n */\n getProjection() {\n return this.projection_;\n }\n\n /**\n * Get the view resolution.\n * @return {number|undefined} The resolution of the view.\n * @observable\n * @api\n */\n getResolution() {\n return /** @type {number|undefined} */ (this.get(ViewProperty.RESOLUTION));\n }\n\n /**\n * Get the resolutions for the view. This returns the array of resolutions\n * passed to the constructor of the View, or undefined if none were given.\n * @return {Array|undefined} The resolutions of the view.\n * @api\n */\n getResolutions() {\n return this.resolutions_;\n }\n\n /**\n * Get the resolution for a provided extent (in map units) and size (in pixels).\n * @param {import(\"./extent.js\").Extent} extent Extent.\n * @param {import(\"./size.js\").Size} [size] Box pixel size.\n * @return {number} The resolution at which the provided extent will render at\n * the given size.\n * @api\n */\n getResolutionForExtent(extent, size) {\n return this.getResolutionForExtentInternal(\n fromUserExtent(extent, this.getProjection()),\n size\n );\n }\n\n /**\n * Get the resolution for a provided extent (in map units) and size (in pixels).\n * @param {import(\"./extent.js\").Extent} extent Extent.\n * @param {import(\"./size.js\").Size} [size] Box pixel size.\n * @return {number} The resolution at which the provided extent will render at\n * the given size.\n */\n getResolutionForExtentInternal(extent, size) {\n size = size || this.getViewportSizeMinusPadding_();\n const xResolution = getWidth(extent) / size[0];\n const yResolution = getHeight(extent) / size[1];\n return Math.max(xResolution, yResolution);\n }\n\n /**\n * Return a function that returns a value between 0 and 1 for a\n * resolution. Exponential scaling is assumed.\n * @param {number} [power] Power.\n * @return {function(number): number} Resolution for value function.\n */\n getResolutionForValueFunction(power) {\n power = power || 2;\n const maxResolution = this.getConstrainedResolution(this.maxResolution_);\n const minResolution = this.minResolution_;\n const max = Math.log(maxResolution / minResolution) / Math.log(power);\n return (\n /**\n * @param {number} value Value.\n * @return {number} Resolution.\n */\n function (value) {\n const resolution = maxResolution / Math.pow(power, value * max);\n return resolution;\n }\n );\n }\n\n /**\n * Get the view rotation.\n * @return {number} The rotation of the view in radians.\n * @observable\n * @api\n */\n getRotation() {\n return /** @type {number} */ (this.get(ViewProperty.ROTATION));\n }\n\n /**\n * Return a function that returns a resolution for a value between\n * 0 and 1. Exponential scaling is assumed.\n * @param {number} [power] Power.\n * @return {function(number): number} Value for resolution function.\n */\n getValueForResolutionFunction(power) {\n const logPower = Math.log(power || 2);\n const maxResolution = this.getConstrainedResolution(this.maxResolution_);\n const minResolution = this.minResolution_;\n const max = Math.log(maxResolution / minResolution) / logPower;\n return (\n /**\n * @param {number} resolution Resolution.\n * @return {number} Value.\n */\n function (resolution) {\n const value = Math.log(maxResolution / resolution) / logPower / max;\n return value;\n }\n );\n }\n\n /**\n * Returns the size of the viewport minus padding.\n * @private\n * @param {number} [rotation] Take into account the rotation of the viewport when giving the size\n * @return {import(\"./size.js\").Size} Viewport size reduced by the padding.\n */\n getViewportSizeMinusPadding_(rotation) {\n let size = this.getViewportSize_(rotation);\n const padding = this.padding_;\n if (padding) {\n size = [\n size[0] - padding[1] - padding[3],\n size[1] - padding[0] - padding[2],\n ];\n }\n return size;\n }\n\n /**\n * @return {State} View state.\n */\n getState() {\n const projection = this.getProjection();\n const resolution = this.getResolution();\n const rotation = this.getRotation();\n let center = /** @type {import(\"./coordinate.js\").Coordinate} */ (\n this.getCenterInternal()\n );\n const padding = this.padding_;\n if (padding) {\n const reducedSize = this.getViewportSizeMinusPadding_();\n center = calculateCenterOn(\n center,\n this.getViewportSize_(),\n [reducedSize[0] / 2 + padding[3], reducedSize[1] / 2 + padding[0]],\n resolution,\n rotation\n );\n }\n return {\n center: center.slice(0),\n projection: projection !== undefined ? projection : null,\n resolution: resolution,\n nextCenter: this.nextCenter_,\n nextResolution: this.nextResolution_,\n nextRotation: this.nextRotation_,\n rotation: rotation,\n zoom: this.getZoom(),\n };\n }\n\n /**\n * @return {ViewStateLayerStateExtent} Like `FrameState`, but just `viewState` and `extent`.\n */\n getViewStateAndExtent() {\n return {\n viewState: this.getState(),\n extent: this.calculateExtent(),\n };\n }\n\n /**\n * Get the current zoom level. This method may return non-integer zoom levels\n * if the view does not constrain the resolution, or if an interaction or\n * animation is underway.\n * @return {number|undefined} Zoom.\n * @api\n */\n getZoom() {\n let zoom;\n const resolution = this.getResolution();\n if (resolution !== undefined) {\n zoom = this.getZoomForResolution(resolution);\n }\n return zoom;\n }\n\n /**\n * Get the zoom level for a resolution.\n * @param {number} resolution The resolution.\n * @return {number|undefined} The zoom level for the provided resolution.\n * @api\n */\n getZoomForResolution(resolution) {\n let offset = this.minZoom_ || 0;\n let max, zoomFactor;\n if (this.resolutions_) {\n const nearest = linearFindNearest(this.resolutions_, resolution, 1);\n offset = nearest;\n max = this.resolutions_[nearest];\n if (nearest == this.resolutions_.length - 1) {\n zoomFactor = 2;\n } else {\n zoomFactor = max / this.resolutions_[nearest + 1];\n }\n } else {\n max = this.maxResolution_;\n zoomFactor = this.zoomFactor_;\n }\n return offset + Math.log(max / resolution) / Math.log(zoomFactor);\n }\n\n /**\n * Get the resolution for a zoom level.\n * @param {number} zoom Zoom level.\n * @return {number} The view resolution for the provided zoom level.\n * @api\n */\n getResolutionForZoom(zoom) {\n if (this.resolutions_) {\n if (this.resolutions_.length <= 1) {\n return 0;\n }\n const baseLevel = clamp(\n Math.floor(zoom),\n 0,\n this.resolutions_.length - 2\n );\n const zoomFactor =\n this.resolutions_[baseLevel] / this.resolutions_[baseLevel + 1];\n return (\n this.resolutions_[baseLevel] /\n Math.pow(zoomFactor, clamp(zoom - baseLevel, 0, 1))\n );\n }\n return (\n this.maxResolution_ / Math.pow(this.zoomFactor_, zoom - this.minZoom_)\n );\n }\n\n /**\n * Fit the given geometry or extent based on the given map size and border.\n * The size is pixel dimensions of the box to fit the extent into.\n * In most cases you will want to use the map size, that is `map.getSize()`.\n * Takes care of the map angle.\n * @param {import(\"./geom/SimpleGeometry.js\").default|import(\"./extent.js\").Extent} geometryOrExtent The geometry or\n * extent to fit the view to.\n * @param {FitOptions} [options] Options.\n * @api\n */\n fit(geometryOrExtent, options) {\n /** @type {import(\"./geom/SimpleGeometry.js\").default} */\n let geometry;\n assert(\n Array.isArray(geometryOrExtent) ||\n typeof (/** @type {?} */ (geometryOrExtent).getSimplifiedGeometry) ===\n 'function',\n 24\n ); // Invalid extent or geometry provided as `geometry`\n if (Array.isArray(geometryOrExtent)) {\n assert(!isEmpty(geometryOrExtent), 25); // Cannot fit empty extent provided as `geometry`\n const extent = fromUserExtent(geometryOrExtent, this.getProjection());\n geometry = polygonFromExtent(extent);\n } else if (geometryOrExtent.getType() === 'Circle') {\n const extent = fromUserExtent(\n geometryOrExtent.getExtent(),\n this.getProjection()\n );\n geometry = polygonFromExtent(extent);\n geometry.rotate(this.getRotation(), getCenter(extent));\n } else {\n const userProjection = getUserProjection();\n if (userProjection) {\n geometry = /** @type {import(\"./geom/SimpleGeometry.js\").default} */ (\n geometryOrExtent\n .clone()\n .transform(userProjection, this.getProjection())\n );\n } else {\n geometry = geometryOrExtent;\n }\n }\n\n this.fitInternal(geometry, options);\n }\n\n /**\n * Calculate rotated extent\n * @param {import(\"./geom/SimpleGeometry.js\").default} geometry The geometry.\n * @return {import(\"./extent\").Extent} The rotated extent for the geometry.\n */\n rotatedExtentForGeometry(geometry) {\n const rotation = this.getRotation();\n const cosAngle = Math.cos(rotation);\n const sinAngle = Math.sin(-rotation);\n const coords = geometry.getFlatCoordinates();\n const stride = geometry.getStride();\n let minRotX = +Infinity;\n let minRotY = +Infinity;\n let maxRotX = -Infinity;\n let maxRotY = -Infinity;\n for (let i = 0, ii = coords.length; i < ii; i += stride) {\n const rotX = coords[i] * cosAngle - coords[i + 1] * sinAngle;\n const rotY = coords[i] * sinAngle + coords[i + 1] * cosAngle;\n minRotX = Math.min(minRotX, rotX);\n minRotY = Math.min(minRotY, rotY);\n maxRotX = Math.max(maxRotX, rotX);\n maxRotY = Math.max(maxRotY, rotY);\n }\n return [minRotX, minRotY, maxRotX, maxRotY];\n }\n\n /**\n * @param {import(\"./geom/SimpleGeometry.js\").default} geometry The geometry.\n * @param {FitOptions} [options] Options.\n */\n fitInternal(geometry, options) {\n options = options || {};\n let size = options.size;\n if (!size) {\n size = this.getViewportSizeMinusPadding_();\n }\n const padding =\n options.padding !== undefined ? options.padding : [0, 0, 0, 0];\n const nearest = options.nearest !== undefined ? options.nearest : false;\n let minResolution;\n if (options.minResolution !== undefined) {\n minResolution = options.minResolution;\n } else if (options.maxZoom !== undefined) {\n minResolution = this.getResolutionForZoom(options.maxZoom);\n } else {\n minResolution = 0;\n }\n\n const rotatedExtent = this.rotatedExtentForGeometry(geometry);\n\n // calculate resolution\n let resolution = this.getResolutionForExtentInternal(rotatedExtent, [\n size[0] - padding[1] - padding[3],\n size[1] - padding[0] - padding[2],\n ]);\n resolution = isNaN(resolution)\n ? minResolution\n : Math.max(resolution, minResolution);\n resolution = this.getConstrainedResolution(resolution, nearest ? 0 : 1);\n\n // calculate center\n const rotation = this.getRotation();\n const sinAngle = Math.sin(rotation);\n const cosAngle = Math.cos(rotation);\n const centerRot = getCenter(rotatedExtent);\n centerRot[0] += ((padding[1] - padding[3]) / 2) * resolution;\n centerRot[1] += ((padding[0] - padding[2]) / 2) * resolution;\n const centerX = centerRot[0] * cosAngle - centerRot[1] * sinAngle;\n const centerY = centerRot[1] * cosAngle + centerRot[0] * sinAngle;\n const center = this.getConstrainedCenter([centerX, centerY], resolution);\n const callback = options.callback ? options.callback : VOID;\n\n if (options.duration !== undefined) {\n this.animateInternal(\n {\n resolution: resolution,\n center: center,\n duration: options.duration,\n easing: options.easing,\n },\n callback\n );\n } else {\n this.targetResolution_ = resolution;\n this.targetCenter_ = center;\n this.applyTargetState_(false, true);\n animationCallback(callback, true);\n }\n }\n\n /**\n * Center on coordinate and view position.\n * @param {import(\"./coordinate.js\").Coordinate} coordinate Coordinate.\n * @param {import(\"./size.js\").Size} size Box pixel size.\n * @param {import(\"./pixel.js\").Pixel} position Position on the view to center on.\n * @api\n */\n centerOn(coordinate, size, position) {\n this.centerOnInternal(\n fromUserCoordinate(coordinate, this.getProjection()),\n size,\n position\n );\n }\n\n /**\n * @param {import(\"./coordinate.js\").Coordinate} coordinate Coordinate.\n * @param {import(\"./size.js\").Size} size Box pixel size.\n * @param {import(\"./pixel.js\").Pixel} position Position on the view to center on.\n */\n centerOnInternal(coordinate, size, position) {\n this.setCenterInternal(\n calculateCenterOn(\n coordinate,\n size,\n position,\n this.getResolution(),\n this.getRotation()\n )\n );\n }\n\n /**\n * Calculates the shift between map and viewport center.\n * @param {import(\"./coordinate.js\").Coordinate} center Center.\n * @param {number} resolution Resolution.\n * @param {number} rotation Rotation.\n * @param {import(\"./size.js\").Size} size Size.\n * @return {Array|undefined} Center shift.\n */\n calculateCenterShift(center, resolution, rotation, size) {\n let centerShift;\n const padding = this.padding_;\n if (padding && center) {\n const reducedSize = this.getViewportSizeMinusPadding_(-rotation);\n const shiftedCenter = calculateCenterOn(\n center,\n size,\n [reducedSize[0] / 2 + padding[3], reducedSize[1] / 2 + padding[0]],\n resolution,\n rotation\n );\n centerShift = [\n center[0] - shiftedCenter[0],\n center[1] - shiftedCenter[1],\n ];\n }\n return centerShift;\n }\n\n /**\n * @return {boolean} Is defined.\n */\n isDef() {\n return !!this.getCenterInternal() && this.getResolution() !== undefined;\n }\n\n /**\n * Adds relative coordinates to the center of the view. Any extent constraint will apply.\n * @param {import(\"./coordinate.js\").Coordinate} deltaCoordinates Relative value to add.\n * @api\n */\n adjustCenter(deltaCoordinates) {\n const center = toUserCoordinate(this.targetCenter_, this.getProjection());\n this.setCenter([\n center[0] + deltaCoordinates[0],\n center[1] + deltaCoordinates[1],\n ]);\n }\n\n /**\n * Adds relative coordinates to the center of the view. Any extent constraint will apply.\n * @param {import(\"./coordinate.js\").Coordinate} deltaCoordinates Relative value to add.\n */\n adjustCenterInternal(deltaCoordinates) {\n const center = this.targetCenter_;\n this.setCenterInternal([\n center[0] + deltaCoordinates[0],\n center[1] + deltaCoordinates[1],\n ]);\n }\n\n /**\n * Multiply the view resolution by a ratio, optionally using an anchor. Any resolution\n * constraint will apply.\n * @param {number} ratio The ratio to apply on the view resolution.\n * @param {import(\"./coordinate.js\").Coordinate} [anchor] The origin of the transformation.\n * @api\n */\n adjustResolution(ratio, anchor) {\n anchor = anchor && fromUserCoordinate(anchor, this.getProjection());\n this.adjustResolutionInternal(ratio, anchor);\n }\n\n /**\n * Multiply the view resolution by a ratio, optionally using an anchor. Any resolution\n * constraint will apply.\n * @param {number} ratio The ratio to apply on the view resolution.\n * @param {import(\"./coordinate.js\").Coordinate} [anchor] The origin of the transformation.\n */\n adjustResolutionInternal(ratio, anchor) {\n const isMoving = this.getAnimating() || this.getInteracting();\n const size = this.getViewportSize_(this.getRotation());\n const newResolution = this.constraints_.resolution(\n this.targetResolution_ * ratio,\n 0,\n size,\n isMoving\n );\n\n if (anchor) {\n this.targetCenter_ = this.calculateCenterZoom(newResolution, anchor);\n }\n\n this.targetResolution_ *= ratio;\n this.applyTargetState_();\n }\n\n /**\n * Adds a value to the view zoom level, optionally using an anchor. Any resolution\n * constraint will apply.\n * @param {number} delta Relative value to add to the zoom level.\n * @param {import(\"./coordinate.js\").Coordinate} [anchor] The origin of the transformation.\n * @api\n */\n adjustZoom(delta, anchor) {\n this.adjustResolution(Math.pow(this.zoomFactor_, -delta), anchor);\n }\n\n /**\n * Adds a value to the view rotation, optionally using an anchor. Any rotation\n * constraint will apply.\n * @param {number} delta Relative value to add to the zoom rotation, in radians.\n * @param {import(\"./coordinate.js\").Coordinate} [anchor] The rotation center.\n * @api\n */\n adjustRotation(delta, anchor) {\n if (anchor) {\n anchor = fromUserCoordinate(anchor, this.getProjection());\n }\n this.adjustRotationInternal(delta, anchor);\n }\n\n /**\n * @param {number} delta Relative value to add to the zoom rotation, in radians.\n * @param {import(\"./coordinate.js\").Coordinate} [anchor] The rotation center.\n */\n adjustRotationInternal(delta, anchor) {\n const isMoving = this.getAnimating() || this.getInteracting();\n const newRotation = this.constraints_.rotation(\n this.targetRotation_ + delta,\n isMoving\n );\n if (anchor) {\n this.targetCenter_ = this.calculateCenterRotate(newRotation, anchor);\n }\n this.targetRotation_ += delta;\n this.applyTargetState_();\n }\n\n /**\n * Set the center of the current view. Any extent constraint will apply.\n * @param {import(\"./coordinate.js\").Coordinate|undefined} center The center of the view.\n * @observable\n * @api\n */\n setCenter(center) {\n this.setCenterInternal(\n center ? fromUserCoordinate(center, this.getProjection()) : center\n );\n }\n\n /**\n * Set the center using the view projection (not the user projection).\n * @param {import(\"./coordinate.js\").Coordinate|undefined} center The center of the view.\n */\n setCenterInternal(center) {\n this.targetCenter_ = center;\n this.applyTargetState_();\n }\n\n /**\n * @param {import(\"./ViewHint.js\").default} hint Hint.\n * @param {number} delta Delta.\n * @return {number} New value.\n */\n setHint(hint, delta) {\n this.hints_[hint] += delta;\n this.changed();\n return this.hints_[hint];\n }\n\n /**\n * Set the resolution for this view. Any resolution constraint will apply.\n * @param {number|undefined} resolution The resolution of the view.\n * @observable\n * @api\n */\n setResolution(resolution) {\n this.targetResolution_ = resolution;\n this.applyTargetState_();\n }\n\n /**\n * Set the rotation for this view. Any rotation constraint will apply.\n * @param {number} rotation The rotation of the view in radians.\n * @observable\n * @api\n */\n setRotation(rotation) {\n this.targetRotation_ = rotation;\n this.applyTargetState_();\n }\n\n /**\n * Zoom to a specific zoom level. Any resolution constrain will apply.\n * @param {number} zoom Zoom level.\n * @api\n */\n setZoom(zoom) {\n this.setResolution(this.getResolutionForZoom(zoom));\n }\n\n /**\n * Recompute rotation/resolution/center based on target values.\n * Note: we have to compute rotation first, then resolution and center considering that\n * parameters can influence one another in case a view extent constraint is present.\n * @param {boolean} [doNotCancelAnims] Do not cancel animations.\n * @param {boolean} [forceMoving] Apply constraints as if the view is moving.\n * @private\n */\n applyTargetState_(doNotCancelAnims, forceMoving) {\n const isMoving =\n this.getAnimating() || this.getInteracting() || forceMoving;\n\n // compute rotation\n const newRotation = this.constraints_.rotation(\n this.targetRotation_,\n isMoving\n );\n const size = this.getViewportSize_(newRotation);\n const newResolution = this.constraints_.resolution(\n this.targetResolution_,\n 0,\n size,\n isMoving\n );\n const newCenter = this.constraints_.center(\n this.targetCenter_,\n newResolution,\n size,\n isMoving,\n this.calculateCenterShift(\n this.targetCenter_,\n newResolution,\n newRotation,\n size\n )\n );\n\n if (this.get(ViewProperty.ROTATION) !== newRotation) {\n this.set(ViewProperty.ROTATION, newRotation);\n }\n if (this.get(ViewProperty.RESOLUTION) !== newResolution) {\n this.set(ViewProperty.RESOLUTION, newResolution);\n this.set('zoom', this.getZoom(), true);\n }\n if (\n !newCenter ||\n !this.get(ViewProperty.CENTER) ||\n !equals(this.get(ViewProperty.CENTER), newCenter)\n ) {\n this.set(ViewProperty.CENTER, newCenter);\n }\n\n if (this.getAnimating() && !doNotCancelAnims) {\n this.cancelAnimations();\n }\n this.cancelAnchor_ = undefined;\n }\n\n /**\n * If any constraints need to be applied, an animation will be triggered.\n * This is typically done on interaction end.\n * Note: calling this with a duration of 0 will apply the constrained values straight away,\n * without animation.\n * @param {number} [duration] The animation duration in ms.\n * @param {number} [resolutionDirection] Which direction to zoom.\n * @param {import(\"./coordinate.js\").Coordinate} [anchor] The origin of the transformation.\n */\n resolveConstraints(duration, resolutionDirection, anchor) {\n duration = duration !== undefined ? duration : 200;\n const direction = resolutionDirection || 0;\n\n const newRotation = this.constraints_.rotation(this.targetRotation_);\n const size = this.getViewportSize_(newRotation);\n const newResolution = this.constraints_.resolution(\n this.targetResolution_,\n direction,\n size\n );\n const newCenter = this.constraints_.center(\n this.targetCenter_,\n newResolution,\n size,\n false,\n this.calculateCenterShift(\n this.targetCenter_,\n newResolution,\n newRotation,\n size\n )\n );\n\n if (duration === 0 && !this.cancelAnchor_) {\n this.targetResolution_ = newResolution;\n this.targetRotation_ = newRotation;\n this.targetCenter_ = newCenter;\n this.applyTargetState_();\n return;\n }\n\n anchor = anchor || (duration === 0 ? this.cancelAnchor_ : undefined);\n this.cancelAnchor_ = undefined;\n\n if (\n this.getResolution() !== newResolution ||\n this.getRotation() !== newRotation ||\n !this.getCenterInternal() ||\n !equals(this.getCenterInternal(), newCenter)\n ) {\n if (this.getAnimating()) {\n this.cancelAnimations();\n }\n\n this.animateInternal({\n rotation: newRotation,\n center: newCenter,\n resolution: newResolution,\n duration: duration,\n easing: easeOut,\n anchor: anchor,\n });\n }\n }\n\n /**\n * Notify the View that an interaction has started.\n * The view state will be resolved to a stable one if needed\n * (depending on its constraints).\n * @api\n */\n beginInteraction() {\n this.resolveConstraints(0);\n\n this.setHint(ViewHint.INTERACTING, 1);\n }\n\n /**\n * Notify the View that an interaction has ended. The view state will be resolved\n * to a stable one if needed (depending on its constraints).\n * @param {number} [duration] Animation duration in ms.\n * @param {number} [resolutionDirection] Which direction to zoom.\n * @param {import(\"./coordinate.js\").Coordinate} [anchor] The origin of the transformation.\n * @api\n */\n endInteraction(duration, resolutionDirection, anchor) {\n anchor = anchor && fromUserCoordinate(anchor, this.getProjection());\n this.endInteractionInternal(duration, resolutionDirection, anchor);\n }\n\n /**\n * Notify the View that an interaction has ended. The view state will be resolved\n * to a stable one if needed (depending on its constraints).\n * @param {number} [duration] Animation duration in ms.\n * @param {number} [resolutionDirection] Which direction to zoom.\n * @param {import(\"./coordinate.js\").Coordinate} [anchor] The origin of the transformation.\n */\n endInteractionInternal(duration, resolutionDirection, anchor) {\n if (!this.getInteracting()) {\n return;\n }\n this.setHint(ViewHint.INTERACTING, -1);\n this.resolveConstraints(duration, resolutionDirection, anchor);\n }\n\n /**\n * Get a valid position for the view center according to the current constraints.\n * @param {import(\"./coordinate.js\").Coordinate|undefined} targetCenter Target center position.\n * @param {number} [targetResolution] Target resolution. If not supplied, the current one will be used.\n * This is useful to guess a valid center position at a different zoom level.\n * @return {import(\"./coordinate.js\").Coordinate|undefined} Valid center position.\n */\n getConstrainedCenter(targetCenter, targetResolution) {\n const size = this.getViewportSize_(this.getRotation());\n return this.constraints_.center(\n targetCenter,\n targetResolution || this.getResolution(),\n size\n );\n }\n\n /**\n * Get a valid zoom level according to the current view constraints.\n * @param {number|undefined} targetZoom Target zoom.\n * @param {number} [direction=0] Indicate which resolution should be used\n * by a renderer if the view resolution does not match any resolution of the tile source.\n * If 0, the nearest resolution will be used. If 1, the nearest lower resolution\n * will be used. If -1, the nearest higher resolution will be used.\n * @return {number|undefined} Valid zoom level.\n */\n getConstrainedZoom(targetZoom, direction) {\n const targetRes = this.getResolutionForZoom(targetZoom);\n return this.getZoomForResolution(\n this.getConstrainedResolution(targetRes, direction)\n );\n }\n\n /**\n * Get a valid resolution according to the current view constraints.\n * @param {number|undefined} targetResolution Target resolution.\n * @param {number} [direction=0] Indicate which resolution should be used\n * by a renderer if the view resolution does not match any resolution of the tile source.\n * If 0, the nearest resolution will be used. If 1, the nearest lower resolution\n * will be used. If -1, the nearest higher resolution will be used.\n * @return {number|undefined} Valid resolution.\n */\n getConstrainedResolution(targetResolution, direction) {\n direction = direction || 0;\n const size = this.getViewportSize_(this.getRotation());\n\n return this.constraints_.resolution(targetResolution, direction, size);\n }\n}\n\n/**\n * @param {Function} callback Callback.\n * @param {*} returnValue Return value.\n */\nfunction animationCallback(callback, returnValue) {\n setTimeout(function () {\n callback(returnValue);\n }, 0);\n}\n\n/**\n * @param {ViewOptions} options View options.\n * @return {import(\"./centerconstraint.js\").Type} The constraint.\n */\nexport function createCenterConstraint(options) {\n if (options.extent !== undefined) {\n const smooth =\n options.smoothExtentConstraint !== undefined\n ? options.smoothExtentConstraint\n : true;\n return createExtent(options.extent, options.constrainOnlyCenter, smooth);\n }\n\n const projection = createProjection(options.projection, 'EPSG:3857');\n if (options.multiWorld !== true && projection.isGlobal()) {\n const extent = projection.getExtent().slice();\n extent[0] = -Infinity;\n extent[2] = Infinity;\n return createExtent(extent, false, false);\n }\n\n return centerNone;\n}\n\n/**\n * @param {ViewOptions} options View options.\n * @return {{constraint: import(\"./resolutionconstraint.js\").Type, maxResolution: number,\n * minResolution: number, minZoom: number, zoomFactor: number}} The constraint.\n */\nexport function createResolutionConstraint(options) {\n let resolutionConstraint;\n let maxResolution;\n let minResolution;\n\n // TODO: move these to be ol constants\n // see https://github.com/openlayers/openlayers/issues/2076\n const defaultMaxZoom = 28;\n const defaultZoomFactor = 2;\n\n let minZoom =\n options.minZoom !== undefined ? options.minZoom : DEFAULT_MIN_ZOOM;\n\n let maxZoom =\n options.maxZoom !== undefined ? options.maxZoom : defaultMaxZoom;\n\n const zoomFactor =\n options.zoomFactor !== undefined ? options.zoomFactor : defaultZoomFactor;\n\n const multiWorld =\n options.multiWorld !== undefined ? options.multiWorld : false;\n\n const smooth =\n options.smoothResolutionConstraint !== undefined\n ? options.smoothResolutionConstraint\n : true;\n\n const showFullExtent =\n options.showFullExtent !== undefined ? options.showFullExtent : false;\n\n const projection = createProjection(options.projection, 'EPSG:3857');\n const projExtent = projection.getExtent();\n let constrainOnlyCenter = options.constrainOnlyCenter;\n let extent = options.extent;\n if (!multiWorld && !extent && projection.isGlobal()) {\n constrainOnlyCenter = false;\n extent = projExtent;\n }\n\n if (options.resolutions !== undefined) {\n const resolutions = options.resolutions;\n maxResolution = resolutions[minZoom];\n minResolution =\n resolutions[maxZoom] !== undefined\n ? resolutions[maxZoom]\n : resolutions[resolutions.length - 1];\n\n if (options.constrainResolution) {\n resolutionConstraint = createSnapToResolutions(\n resolutions,\n smooth,\n !constrainOnlyCenter && extent,\n showFullExtent\n );\n } else {\n resolutionConstraint = createMinMaxResolution(\n maxResolution,\n minResolution,\n smooth,\n !constrainOnlyCenter && extent,\n showFullExtent\n );\n }\n } else {\n // calculate the default min and max resolution\n const size = !projExtent\n ? // use an extent that can fit the whole world if need be\n (360 * METERS_PER_UNIT.degrees) / projection.getMetersPerUnit()\n : Math.max(getWidth(projExtent), getHeight(projExtent));\n\n const defaultMaxResolution =\n size / DEFAULT_TILE_SIZE / Math.pow(defaultZoomFactor, DEFAULT_MIN_ZOOM);\n\n const defaultMinResolution =\n defaultMaxResolution /\n Math.pow(defaultZoomFactor, defaultMaxZoom - DEFAULT_MIN_ZOOM);\n\n // user provided maxResolution takes precedence\n maxResolution = options.maxResolution;\n if (maxResolution !== undefined) {\n minZoom = 0;\n } else {\n maxResolution = defaultMaxResolution / Math.pow(zoomFactor, minZoom);\n }\n\n // user provided minResolution takes precedence\n minResolution = options.minResolution;\n if (minResolution === undefined) {\n if (options.maxZoom !== undefined) {\n if (options.maxResolution !== undefined) {\n minResolution = maxResolution / Math.pow(zoomFactor, maxZoom);\n } else {\n minResolution = defaultMaxResolution / Math.pow(zoomFactor, maxZoom);\n }\n } else {\n minResolution = defaultMinResolution;\n }\n }\n\n // given discrete zoom levels, minResolution may be different than provided\n maxZoom =\n minZoom +\n Math.floor(\n Math.log(maxResolution / minResolution) / Math.log(zoomFactor)\n );\n minResolution = maxResolution / Math.pow(zoomFactor, maxZoom - minZoom);\n\n if (options.constrainResolution) {\n resolutionConstraint = createSnapToPower(\n zoomFactor,\n maxResolution,\n minResolution,\n smooth,\n !constrainOnlyCenter && extent,\n showFullExtent\n );\n } else {\n resolutionConstraint = createMinMaxResolution(\n maxResolution,\n minResolution,\n smooth,\n !constrainOnlyCenter && extent,\n showFullExtent\n );\n }\n }\n return {\n constraint: resolutionConstraint,\n maxResolution: maxResolution,\n minResolution: minResolution,\n minZoom: minZoom,\n zoomFactor: zoomFactor,\n };\n}\n\n/**\n * @param {ViewOptions} options View options.\n * @return {import(\"./rotationconstraint.js\").Type} Rotation constraint.\n */\nexport function createRotationConstraint(options) {\n const enableRotation =\n options.enableRotation !== undefined ? options.enableRotation : true;\n if (enableRotation) {\n const constrainRotation = options.constrainRotation;\n if (constrainRotation === undefined || constrainRotation === true) {\n return createSnapToZero();\n }\n if (constrainRotation === false) {\n return rotationNone;\n }\n if (typeof constrainRotation === 'number') {\n return createSnapToN(constrainRotation);\n }\n return rotationNone;\n }\n return disable;\n}\n\n/**\n * Determine if an animation involves no view change.\n * @param {Animation} animation The animation.\n * @return {boolean} The animation involves no view change.\n */\nexport function isNoopAnimation(animation) {\n if (animation.sourceCenter && animation.targetCenter) {\n if (!coordinatesEqual(animation.sourceCenter, animation.targetCenter)) {\n return false;\n }\n }\n if (animation.sourceResolution !== animation.targetResolution) {\n return false;\n }\n if (animation.sourceRotation !== animation.targetRotation) {\n return false;\n }\n return true;\n}\n\n/**\n * @param {import(\"./coordinate.js\").Coordinate} coordinate Coordinate.\n * @param {import(\"./size.js\").Size} size Box pixel size.\n * @param {import(\"./pixel.js\").Pixel} position Position on the view to center on.\n * @param {number} resolution Resolution.\n * @param {number} rotation Rotation.\n * @return {import(\"./coordinate.js\").Coordinate} Shifted center.\n */\nfunction calculateCenterOn(coordinate, size, position, resolution, rotation) {\n // calculate rotated position\n const cosAngle = Math.cos(-rotation);\n let sinAngle = Math.sin(-rotation);\n let rotX = coordinate[0] * cosAngle - coordinate[1] * sinAngle;\n let rotY = coordinate[1] * cosAngle + coordinate[0] * sinAngle;\n rotX += (size[0] / 2 - position[0]) * resolution;\n rotY += (position[1] - size[1] / 2) * resolution;\n\n // go back to original angle\n sinAngle = -sinAngle; // go back to original rotation\n const centerX = rotX * cosAngle - rotY * sinAngle;\n const centerY = rotY * cosAngle + rotX * sinAngle;\n\n return [centerX, centerY];\n}\n\nexport default View;\n","/**\n * @module ol/layer/Layer\n */\nimport BaseLayer from './Base.js';\nimport EventType from '../events/EventType.js';\nimport LayerProperty from './Property.js';\nimport RenderEventType from '../render/EventType.js';\nimport View from '../View.js';\nimport {assert} from '../asserts.js';\nimport {intersects} from '../extent.js';\nimport {listen, unlistenByKey} from '../events.js';\n\n/**\n * @typedef {function(import(\"../Map.js\").FrameState):HTMLElement} RenderFunction\n */\n\n/**\n * @typedef {'sourceready'|'change:source'} LayerEventType\n */\n\n/***\n * @template Return\n * @typedef {import(\"../Observable\").OnSignature &\n * import(\"../Observable\").OnSignature &\n * import(\"../Observable\").OnSignature &\n * import(\"../Observable\").CombinedOnSignature} LayerOnSignature\n */\n\n/**\n * @template {import(\"../source/Source.js\").default} [SourceType=import(\"../source/Source.js\").default]\n * @typedef {Object} Options\n * @property {string} [className='ol-layer'] A CSS class name to set to the layer element.\n * @property {number} [opacity=1] Opacity (0, 1).\n * @property {boolean} [visible=true] Visibility.\n * @property {import(\"../extent.js\").Extent} [extent] The bounding extent for layer rendering. The layer will not be\n * rendered outside of this extent.\n * @property {number} [zIndex] The z-index for layer rendering. At rendering time, the layers\n * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed\n * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`\n * method was used.\n * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be\n * visible.\n * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will\n * be visible.\n * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be\n * visible.\n * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will\n * be visible.\n * @property {SourceType} [source] Source for this layer. If not provided to the constructor,\n * the source can be set by calling {@link module:ol/layer/Layer~Layer#setSource layer.setSource(source)} after\n * construction.\n * @property {import(\"../Map.js\").default|null} [map] Map.\n * @property {RenderFunction} [render] Render function. Takes the frame state as input and is expected to return an\n * HTML element. Will overwrite the default rendering for the layer.\n * @property {Object} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.\n */\n\n/**\n * @typedef {Object} State\n * @property {import(\"./Layer.js\").default} layer Layer.\n * @property {number} opacity Opacity, the value is rounded to two digits to appear after the decimal point.\n * @property {boolean} visible Visible.\n * @property {boolean} managed Managed.\n * @property {import(\"../extent.js\").Extent} [extent] Extent.\n * @property {number} zIndex ZIndex.\n * @property {number} maxResolution Maximum resolution.\n * @property {number} minResolution Minimum resolution.\n * @property {number} minZoom Minimum zoom.\n * @property {number} maxZoom Maximum zoom.\n */\n\n/**\n * @classdesc\n * Base class from which all layer types are derived. This should only be instantiated\n * in the case where a custom layer is added to the map with a custom `render` function.\n * Such a function can be specified in the `options` object, and is expected to return an HTML element.\n *\n * A visual representation of raster or vector map data.\n * Layers group together those properties that pertain to how the data is to be\n * displayed, irrespective of the source of that data.\n *\n * Layers are usually added to a map with [map.addLayer()]{@link import(\"../Map.js\").default#addLayer}.\n * Components like {@link module:ol/interaction/Draw~Draw} use unmanaged layers\n * internally. These unmanaged layers are associated with the map using\n * [layer.setMap()]{@link module:ol/layer/Layer~Layer#setMap} instead.\n *\n * A generic `change` event is fired when the state of the source changes.\n * A `sourceready` event is fired when the layer's source is ready.\n *\n * @fires import(\"../render/Event.js\").RenderEvent#prerender\n * @fires import(\"../render/Event.js\").RenderEvent#postrender\n * @fires import(\"../events/Event.js\").BaseEvent#sourceready\n *\n * @template {import(\"../source/Source.js\").default} [SourceType=import(\"../source/Source.js\").default]\n * @template {import(\"../renderer/Layer.js\").default} [RendererType=import(\"../renderer/Layer.js\").default]\n * @api\n */\nclass Layer extends BaseLayer {\n /**\n * @param {Options} options Layer options.\n */\n constructor(options) {\n const baseOptions = Object.assign({}, options);\n delete baseOptions.source;\n\n super(baseOptions);\n\n /***\n * @type {LayerOnSignature}\n */\n this.on;\n\n /***\n * @type {LayerOnSignature}\n */\n this.once;\n\n /***\n * @type {LayerOnSignature}\n */\n this.un;\n\n /**\n * @private\n * @type {?import(\"../events.js\").EventsKey}\n */\n this.mapPrecomposeKey_ = null;\n\n /**\n * @private\n * @type {?import(\"../events.js\").EventsKey}\n */\n this.mapRenderKey_ = null;\n\n /**\n * @private\n * @type {?import(\"../events.js\").EventsKey}\n */\n this.sourceChangeKey_ = null;\n\n /**\n * @private\n * @type {RendererType}\n */\n this.renderer_ = null;\n\n /**\n * @private\n * @type {boolean}\n */\n this.sourceReady_ = false;\n\n /**\n * @protected\n * @type {boolean}\n */\n this.rendered = false;\n\n // Overwrite default render method with a custom one\n if (options.render) {\n this.render = options.render;\n }\n\n if (options.map) {\n this.setMap(options.map);\n }\n\n this.addChangeListener(\n LayerProperty.SOURCE,\n this.handleSourcePropertyChange_\n );\n\n const source = options.source\n ? /** @type {SourceType} */ (options.source)\n : null;\n this.setSource(source);\n }\n\n /**\n * @param {Array} [array] Array of layers (to be modified in place).\n * @return {Array} Array of layers.\n */\n getLayersArray(array) {\n array = array ? array : [];\n array.push(this);\n return array;\n }\n\n /**\n * @param {Array} [states] Optional list of layer states (to be modified in place).\n * @return {Array} List of layer states.\n */\n getLayerStatesArray(states) {\n states = states ? states : [];\n states.push(this.getLayerState());\n return states;\n }\n\n /**\n * Get the layer source.\n * @return {SourceType|null} The layer source (or `null` if not yet set).\n * @observable\n * @api\n */\n getSource() {\n return /** @type {SourceType} */ (this.get(LayerProperty.SOURCE)) || null;\n }\n\n /**\n * @return {SourceType|null} The source being rendered.\n */\n getRenderSource() {\n return this.getSource();\n }\n\n /**\n * @return {import(\"../source/Source.js\").State} Source state.\n */\n getSourceState() {\n const source = this.getSource();\n return !source ? 'undefined' : source.getState();\n }\n\n /**\n * @private\n */\n handleSourceChange_() {\n this.changed();\n if (this.sourceReady_ || this.getSource().getState() !== 'ready') {\n return;\n }\n this.sourceReady_ = true;\n this.dispatchEvent('sourceready');\n }\n\n /**\n * @private\n */\n handleSourcePropertyChange_() {\n if (this.sourceChangeKey_) {\n unlistenByKey(this.sourceChangeKey_);\n this.sourceChangeKey_ = null;\n }\n this.sourceReady_ = false;\n const source = this.getSource();\n if (source) {\n this.sourceChangeKey_ = listen(\n source,\n EventType.CHANGE,\n this.handleSourceChange_,\n this\n );\n if (source.getState() === 'ready') {\n this.sourceReady_ = true;\n setTimeout(() => {\n this.dispatchEvent('sourceready');\n }, 0);\n }\n }\n this.changed();\n }\n\n /**\n * @param {import(\"../pixel\").Pixel} pixel Pixel.\n * @return {Promise>} Promise that resolves with\n * an array of features.\n */\n getFeatures(pixel) {\n if (!this.renderer_) {\n return Promise.resolve([]);\n }\n return this.renderer_.getFeatures(pixel);\n }\n\n /**\n * @param {import(\"../pixel\").Pixel} pixel Pixel.\n * @return {Uint8ClampedArray|Uint8Array|Float32Array|DataView|null} Pixel data.\n */\n getData(pixel) {\n if (!this.renderer_ || !this.rendered) {\n return null;\n }\n return this.renderer_.getData(pixel);\n }\n\n /**\n * The layer is visible on the map view, i.e. within its min/max resolution or zoom and\n * extent, not set to `visible: false`, and not inside a layer group that is set\n * to `visible: false`.\n * @param {View|import(\"../View.js\").ViewStateLayerStateExtent} [view] View or {@link import(\"../Map.js\").FrameState}.\n * Only required when the layer is not added to a map.\n * @return {boolean} The layer is visible in the map view.\n * @api\n */\n isVisible(view) {\n let frameState;\n const map = this.getMapInternal();\n if (!view && map) {\n view = map.getView();\n }\n if (view instanceof View) {\n frameState = {\n viewState: view.getState(),\n extent: view.calculateExtent(),\n };\n } else {\n frameState = view;\n }\n if (!frameState.layerStatesArray && map) {\n frameState.layerStatesArray = map.getLayerGroup().getLayerStatesArray();\n }\n let layerState;\n if (frameState.layerStatesArray) {\n layerState = frameState.layerStatesArray.find(\n (layerState) => layerState.layer === this\n );\n } else {\n layerState = this.getLayerState();\n }\n\n const layerExtent = this.getExtent();\n\n return (\n inView(layerState, frameState.viewState) &&\n (!layerExtent || intersects(layerExtent, frameState.extent))\n );\n }\n\n /**\n * Get the attributions of the source of this layer for the given view.\n * @param {View|import(\"../View.js\").ViewStateLayerStateExtent} [view] View or {@link import(\"../Map.js\").FrameState}.\n * Only required when the layer is not added to a map.\n * @return {Array} Attributions for this layer at the given view.\n * @api\n */\n getAttributions(view) {\n if (!this.isVisible(view)) {\n return [];\n }\n let getAttributions;\n const source = this.getSource();\n if (source) {\n getAttributions = source.getAttributions();\n }\n if (!getAttributions) {\n return [];\n }\n const frameState =\n view instanceof View ? view.getViewStateAndExtent() : view;\n let attributions = getAttributions(frameState);\n if (!Array.isArray(attributions)) {\n attributions = [attributions];\n }\n return attributions;\n }\n\n /**\n * In charge to manage the rendering of the layer. One layer type is\n * bounded with one layer renderer.\n * @param {?import(\"../Map.js\").FrameState} frameState Frame state.\n * @param {HTMLElement} target Target which the renderer may (but need not) use\n * for rendering its content.\n * @return {HTMLElement|null} The rendered element.\n */\n render(frameState, target) {\n const layerRenderer = this.getRenderer();\n\n if (layerRenderer.prepareFrame(frameState)) {\n this.rendered = true;\n return layerRenderer.renderFrame(frameState, target);\n }\n return null;\n }\n\n /**\n * Called when a layer is not visible during a map render.\n */\n unrender() {\n this.rendered = false;\n }\n\n /**\n * For use inside the library only.\n * @param {import(\"../Map.js\").default|null} map Map.\n */\n setMapInternal(map) {\n if (!map) {\n this.unrender();\n }\n this.set(LayerProperty.MAP, map);\n }\n\n /**\n * For use inside the library only.\n * @return {import(\"../Map.js\").default|null} Map.\n */\n getMapInternal() {\n return this.get(LayerProperty.MAP);\n }\n\n /**\n * Sets the layer to be rendered on top of other layers on a map. The map will\n * not manage this layer in its layers collection. This\n * is useful for temporary layers. To remove an unmanaged layer from the map,\n * use `#setMap(null)`.\n *\n * To add the layer to a map and have it managed by the map, use\n * {@link module:ol/Map~Map#addLayer} instead.\n * @param {import(\"../Map.js\").default|null} map Map.\n * @api\n */\n setMap(map) {\n if (this.mapPrecomposeKey_) {\n unlistenByKey(this.mapPrecomposeKey_);\n this.mapPrecomposeKey_ = null;\n }\n if (!map) {\n this.changed();\n }\n if (this.mapRenderKey_) {\n unlistenByKey(this.mapRenderKey_);\n this.mapRenderKey_ = null;\n }\n if (map) {\n this.mapPrecomposeKey_ = listen(\n map,\n RenderEventType.PRECOMPOSE,\n function (evt) {\n const renderEvent =\n /** @type {import(\"../render/Event.js\").default} */ (evt);\n const layerStatesArray = renderEvent.frameState.layerStatesArray;\n const layerState = this.getLayerState(false);\n // A layer can only be added to the map once. Use either `layer.setMap()` or `map.addLayer()`, not both.\n assert(\n !layerStatesArray.some(function (arrayLayerState) {\n return arrayLayerState.layer === layerState.layer;\n }),\n 67\n );\n layerStatesArray.push(layerState);\n },\n this\n );\n this.mapRenderKey_ = listen(this, EventType.CHANGE, map.render, map);\n this.changed();\n }\n }\n\n /**\n * Set the layer source.\n * @param {SourceType|null} source The layer source.\n * @observable\n * @api\n */\n setSource(source) {\n this.set(LayerProperty.SOURCE, source);\n }\n\n /**\n * Get the renderer for this layer.\n * @return {RendererType|null} The layer renderer.\n */\n getRenderer() {\n if (!this.renderer_) {\n this.renderer_ = this.createRenderer();\n }\n return this.renderer_;\n }\n\n /**\n * @return {boolean} The layer has a renderer.\n */\n hasRenderer() {\n return !!this.renderer_;\n }\n\n /**\n * Create a renderer for this layer.\n * @return {RendererType} A layer renderer.\n * @protected\n */\n createRenderer() {\n return null;\n }\n\n /**\n * Clean up.\n */\n disposeInternal() {\n if (this.renderer_) {\n this.renderer_.dispose();\n delete this.renderer_;\n }\n\n this.setSource(null);\n super.disposeInternal();\n }\n}\n\n/**\n * Return `true` if the layer is visible and if the provided view state\n * has resolution and zoom levels that are in range of the layer's min/max.\n * @param {State} layerState Layer state.\n * @param {import(\"../View.js\").State} viewState View state.\n * @return {boolean} The layer is visible at the given view state.\n */\nexport function inView(layerState, viewState) {\n if (!layerState.visible) {\n return false;\n }\n const resolution = viewState.resolution;\n if (\n resolution < layerState.minResolution ||\n resolution >= layerState.maxResolution\n ) {\n return false;\n }\n const zoom = viewState.zoom;\n return zoom > layerState.minZoom && zoom <= layerState.maxZoom;\n}\n\nexport default Layer;\n","/**\n * @module ol/renderer/Map\n */\nimport Disposable from '../Disposable.js';\nimport {TRUE} from '../functions.js';\nimport {abstract} from '../util.js';\nimport {compose as composeTransform, makeInverse} from '../transform.js';\nimport {getWidth} from '../extent.js';\nimport {shared as iconImageCache} from '../style/IconImageCache.js';\nimport {inView} from '../layer/Layer.js';\nimport {wrapX} from '../coordinate.js';\n\n/**\n * @template T\n * @typedef HitMatch\n * @property {import(\"../Feature.js\").FeatureLike} feature Feature.\n * @property {import(\"../layer/Layer.js\").default} layer Layer.\n * @property {import(\"../geom/SimpleGeometry.js\").default} geometry Geometry.\n * @property {number} distanceSq Squared distance.\n * @property {import(\"./vector.js\").FeatureCallback} callback Callback.\n */\n\n/**\n * @abstract\n */\nclass MapRenderer extends Disposable {\n /**\n * @param {import(\"../Map.js\").default} map Map.\n */\n constructor(map) {\n super();\n\n /**\n * @private\n * @type {import(\"../Map.js\").default}\n */\n this.map_ = map;\n }\n\n /**\n * @abstract\n * @param {import(\"../render/EventType.js\").default} type Event type.\n * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n */\n dispatchRenderEvent(type, frameState) {\n abstract();\n }\n\n /**\n * @param {import(\"../Map.js\").FrameState} frameState FrameState.\n * @protected\n */\n calculateMatrices2D(frameState) {\n const viewState = frameState.viewState;\n const coordinateToPixelTransform = frameState.coordinateToPixelTransform;\n const pixelToCoordinateTransform = frameState.pixelToCoordinateTransform;\n\n composeTransform(\n coordinateToPixelTransform,\n frameState.size[0] / 2,\n frameState.size[1] / 2,\n 1 / viewState.resolution,\n -1 / viewState.resolution,\n -viewState.rotation,\n -viewState.center[0],\n -viewState.center[1]\n );\n\n makeInverse(pixelToCoordinateTransform, coordinateToPixelTransform);\n }\n\n /**\n * @param {import(\"../coordinate.js\").Coordinate} coordinate Coordinate.\n * @param {import(\"../Map.js\").FrameState} frameState FrameState.\n * @param {number} hitTolerance Hit tolerance in pixels.\n * @param {boolean} checkWrapped Check for wrapped geometries.\n * @param {import(\"./vector.js\").FeatureCallback} callback Feature callback.\n * @param {S} thisArg Value to use as `this` when executing `callback`.\n * @param {function(this: U, import(\"../layer/Layer.js\").default): boolean} layerFilter Layer filter\n * function, only layers which are visible and for which this function\n * returns `true` will be tested for features. By default, all visible\n * layers will be tested.\n * @param {U} thisArg2 Value to use as `this` when executing `layerFilter`.\n * @return {T|undefined} Callback result.\n * @template S,T,U\n */\n forEachFeatureAtCoordinate(\n coordinate,\n frameState,\n hitTolerance,\n checkWrapped,\n callback,\n thisArg,\n layerFilter,\n thisArg2\n ) {\n let result;\n const viewState = frameState.viewState;\n\n /**\n * @param {boolean} managed Managed layer.\n * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n * @param {import(\"../layer/Layer.js\").default} layer Layer.\n * @param {import(\"../geom/Geometry.js\").default} geometry Geometry.\n * @return {T|undefined} Callback result.\n */\n function forEachFeatureAtCoordinate(managed, feature, layer, geometry) {\n return callback.call(thisArg, feature, managed ? layer : null, geometry);\n }\n\n const projection = viewState.projection;\n\n const translatedCoordinate = wrapX(coordinate.slice(), projection);\n const offsets = [[0, 0]];\n if (projection.canWrapX() && checkWrapped) {\n const projectionExtent = projection.getExtent();\n const worldWidth = getWidth(projectionExtent);\n offsets.push([-worldWidth, 0], [worldWidth, 0]);\n }\n\n const layerStates = frameState.layerStatesArray;\n const numLayers = layerStates.length;\n\n const matches = /** @type {Array>} */ ([]);\n const tmpCoord = [];\n for (let i = 0; i < offsets.length; i++) {\n for (let j = numLayers - 1; j >= 0; --j) {\n const layerState = layerStates[j];\n const layer = layerState.layer;\n if (\n layer.hasRenderer() &&\n inView(layerState, viewState) &&\n layerFilter.call(thisArg2, layer)\n ) {\n const layerRenderer = layer.getRenderer();\n const source = layer.getSource();\n if (layerRenderer && source) {\n const coordinates = source.getWrapX()\n ? translatedCoordinate\n : coordinate;\n const callback = forEachFeatureAtCoordinate.bind(\n null,\n layerState.managed\n );\n tmpCoord[0] = coordinates[0] + offsets[i][0];\n tmpCoord[1] = coordinates[1] + offsets[i][1];\n result = layerRenderer.forEachFeatureAtCoordinate(\n tmpCoord,\n frameState,\n hitTolerance,\n callback,\n matches\n );\n }\n if (result) {\n return result;\n }\n }\n }\n }\n if (matches.length === 0) {\n return undefined;\n }\n const order = 1 / matches.length;\n matches.forEach((m, i) => (m.distanceSq += i * order));\n matches.sort((a, b) => a.distanceSq - b.distanceSq);\n matches.some((m) => {\n return (result = m.callback(m.feature, m.layer, m.geometry));\n });\n return result;\n }\n\n /**\n * @param {import(\"../coordinate.js\").Coordinate} coordinate Coordinate.\n * @param {import(\"../Map.js\").FrameState} frameState FrameState.\n * @param {number} hitTolerance Hit tolerance in pixels.\n * @param {boolean} checkWrapped Check for wrapped geometries.\n * @param {function(this: U, import(\"../layer/Layer.js\").default): boolean} layerFilter Layer filter\n * function, only layers which are visible and for which this function\n * returns `true` will be tested for features. By default, all visible\n * layers will be tested.\n * @param {U} thisArg Value to use as `this` when executing `layerFilter`.\n * @return {boolean} Is there a feature at the given coordinate?\n * @template U\n */\n hasFeatureAtCoordinate(\n coordinate,\n frameState,\n hitTolerance,\n checkWrapped,\n layerFilter,\n thisArg\n ) {\n const hasFeature = this.forEachFeatureAtCoordinate(\n coordinate,\n frameState,\n hitTolerance,\n checkWrapped,\n TRUE,\n this,\n layerFilter,\n thisArg\n );\n\n return hasFeature !== undefined;\n }\n\n /**\n * @return {import(\"../Map.js\").default} Map.\n */\n getMap() {\n return this.map_;\n }\n\n /**\n * Render.\n * @abstract\n * @param {?import(\"../Map.js\").FrameState} frameState Frame state.\n */\n renderFrame(frameState) {\n abstract();\n }\n\n /**\n * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n */\n flushDeclutterItems(frameState) {}\n\n /**\n * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n * @protected\n */\n scheduleExpireIconCache(frameState) {\n if (iconImageCache.canExpireCache()) {\n frameState.postRenderFunctions.push(expireIconCache);\n }\n }\n}\n\n/**\n * @param {import(\"../Map.js\").default} map Map.\n * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n */\nfunction expireIconCache(map, frameState) {\n iconImageCache.expire();\n}\n\nexport default MapRenderer;\n","/**\n * @module ol/render/Event\n */\n\nimport Event from '../events/Event.js';\n\nclass RenderEvent extends Event {\n /**\n * @param {import(\"./EventType.js\").default} type Type.\n * @param {import(\"../transform.js\").Transform} [inversePixelTransform] Transform for\n * CSS pixels to rendered pixels.\n * @param {import(\"../Map.js\").FrameState} [frameState] Frame state.\n * @param {?(CanvasRenderingContext2D|WebGLRenderingContext)} [context] Context.\n */\n constructor(type, inversePixelTransform, frameState, context) {\n super(type);\n\n /**\n * Transform from CSS pixels (relative to the top-left corner of the map viewport)\n * to rendered pixels on this event's `context`. Only available when a Canvas renderer is used, null otherwise.\n * @type {import(\"../transform.js\").Transform|undefined}\n * @api\n */\n this.inversePixelTransform = inversePixelTransform;\n\n /**\n * An object representing the current render frame state.\n * @type {import(\"../Map.js\").FrameState|undefined}\n * @api\n */\n this.frameState = frameState;\n\n /**\n * Canvas context. Not available when the event is dispatched by the map. For Canvas 2D layers,\n * the context will be the 2D rendering context. For WebGL layers, the context will be the WebGL\n * context.\n * @type {CanvasRenderingContext2D|WebGLRenderingContext|undefined}\n * @api\n */\n this.context = context;\n }\n}\n\nexport default RenderEvent;\n","/**\n * @module ol/css\n */\n\n/**\n * @typedef {Object} FontParameters\n * @property {string} style Style.\n * @property {string} variant Variant.\n * @property {string} weight Weight.\n * @property {string} size Size.\n * @property {string} lineHeight LineHeight.\n * @property {string} family Family.\n * @property {Array} families Families.\n */\n\n/**\n * The CSS class for hidden feature.\n *\n * @const\n * @type {string}\n */\nexport const CLASS_HIDDEN = 'ol-hidden';\n\n/**\n * The CSS class that we'll give the DOM elements to have them selectable.\n *\n * @const\n * @type {string}\n */\nexport const CLASS_SELECTABLE = 'ol-selectable';\n\n/**\n * The CSS class that we'll give the DOM elements to have them unselectable.\n *\n * @const\n * @type {string}\n */\nexport const CLASS_UNSELECTABLE = 'ol-unselectable';\n\n/**\n * The CSS class for unsupported feature.\n *\n * @const\n * @type {string}\n */\nexport const CLASS_UNSUPPORTED = 'ol-unsupported';\n\n/**\n * The CSS class for controls.\n *\n * @const\n * @type {string}\n */\nexport const CLASS_CONTROL = 'ol-control';\n\n/**\n * The CSS class that we'll give the DOM elements that are collapsed, i.e.\n * to those elements which usually can be expanded.\n *\n * @const\n * @type {string}\n */\nexport const CLASS_COLLAPSED = 'ol-collapsed';\n\n/**\n * From https://stackoverflow.com/questions/10135697/regex-to-parse-any-css-font\n * @type {RegExp}\n */\nconst fontRegEx = new RegExp(\n [\n '^\\\\s*(?=(?:(?:[-a-z]+\\\\s*){0,2}(italic|oblique))?)',\n '(?=(?:(?:[-a-z]+\\\\s*){0,2}(small-caps))?)',\n '(?=(?:(?:[-a-z]+\\\\s*){0,2}(bold(?:er)?|lighter|[1-9]00 ))?)',\n '(?:(?:normal|\\\\1|\\\\2|\\\\3)\\\\s*){0,3}((?:xx?-)?',\n '(?:small|large)|medium|smaller|larger|[\\\\.\\\\d]+(?:\\\\%|in|[cem]m|ex|p[ctx]))',\n '(?:\\\\s*\\\\/\\\\s*(normal|[\\\\.\\\\d]+(?:\\\\%|in|[cem]m|ex|p[ctx])?))',\n '?\\\\s*([-,\\\\\"\\\\\\'\\\\sa-z]+?)\\\\s*$',\n ].join(''),\n 'i'\n);\nconst fontRegExMatchIndex = [\n 'style',\n 'variant',\n 'weight',\n 'size',\n 'lineHeight',\n 'family',\n];\n\n/**\n * Get the list of font families from a font spec. Note that this doesn't work\n * for font families that have commas in them.\n * @param {string} fontSpec The CSS font property.\n * @return {FontParameters|null} The font parameters (or null if the input spec is invalid).\n */\nexport const getFontParameters = function (fontSpec) {\n const match = fontSpec.match(fontRegEx);\n if (!match) {\n return null;\n }\n const style = /** @type {FontParameters} */ ({\n lineHeight: 'normal',\n size: '1.2em',\n style: 'normal',\n weight: 'normal',\n variant: 'normal',\n });\n for (let i = 0, ii = fontRegExMatchIndex.length; i < ii; ++i) {\n const value = match[i + 1];\n if (value !== undefined) {\n style[fontRegExMatchIndex[i]] = value;\n }\n }\n style.families = style.family.split(/,\\s?/);\n return style;\n};\n","/**\n * @module ol/render/canvas\n */\nimport BaseObject from '../Object.js';\nimport {WORKER_OFFSCREEN_CANVAS} from '../has.js';\nimport {clear} from '../obj.js';\nimport {createCanvasContext2D} from '../dom.js';\nimport {getFontParameters} from '../css.js';\n\n/**\n * @typedef {'Circle' | 'Image' | 'LineString' | 'Polygon' | 'Text' | 'Default'} BuilderType\n */\n\n/**\n * @typedef {Object} FillState\n * @property {import(\"../colorlike.js\").ColorLike} fillStyle FillStyle.\n */\n\n/**\n * @typedef Label\n * @property {number} width Width.\n * @property {number} height Height.\n * @property {Array} contextInstructions ContextInstructions.\n */\n\n/**\n * @typedef {Object} FillStrokeState\n * @property {import(\"../colorlike.js\").ColorLike} [currentFillStyle] Current FillStyle.\n * @property {import(\"../colorlike.js\").ColorLike} [currentStrokeStyle] Current StrokeStyle.\n * @property {CanvasLineCap} [currentLineCap] Current LineCap.\n * @property {Array} currentLineDash Current LineDash.\n * @property {number} [currentLineDashOffset] Current LineDashOffset.\n * @property {CanvasLineJoin} [currentLineJoin] Current LineJoin.\n * @property {number} [currentLineWidth] Current LineWidth.\n * @property {number} [currentMiterLimit] Current MiterLimit.\n * @property {number} [lastStroke] Last stroke.\n * @property {import(\"../colorlike.js\").ColorLike} [fillStyle] FillStyle.\n * @property {import(\"../colorlike.js\").ColorLike} [strokeStyle] StrokeStyle.\n * @property {CanvasLineCap} [lineCap] LineCap.\n * @property {Array} lineDash LineDash.\n * @property {number} [lineDashOffset] LineDashOffset.\n * @property {CanvasLineJoin} [lineJoin] LineJoin.\n * @property {number} [lineWidth] LineWidth.\n * @property {number} [miterLimit] MiterLimit.\n */\n\n/**\n * @typedef {Object} StrokeState\n * @property {CanvasLineCap} lineCap LineCap.\n * @property {Array} lineDash LineDash.\n * @property {number} lineDashOffset LineDashOffset.\n * @property {CanvasLineJoin} lineJoin LineJoin.\n * @property {number} lineWidth LineWidth.\n * @property {number} miterLimit MiterLimit.\n * @property {import(\"../colorlike.js\").ColorLike} strokeStyle StrokeStyle.\n */\n\n/**\n * @typedef {Object} TextState\n * @property {string} font Font.\n * @property {CanvasTextAlign} [textAlign] TextAlign.\n * @property {number} [repeat] Repeat.\n * @property {import(\"../style/Text.js\").TextJustify} [justify] Justify.\n * @property {CanvasTextBaseline} textBaseline TextBaseline.\n * @property {import(\"../style/Text.js\").TextPlacement} [placement] Placement.\n * @property {number} [maxAngle] MaxAngle.\n * @property {boolean} [overflow] Overflow.\n * @property {import(\"../style/Fill.js\").default} [backgroundFill] BackgroundFill.\n * @property {import(\"../style/Stroke.js\").default} [backgroundStroke] BackgroundStroke.\n * @property {import(\"../size.js\").Size} [scale] Scale.\n * @property {Array} [padding] Padding.\n */\n\n/**\n * @typedef {Object} SerializableInstructions\n * @property {Array<*>} instructions The rendering instructions.\n * @property {Array<*>} hitDetectionInstructions The rendering hit detection instructions.\n * @property {Array} coordinates The array of all coordinates.\n * @property {!Object} [textStates] The text states (decluttering).\n * @property {!Object} [fillStates] The fill states (decluttering).\n * @property {!Object} [strokeStates] The stroke states (decluttering).\n */\n\n/**\n * @typedef {Object} DeclutterImageWithText\n */\n\n/**\n * @const\n * @type {string}\n */\nexport const defaultFont = '10px sans-serif';\n\n/**\n * @const\n * @type {string}\n */\nexport const defaultFillStyle = '#000';\n\n/**\n * @const\n * @type {CanvasLineCap}\n */\nexport const defaultLineCap = 'round';\n\n/**\n * @const\n * @type {Array}\n */\nexport const defaultLineDash = [];\n\n/**\n * @const\n * @type {number}\n */\nexport const defaultLineDashOffset = 0;\n\n/**\n * @const\n * @type {CanvasLineJoin}\n */\nexport const defaultLineJoin = 'round';\n\n/**\n * @const\n * @type {number}\n */\nexport const defaultMiterLimit = 10;\n\n/**\n * @const\n * @type {import(\"../colorlike.js\").ColorLike}\n */\nexport const defaultStrokeStyle = '#000';\n\n/**\n * @const\n * @type {CanvasTextAlign}\n */\nexport const defaultTextAlign = 'center';\n\n/**\n * @const\n * @type {CanvasTextBaseline}\n */\nexport const defaultTextBaseline = 'middle';\n\n/**\n * @const\n * @type {Array}\n */\nexport const defaultPadding = [0, 0, 0, 0];\n\n/**\n * @const\n * @type {number}\n */\nexport const defaultLineWidth = 1;\n\n/**\n * @type {BaseObject}\n */\nexport const checkedFonts = new BaseObject();\n\n/**\n * @type {CanvasRenderingContext2D}\n */\nlet measureContext = null;\n\n/**\n * @type {string}\n */\nlet measureFont;\n\n/**\n * @type {!Object}\n */\nexport const textHeights = {};\n\n/**\n * Clears the label cache when a font becomes available.\n * @param {string} fontSpec CSS font spec.\n */\nexport const registerFont = (function () {\n const retries = 100;\n const size = '32px ';\n const referenceFonts = ['monospace', 'serif'];\n const len = referenceFonts.length;\n const text = 'wmytzilWMYTZIL@#/&?$%10\\uF013';\n let interval, referenceWidth;\n\n /**\n * @param {string} fontStyle Css font-style\n * @param {string} fontWeight Css font-weight\n * @param {*} fontFamily Css font-family\n * @return {boolean} Font with style and weight is available\n */\n function isAvailable(fontStyle, fontWeight, fontFamily) {\n let available = true;\n for (let i = 0; i < len; ++i) {\n const referenceFont = referenceFonts[i];\n referenceWidth = measureTextWidth(\n fontStyle + ' ' + fontWeight + ' ' + size + referenceFont,\n text\n );\n if (fontFamily != referenceFont) {\n const width = measureTextWidth(\n fontStyle +\n ' ' +\n fontWeight +\n ' ' +\n size +\n fontFamily +\n ',' +\n referenceFont,\n text\n );\n // If width and referenceWidth are the same, then the fallback was used\n // instead of the font we wanted, so the font is not available.\n available = available && width != referenceWidth;\n }\n }\n if (available) {\n return true;\n }\n return false;\n }\n\n function check() {\n let done = true;\n const fonts = checkedFonts.getKeys();\n for (let i = 0, ii = fonts.length; i < ii; ++i) {\n const font = fonts[i];\n if (checkedFonts.get(font) < retries) {\n if (isAvailable.apply(this, font.split('\\n'))) {\n clear(textHeights);\n // Make sure that loaded fonts are picked up by Safari\n measureContext = null;\n measureFont = undefined;\n checkedFonts.set(font, retries);\n } else {\n checkedFonts.set(font, checkedFonts.get(font) + 1, true);\n done = false;\n }\n }\n }\n if (done) {\n clearInterval(interval);\n interval = undefined;\n }\n }\n\n return function (fontSpec) {\n const font = getFontParameters(fontSpec);\n if (!font) {\n return;\n }\n const families = font.families;\n for (let i = 0, ii = families.length; i < ii; ++i) {\n const family = families[i];\n const key = font.style + '\\n' + font.weight + '\\n' + family;\n if (checkedFonts.get(key) === undefined) {\n checkedFonts.set(key, retries, true);\n if (!isAvailable(font.style, font.weight, family)) {\n checkedFonts.set(key, 0, true);\n if (interval === undefined) {\n interval = setInterval(check, 32);\n }\n }\n }\n }\n };\n})();\n\n/**\n * @param {string} font Font to use for measuring.\n * @return {import(\"../size.js\").Size} Measurement.\n */\nexport const measureTextHeight = (function () {\n /**\n * @type {HTMLDivElement}\n */\n let measureElement;\n return function (fontSpec) {\n let height = textHeights[fontSpec];\n if (height == undefined) {\n if (WORKER_OFFSCREEN_CANVAS) {\n const font = getFontParameters(fontSpec);\n const metrics = measureText(fontSpec, 'Žg');\n const lineHeight = isNaN(Number(font.lineHeight))\n ? 1.2\n : Number(font.lineHeight);\n height =\n lineHeight *\n (metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent);\n } else {\n if (!measureElement) {\n measureElement = document.createElement('div');\n measureElement.innerHTML = 'M';\n measureElement.style.minHeight = '0';\n measureElement.style.maxHeight = 'none';\n measureElement.style.height = 'auto';\n measureElement.style.padding = '0';\n measureElement.style.border = 'none';\n measureElement.style.position = 'absolute';\n measureElement.style.display = 'block';\n measureElement.style.left = '-99999px';\n }\n measureElement.style.font = fontSpec;\n document.body.appendChild(measureElement);\n height = measureElement.offsetHeight;\n document.body.removeChild(measureElement);\n }\n textHeights[fontSpec] = height;\n }\n return height;\n };\n})();\n\n/**\n * @param {string} font Font.\n * @param {string} text Text.\n * @return {TextMetrics} Text metrics.\n */\nfunction measureText(font, text) {\n if (!measureContext) {\n measureContext = createCanvasContext2D(1, 1);\n }\n if (font != measureFont) {\n measureContext.font = font;\n measureFont = measureContext.font;\n }\n return measureContext.measureText(text);\n}\n\n/**\n * @param {string} font Font.\n * @param {string} text Text.\n * @return {number} Width.\n */\nexport function measureTextWidth(font, text) {\n return measureText(font, text).width;\n}\n\n/**\n * Measure text width using a cache.\n * @param {string} font The font.\n * @param {string} text The text to measure.\n * @param {Object} cache A lookup of cached widths by text.\n * @return {number} The text width.\n */\nexport function measureAndCacheTextWidth(font, text, cache) {\n if (text in cache) {\n return cache[text];\n }\n const width = text\n .split('\\n')\n .reduce((prev, curr) => Math.max(prev, measureTextWidth(font, curr)), 0);\n cache[text] = width;\n return width;\n}\n\n/**\n * @param {TextState} baseStyle Base style.\n * @param {Array} chunks Text chunks to measure.\n * @return {{width: number, height: number, widths: Array, heights: Array, lineWidths: Array}}} Text metrics.\n */\nexport function getTextDimensions(baseStyle, chunks) {\n const widths = [];\n const heights = [];\n const lineWidths = [];\n let width = 0;\n let lineWidth = 0;\n let height = 0;\n let lineHeight = 0;\n for (let i = 0, ii = chunks.length; i <= ii; i += 2) {\n const text = chunks[i];\n if (text === '\\n' || i === ii) {\n width = Math.max(width, lineWidth);\n lineWidths.push(lineWidth);\n lineWidth = 0;\n height += lineHeight;\n continue;\n }\n const font = chunks[i + 1] || baseStyle.font;\n const currentWidth = measureTextWidth(font, text);\n widths.push(currentWidth);\n lineWidth += currentWidth;\n const currentHeight = measureTextHeight(font);\n heights.push(currentHeight);\n lineHeight = Math.max(lineHeight, currentHeight);\n }\n return {width, height, widths, heights, lineWidths};\n}\n\n/**\n * @param {CanvasRenderingContext2D} context Context.\n * @param {number} rotation Rotation.\n * @param {number} offsetX X offset.\n * @param {number} offsetY Y offset.\n */\nexport function rotateAtOffset(context, rotation, offsetX, offsetY) {\n if (rotation !== 0) {\n context.translate(offsetX, offsetY);\n context.rotate(rotation);\n context.translate(-offsetX, -offsetY);\n }\n}\n\n/**\n * @param {CanvasRenderingContext2D} context Context.\n * @param {import(\"../transform.js\").Transform|null} transform Transform.\n * @param {number} opacity Opacity.\n * @param {Label|HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} labelOrImage Label.\n * @param {number} originX Origin X.\n * @param {number} originY Origin Y.\n * @param {number} w Width.\n * @param {number} h Height.\n * @param {number} x X.\n * @param {number} y Y.\n * @param {import(\"../size.js\").Size} scale Scale.\n */\nexport function drawImageOrLabel(\n context,\n transform,\n opacity,\n labelOrImage,\n originX,\n originY,\n w,\n h,\n x,\n y,\n scale\n) {\n context.save();\n\n if (opacity !== 1) {\n context.globalAlpha *= opacity;\n }\n if (transform) {\n context.setTransform.apply(context, transform);\n }\n\n if (/** @type {*} */ (labelOrImage).contextInstructions) {\n // label\n context.translate(x, y);\n context.scale(scale[0], scale[1]);\n executeLabelInstructions(/** @type {Label} */ (labelOrImage), context);\n } else if (scale[0] < 0 || scale[1] < 0) {\n // flipped image\n context.translate(x, y);\n context.scale(scale[0], scale[1]);\n context.drawImage(\n /** @type {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} */ (\n labelOrImage\n ),\n originX,\n originY,\n w,\n h,\n 0,\n 0,\n w,\n h\n );\n } else {\n // if image not flipped translate and scale can be avoided\n context.drawImage(\n /** @type {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} */ (\n labelOrImage\n ),\n originX,\n originY,\n w,\n h,\n x,\n y,\n w * scale[0],\n h * scale[1]\n );\n }\n\n context.restore();\n}\n\n/**\n * @param {Label} label Label.\n * @param {CanvasRenderingContext2D} context Context.\n */\nfunction executeLabelInstructions(label, context) {\n const contextInstructions = label.contextInstructions;\n for (let i = 0, ii = contextInstructions.length; i < ii; i += 2) {\n if (Array.isArray(contextInstructions[i + 1])) {\n context[contextInstructions[i]].apply(\n context,\n contextInstructions[i + 1]\n );\n } else {\n context[contextInstructions[i]] = contextInstructions[i + 1];\n }\n }\n}\n","/**\n * @module ol/renderer/Composite\n */\nimport MapRenderer from './Map.js';\nimport ObjectEventType from '../ObjectEventType.js';\nimport RenderEvent from '../render/Event.js';\nimport RenderEventType from '../render/EventType.js';\nimport {CLASS_UNSELECTABLE} from '../css.js';\nimport {checkedFonts} from '../render/canvas.js';\nimport {inView} from '../layer/Layer.js';\nimport {listen, unlistenByKey} from '../events.js';\nimport {replaceChildren} from '../dom.js';\n\n/**\n * @classdesc\n * Canvas map renderer.\n * @api\n */\nclass CompositeMapRenderer extends MapRenderer {\n /**\n * @param {import(\"../Map.js\").default} map Map.\n */\n constructor(map) {\n super(map);\n\n /**\n * @type {import(\"../events.js\").EventsKey}\n */\n this.fontChangeListenerKey_ = listen(\n checkedFonts,\n ObjectEventType.PROPERTYCHANGE,\n map.redrawText.bind(map)\n );\n\n /**\n * @private\n * @type {HTMLDivElement}\n */\n this.element_ = document.createElement('div');\n const style = this.element_.style;\n style.position = 'absolute';\n style.width = '100%';\n style.height = '100%';\n style.zIndex = '0';\n\n this.element_.className = CLASS_UNSELECTABLE + ' ol-layers';\n\n const container = map.getViewport();\n container.insertBefore(this.element_, container.firstChild || null);\n\n /**\n * @private\n * @type {Array}\n */\n this.children_ = [];\n\n /**\n * @private\n * @type {boolean}\n */\n this.renderedVisible_ = true;\n\n /**\n * @type {Array}\n */\n this.declutterLayers_ = [];\n }\n\n /**\n * @param {import(\"../render/EventType.js\").default} type Event type.\n * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n */\n dispatchRenderEvent(type, frameState) {\n const map = this.getMap();\n if (map.hasListener(type)) {\n const event = new RenderEvent(type, undefined, frameState);\n map.dispatchEvent(event);\n }\n }\n\n disposeInternal() {\n unlistenByKey(this.fontChangeListenerKey_);\n this.element_.parentNode.removeChild(this.element_);\n super.disposeInternal();\n }\n\n /**\n * Render.\n * @param {?import(\"../Map.js\").FrameState} frameState Frame state.\n */\n renderFrame(frameState) {\n if (!frameState) {\n if (this.renderedVisible_) {\n this.element_.style.display = 'none';\n this.renderedVisible_ = false;\n }\n return;\n }\n\n this.calculateMatrices2D(frameState);\n this.dispatchRenderEvent(RenderEventType.PRECOMPOSE, frameState);\n\n const layerStatesArray = frameState.layerStatesArray.sort(function (a, b) {\n return a.zIndex - b.zIndex;\n });\n const viewState = frameState.viewState;\n\n this.children_.length = 0;\n\n const declutterLayers = this.declutterLayers_;\n declutterLayers.length = 0;\n\n let previousElement = null;\n for (let i = 0, ii = layerStatesArray.length; i < ii; ++i) {\n const layerState = layerStatesArray[i];\n frameState.layerIndex = i;\n\n const layer = layerState.layer;\n const sourceState = layer.getSourceState();\n if (\n !inView(layerState, viewState) ||\n (sourceState != 'ready' && sourceState != 'undefined')\n ) {\n layer.unrender();\n continue;\n }\n\n const element = layer.render(frameState, previousElement);\n if (!element) {\n continue;\n }\n if (element !== previousElement) {\n this.children_.push(element);\n previousElement = element;\n }\n if ('getDeclutter' in layer) {\n declutterLayers.push(\n /** @type {import(\"../layer/BaseVector.js\").default} */ (layer)\n );\n }\n }\n this.flushDeclutterItems(frameState);\n\n replaceChildren(this.element_, this.children_);\n\n this.dispatchRenderEvent(RenderEventType.POSTCOMPOSE, frameState);\n\n if (!this.renderedVisible_) {\n this.element_.style.display = '';\n this.renderedVisible_ = true;\n }\n\n this.scheduleExpireIconCache(frameState);\n }\n\n /**\n * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n */\n flushDeclutterItems(frameState) {\n const layers = this.declutterLayers_;\n for (let i = layers.length - 1; i >= 0; --i) {\n layers[i].renderDeclutter(frameState);\n }\n frameState.declutterTree = null;\n layers.length = 0;\n }\n}\n\nexport default CompositeMapRenderer;\n","/**\n * @module ol/layer/Group\n */\nimport BaseLayer from './Base.js';\nimport Collection from '../Collection.js';\nimport CollectionEventType from '../CollectionEventType.js';\nimport Event from '../events/Event.js';\nimport EventType from '../events/EventType.js';\nimport ObjectEventType from '../ObjectEventType.js';\nimport {assert} from '../asserts.js';\nimport {clear} from '../obj.js';\nimport {getIntersection} from '../extent.js';\nimport {getUid} from '../util.js';\nimport {listen, unlistenByKey} from '../events.js';\n\n/**\n * @typedef {'addlayer'|'removelayer'} EventType\n */\n\n/**\n * @classdesc\n * A layer group triggers 'addlayer' and 'removelayer' events when layers are added to or removed from\n * the group or one of its child groups. When a layer group is added to or removed from another layer group,\n * a single event will be triggered (instead of one per layer in the group added or removed).\n */\nexport class GroupEvent extends Event {\n /**\n * @param {EventType} type The event type.\n * @param {BaseLayer} layer The layer.\n */\n constructor(type, layer) {\n super(type);\n\n /**\n * The added or removed layer.\n * @type {BaseLayer}\n * @api\n */\n this.layer = layer;\n }\n}\n\n/***\n * @template Return\n * @typedef {import(\"../Observable\").OnSignature &\n * import(\"../Observable\").OnSignature &\n * import(\"../Observable\").CombinedOnSignature} GroupOnSignature\n */\n\n/**\n * @typedef {Object} Options\n * @property {number} [opacity=1] Opacity (0, 1).\n * @property {boolean} [visible=true] Visibility.\n * @property {import(\"../extent.js\").Extent} [extent] The bounding extent for layer rendering. The layer will not be\n * rendered outside of this extent.\n * @property {number} [zIndex] The z-index for layer rendering. At rendering time, the layers\n * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed\n * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`\n * method was used.\n * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be\n * visible.\n * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will\n * be visible.\n * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be\n * visible.\n * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will\n * be visible.\n * @property {Array|Collection} [layers] Child layers.\n * @property {Object} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.\n */\n\n/**\n * @enum {string}\n * @private\n */\nconst Property = {\n LAYERS: 'layers',\n};\n\n/**\n * @classdesc\n * A {@link module:ol/Collection~Collection} of layers that are handled together.\n *\n * A generic `change` event is triggered when the group/Collection changes.\n *\n * @api\n */\nclass LayerGroup extends BaseLayer {\n /**\n * @param {Options} [options] Layer options.\n */\n constructor(options) {\n options = options || {};\n const baseOptions = /** @type {Options} */ (Object.assign({}, options));\n delete baseOptions.layers;\n\n let layers = options.layers;\n\n super(baseOptions);\n\n /***\n * @type {GroupOnSignature}\n */\n this.on;\n\n /***\n * @type {GroupOnSignature}\n */\n this.once;\n\n /***\n * @type {GroupOnSignature}\n */\n this.un;\n\n /**\n * @private\n * @type {Array}\n */\n this.layersListenerKeys_ = [];\n\n /**\n * @private\n * @type {Object>}\n */\n this.listenerKeys_ = {};\n\n this.addChangeListener(Property.LAYERS, this.handleLayersChanged_);\n\n if (layers) {\n if (Array.isArray(layers)) {\n layers = new Collection(layers.slice(), {unique: true});\n } else {\n assert(typeof (/** @type {?} */ (layers).getArray) === 'function', 43); // Expected `layers` to be an array or a `Collection`\n }\n } else {\n layers = new Collection(undefined, {unique: true});\n }\n\n this.setLayers(layers);\n }\n\n /**\n * @private\n */\n handleLayerChange_() {\n this.changed();\n }\n\n /**\n * @private\n */\n handleLayersChanged_() {\n this.layersListenerKeys_.forEach(unlistenByKey);\n this.layersListenerKeys_.length = 0;\n\n const layers = this.getLayers();\n this.layersListenerKeys_.push(\n listen(layers, CollectionEventType.ADD, this.handleLayersAdd_, this),\n listen(layers, CollectionEventType.REMOVE, this.handleLayersRemove_, this)\n );\n\n for (const id in this.listenerKeys_) {\n this.listenerKeys_[id].forEach(unlistenByKey);\n }\n clear(this.listenerKeys_);\n\n const layersArray = layers.getArray();\n for (let i = 0, ii = layersArray.length; i < ii; i++) {\n const layer = layersArray[i];\n this.registerLayerListeners_(layer);\n this.dispatchEvent(new GroupEvent('addlayer', layer));\n }\n this.changed();\n }\n\n /**\n * @param {BaseLayer} layer The layer.\n */\n registerLayerListeners_(layer) {\n const listenerKeys = [\n listen(\n layer,\n ObjectEventType.PROPERTYCHANGE,\n this.handleLayerChange_,\n this\n ),\n listen(layer, EventType.CHANGE, this.handleLayerChange_, this),\n ];\n\n if (layer instanceof LayerGroup) {\n listenerKeys.push(\n listen(layer, 'addlayer', this.handleLayerGroupAdd_, this),\n listen(layer, 'removelayer', this.handleLayerGroupRemove_, this)\n );\n }\n\n this.listenerKeys_[getUid(layer)] = listenerKeys;\n }\n\n /**\n * @param {GroupEvent} event The layer group event.\n */\n handleLayerGroupAdd_(event) {\n this.dispatchEvent(new GroupEvent('addlayer', event.layer));\n }\n\n /**\n * @param {GroupEvent} event The layer group event.\n */\n handleLayerGroupRemove_(event) {\n this.dispatchEvent(new GroupEvent('removelayer', event.layer));\n }\n\n /**\n * @param {import(\"../Collection.js\").CollectionEvent} collectionEvent CollectionEvent.\n * @private\n */\n handleLayersAdd_(collectionEvent) {\n const layer = collectionEvent.element;\n this.registerLayerListeners_(layer);\n this.dispatchEvent(new GroupEvent('addlayer', layer));\n this.changed();\n }\n\n /**\n * @param {import(\"../Collection.js\").CollectionEvent} collectionEvent CollectionEvent.\n * @private\n */\n handleLayersRemove_(collectionEvent) {\n const layer = collectionEvent.element;\n const key = getUid(layer);\n this.listenerKeys_[key].forEach(unlistenByKey);\n delete this.listenerKeys_[key];\n this.dispatchEvent(new GroupEvent('removelayer', layer));\n this.changed();\n }\n\n /**\n * Returns the {@link module:ol/Collection~Collection collection} of {@link module:ol/layer/Layer~Layer layers}\n * in this group.\n * @return {!Collection} Collection of\n * {@link module:ol/layer/Base~BaseLayer layers} that are part of this group.\n * @observable\n * @api\n */\n getLayers() {\n return /** @type {!Collection} */ (\n this.get(Property.LAYERS)\n );\n }\n\n /**\n * Set the {@link module:ol/Collection~Collection collection} of {@link module:ol/layer/Layer~Layer layers}\n * in this group.\n * @param {!Collection} layers Collection of\n * {@link module:ol/layer/Base~BaseLayer layers} that are part of this group.\n * @observable\n * @api\n */\n setLayers(layers) {\n const collection = this.getLayers();\n if (collection) {\n const currentLayers = collection.getArray();\n for (let i = 0, ii = currentLayers.length; i < ii; ++i) {\n this.dispatchEvent(new GroupEvent('removelayer', currentLayers[i]));\n }\n }\n\n this.set(Property.LAYERS, layers);\n }\n\n /**\n * @param {Array} [array] Array of layers (to be modified in place).\n * @return {Array} Array of layers.\n */\n getLayersArray(array) {\n array = array !== undefined ? array : [];\n this.getLayers().forEach(function (layer) {\n layer.getLayersArray(array);\n });\n return array;\n }\n\n /**\n * Get the layer states list and use this groups z-index as the default\n * for all layers in this and nested groups, if it is unset at this point.\n * If dest is not provided and this group's z-index is undefined\n * 0 is used a the default z-index.\n * @param {Array} [dest] Optional list\n * of layer states (to be modified in place).\n * @return {Array} List of layer states.\n */\n getLayerStatesArray(dest) {\n const states = dest !== undefined ? dest : [];\n const pos = states.length;\n\n this.getLayers().forEach(function (layer) {\n layer.getLayerStatesArray(states);\n });\n\n const ownLayerState = this.getLayerState();\n let defaultZIndex = ownLayerState.zIndex;\n if (!dest && ownLayerState.zIndex === undefined) {\n defaultZIndex = 0;\n }\n for (let i = pos, ii = states.length; i < ii; i++) {\n const layerState = states[i];\n layerState.opacity *= ownLayerState.opacity;\n layerState.visible = layerState.visible && ownLayerState.visible;\n layerState.maxResolution = Math.min(\n layerState.maxResolution,\n ownLayerState.maxResolution\n );\n layerState.minResolution = Math.max(\n layerState.minResolution,\n ownLayerState.minResolution\n );\n layerState.minZoom = Math.max(layerState.minZoom, ownLayerState.minZoom);\n layerState.maxZoom = Math.min(layerState.maxZoom, ownLayerState.maxZoom);\n if (ownLayerState.extent !== undefined) {\n if (layerState.extent !== undefined) {\n layerState.extent = getIntersection(\n layerState.extent,\n ownLayerState.extent\n );\n } else {\n layerState.extent = ownLayerState.extent;\n }\n }\n if (layerState.zIndex === undefined) {\n layerState.zIndex = defaultZIndex;\n }\n }\n\n return states;\n }\n\n /**\n * @return {import(\"../source/Source.js\").State} Source state.\n */\n getSourceState() {\n return 'ready';\n }\n}\n\nexport default LayerGroup;\n","/**\n * @module ol/MapEvent\n */\nimport Event from './events/Event.js';\n\n/**\n * @classdesc\n * Events emitted as map events are instances of this type.\n * See {@link module:ol/Map~Map} for which events trigger a map event.\n */\nclass MapEvent extends Event {\n /**\n * @param {string} type Event type.\n * @param {import(\"./Map.js\").default} map Map.\n * @param {?import(\"./Map.js\").FrameState} [frameState] Frame state.\n */\n constructor(type, map, frameState) {\n super(type);\n\n /**\n * The map where the event occurred.\n * @type {import(\"./Map.js\").default}\n * @api\n */\n this.map = map;\n\n /**\n * The frame state at the time of the event.\n * @type {?import(\"./Map.js\").FrameState}\n * @api\n */\n this.frameState = frameState !== undefined ? frameState : null;\n }\n}\n\nexport default MapEvent;\n","/**\n * @module ol/MapBrowserEvent\n */\nimport MapEvent from './MapEvent.js';\n\n/**\n * @classdesc\n * Events emitted as map browser events are instances of this type.\n * See {@link module:ol/Map~Map} for which events trigger a map browser event.\n * @template {UIEvent} EVENT\n */\nclass MapBrowserEvent extends MapEvent {\n /**\n * @param {string} type Event type.\n * @param {import(\"./Map.js\").default} map Map.\n * @param {EVENT} originalEvent Original event.\n * @param {boolean} [dragging] Is the map currently being dragged?\n * @param {import(\"./Map.js\").FrameState} [frameState] Frame state.\n * @param {Array} [activePointers] Active pointers.\n */\n constructor(type, map, originalEvent, dragging, frameState, activePointers) {\n super(type, map, frameState);\n\n /**\n * The original browser event.\n * @const\n * @type {EVENT}\n * @api\n */\n this.originalEvent = originalEvent;\n\n /**\n * The map pixel relative to the viewport corresponding to the original browser event.\n * @type {?import(\"./pixel.js\").Pixel}\n */\n this.pixel_ = null;\n\n /**\n * The coordinate in the user projection corresponding to the original browser event.\n * @type {?import(\"./coordinate.js\").Coordinate}\n */\n this.coordinate_ = null;\n\n /**\n * Indicates if the map is currently being dragged. Only set for\n * `POINTERDRAG` and `POINTERMOVE` events. Default is `false`.\n *\n * @type {boolean}\n * @api\n */\n this.dragging = dragging !== undefined ? dragging : false;\n\n /**\n * @type {Array|undefined}\n */\n this.activePointers = activePointers;\n }\n\n /**\n * The map pixel relative to the viewport corresponding to the original event.\n * @type {import(\"./pixel.js\").Pixel}\n * @api\n */\n get pixel() {\n if (!this.pixel_) {\n this.pixel_ = this.map.getEventPixel(this.originalEvent);\n }\n return this.pixel_;\n }\n set pixel(pixel) {\n this.pixel_ = pixel;\n }\n\n /**\n * The coordinate corresponding to the original browser event. This will be in the user\n * projection if one is set. Otherwise it will be in the view projection.\n * @type {import(\"./coordinate.js\").Coordinate}\n * @api\n */\n get coordinate() {\n if (!this.coordinate_) {\n this.coordinate_ = this.map.getCoordinateFromPixel(this.pixel);\n }\n return this.coordinate_;\n }\n set coordinate(coordinate) {\n this.coordinate_ = coordinate;\n }\n\n /**\n * Prevents the default browser action.\n * See https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault.\n * @api\n */\n preventDefault() {\n super.preventDefault();\n if ('preventDefault' in this.originalEvent) {\n /** @type {UIEvent} */ (this.originalEvent).preventDefault();\n }\n }\n\n /**\n * Prevents further propagation of the current event.\n * See https://developer.mozilla.org/en-US/docs/Web/API/event.stopPropagation.\n * @api\n */\n stopPropagation() {\n super.stopPropagation();\n if ('stopPropagation' in this.originalEvent) {\n /** @type {UIEvent} */ (this.originalEvent).stopPropagation();\n }\n }\n}\n\nexport default MapBrowserEvent;\n","/**\n * @module ol/MapBrowserEventType\n */\nimport EventType from './events/EventType.js';\n\n/**\n * Constants for event names.\n * @enum {string}\n */\nexport default {\n /**\n * A true single click with no dragging and no double click. Note that this\n * event is delayed by 250 ms to ensure that it is not a double click.\n * @event module:ol/MapBrowserEvent~MapBrowserEvent#singleclick\n * @api\n */\n SINGLECLICK: 'singleclick',\n\n /**\n * A click with no dragging. A double click will fire two of this.\n * @event module:ol/MapBrowserEvent~MapBrowserEvent#click\n * @api\n */\n CLICK: EventType.CLICK,\n\n /**\n * A true double click, with no dragging.\n * @event module:ol/MapBrowserEvent~MapBrowserEvent#dblclick\n * @api\n */\n DBLCLICK: EventType.DBLCLICK,\n\n /**\n * Triggered when a pointer is dragged.\n * @event module:ol/MapBrowserEvent~MapBrowserEvent#pointerdrag\n * @api\n */\n POINTERDRAG: 'pointerdrag',\n\n /**\n * Triggered when a pointer is moved. Note that on touch devices this is\n * triggered when the map is panned, so is not the same as mousemove.\n * @event module:ol/MapBrowserEvent~MapBrowserEvent#pointermove\n * @api\n */\n POINTERMOVE: 'pointermove',\n\n POINTERDOWN: 'pointerdown',\n POINTERUP: 'pointerup',\n POINTEROVER: 'pointerover',\n POINTEROUT: 'pointerout',\n POINTERENTER: 'pointerenter',\n POINTERLEAVE: 'pointerleave',\n POINTERCANCEL: 'pointercancel',\n};\n\n/***\n * @typedef {'singleclick'|'click'|'dblclick'|'pointerdrag'|'pointermove'} Types\n */\n","/**\n * @module ol/pointer/EventType\n */\n\n/**\n * Constants for event names.\n * @enum {string}\n */\nexport default {\n POINTERMOVE: 'pointermove',\n POINTERDOWN: 'pointerdown',\n POINTERUP: 'pointerup',\n POINTEROVER: 'pointerover',\n POINTEROUT: 'pointerout',\n POINTERENTER: 'pointerenter',\n POINTERLEAVE: 'pointerleave',\n POINTERCANCEL: 'pointercancel',\n};\n","/**\n * @module ol/MapBrowserEventHandler\n */\n\nimport EventType from './events/EventType.js';\nimport MapBrowserEvent from './MapBrowserEvent.js';\nimport MapBrowserEventType from './MapBrowserEventType.js';\nimport PointerEventType from './pointer/EventType.js';\nimport Target from './events/Target.js';\nimport {PASSIVE_EVENT_LISTENERS} from './has.js';\nimport {listen, unlistenByKey} from './events.js';\n\nclass MapBrowserEventHandler extends Target {\n /**\n * @param {import(\"./Map.js\").default} map The map with the viewport to listen to events on.\n * @param {number} [moveTolerance] The minimal distance the pointer must travel to trigger a move.\n */\n constructor(map, moveTolerance) {\n super(map);\n\n /**\n * This is the element that we will listen to the real events on.\n * @type {import(\"./Map.js\").default}\n * @private\n */\n this.map_ = map;\n\n /**\n * @type {ReturnType}\n * @private\n */\n this.clickTimeoutId_;\n\n /**\n * Emulate dblclick and singleclick. Will be true when only one pointer is active.\n * @type {boolean}\n */\n this.emulateClicks_ = false;\n\n /**\n * @type {boolean}\n * @private\n */\n this.dragging_ = false;\n\n /**\n * @type {!Array}\n * @private\n */\n this.dragListenerKeys_ = [];\n\n /**\n * @type {number}\n * @private\n */\n this.moveTolerance_ = moveTolerance === undefined ? 1 : moveTolerance;\n\n /**\n * The most recent \"down\" type event (or null if none have occurred).\n * Set on pointerdown.\n * @type {PointerEvent|null}\n * @private\n */\n this.down_ = null;\n\n const element = this.map_.getViewport();\n\n /**\n * @type {Array}\n * @private\n */\n this.activePointers_ = [];\n\n /**\n * @type {!Object}\n * @private\n */\n this.trackedTouches_ = {};\n\n this.element_ = element;\n\n /**\n * @type {?import(\"./events.js\").EventsKey}\n * @private\n */\n this.pointerdownListenerKey_ = listen(\n element,\n PointerEventType.POINTERDOWN,\n this.handlePointerDown_,\n this\n );\n\n /**\n * @type {PointerEvent}\n * @private\n */\n this.originalPointerMoveEvent_;\n\n /**\n * @type {?import(\"./events.js\").EventsKey}\n * @private\n */\n this.relayedListenerKey_ = listen(\n element,\n PointerEventType.POINTERMOVE,\n this.relayMoveEvent_,\n this\n );\n\n /**\n * @private\n */\n this.boundHandleTouchMove_ = this.handleTouchMove_.bind(this);\n\n this.element_.addEventListener(\n EventType.TOUCHMOVE,\n this.boundHandleTouchMove_,\n PASSIVE_EVENT_LISTENERS ? {passive: false} : false\n );\n }\n\n /**\n * @param {PointerEvent} pointerEvent Pointer\n * event.\n * @private\n */\n emulateClick_(pointerEvent) {\n let newEvent = new MapBrowserEvent(\n MapBrowserEventType.CLICK,\n this.map_,\n pointerEvent\n );\n this.dispatchEvent(newEvent);\n if (this.clickTimeoutId_ !== undefined) {\n // double-click\n clearTimeout(this.clickTimeoutId_);\n this.clickTimeoutId_ = undefined;\n newEvent = new MapBrowserEvent(\n MapBrowserEventType.DBLCLICK,\n this.map_,\n pointerEvent\n );\n this.dispatchEvent(newEvent);\n } else {\n // click\n this.clickTimeoutId_ = setTimeout(() => {\n this.clickTimeoutId_ = undefined;\n const newEvent = new MapBrowserEvent(\n MapBrowserEventType.SINGLECLICK,\n this.map_,\n pointerEvent\n );\n this.dispatchEvent(newEvent);\n }, 250);\n }\n }\n\n /**\n * Keeps track on how many pointers are currently active.\n *\n * @param {PointerEvent} pointerEvent Pointer\n * event.\n * @private\n */\n updateActivePointers_(pointerEvent) {\n const event = pointerEvent;\n const id = event.pointerId;\n\n if (\n event.type == MapBrowserEventType.POINTERUP ||\n event.type == MapBrowserEventType.POINTERCANCEL\n ) {\n delete this.trackedTouches_[id];\n for (const pointerId in this.trackedTouches_) {\n if (this.trackedTouches_[pointerId].target !== event.target) {\n // Some platforms assign a new pointerId when the target changes.\n // If this happens, delete one tracked pointer. If there is more\n // than one tracked pointer for the old target, it will be cleared\n // by subsequent POINTERUP events from other pointers.\n delete this.trackedTouches_[pointerId];\n break;\n }\n }\n } else if (\n event.type == MapBrowserEventType.POINTERDOWN ||\n event.type == MapBrowserEventType.POINTERMOVE\n ) {\n this.trackedTouches_[id] = event;\n }\n this.activePointers_ = Object.values(this.trackedTouches_);\n }\n\n /**\n * @param {PointerEvent} pointerEvent Pointer\n * event.\n * @private\n */\n handlePointerUp_(pointerEvent) {\n this.updateActivePointers_(pointerEvent);\n const newEvent = new MapBrowserEvent(\n MapBrowserEventType.POINTERUP,\n this.map_,\n pointerEvent,\n undefined,\n undefined,\n this.activePointers_\n );\n this.dispatchEvent(newEvent);\n\n // We emulate click events on left mouse button click, touch contact, and pen\n // contact. isMouseActionButton returns true in these cases (evt.button is set\n // to 0).\n // See http://www.w3.org/TR/pointerevents/#button-states\n // We only fire click, singleclick, and doubleclick if nobody has called\n // event.preventDefault().\n if (\n this.emulateClicks_ &&\n !newEvent.defaultPrevented &&\n !this.dragging_ &&\n this.isMouseActionButton_(pointerEvent)\n ) {\n this.emulateClick_(this.down_);\n }\n\n if (this.activePointers_.length === 0) {\n this.dragListenerKeys_.forEach(unlistenByKey);\n this.dragListenerKeys_.length = 0;\n this.dragging_ = false;\n this.down_ = null;\n }\n }\n\n /**\n * @param {PointerEvent} pointerEvent Pointer\n * event.\n * @return {boolean} If the left mouse button was pressed.\n * @private\n */\n isMouseActionButton_(pointerEvent) {\n return pointerEvent.button === 0;\n }\n\n /**\n * @param {PointerEvent} pointerEvent Pointer\n * event.\n * @private\n */\n handlePointerDown_(pointerEvent) {\n this.emulateClicks_ = this.activePointers_.length === 0;\n this.updateActivePointers_(pointerEvent);\n const newEvent = new MapBrowserEvent(\n MapBrowserEventType.POINTERDOWN,\n this.map_,\n pointerEvent,\n undefined,\n undefined,\n this.activePointers_\n );\n this.dispatchEvent(newEvent);\n\n this.down_ = new PointerEvent(pointerEvent.type, pointerEvent);\n Object.defineProperty(this.down_, 'target', {\n writable: false,\n value: pointerEvent.target,\n });\n\n if (this.dragListenerKeys_.length === 0) {\n const doc = this.map_.getOwnerDocument();\n this.dragListenerKeys_.push(\n listen(\n doc,\n MapBrowserEventType.POINTERMOVE,\n this.handlePointerMove_,\n this\n ),\n listen(doc, MapBrowserEventType.POINTERUP, this.handlePointerUp_, this),\n /* Note that the listener for `pointercancel is set up on\n * `pointerEventHandler_` and not `documentPointerEventHandler_` like\n * the `pointerup` and `pointermove` listeners.\n *\n * The reason for this is the following: `TouchSource.vacuumTouches_()`\n * issues `pointercancel` events, when there was no `touchend` for a\n * `touchstart`. Now, let's say a first `touchstart` is registered on\n * `pointerEventHandler_`. The `documentPointerEventHandler_` is set up.\n * But `documentPointerEventHandler_` doesn't know about the first\n * `touchstart`. If there is no `touchend` for the `touchstart`, we can\n * only receive a `touchcancel` from `pointerEventHandler_`, because it is\n * only registered there.\n */\n listen(\n this.element_,\n MapBrowserEventType.POINTERCANCEL,\n this.handlePointerUp_,\n this\n )\n );\n if (this.element_.getRootNode && this.element_.getRootNode() !== doc) {\n this.dragListenerKeys_.push(\n listen(\n this.element_.getRootNode(),\n MapBrowserEventType.POINTERUP,\n this.handlePointerUp_,\n this\n )\n );\n }\n }\n }\n\n /**\n * @param {PointerEvent} pointerEvent Pointer\n * event.\n * @private\n */\n handlePointerMove_(pointerEvent) {\n // Between pointerdown and pointerup, pointermove events are triggered.\n // To avoid a 'false' touchmove event to be dispatched, we test if the pointer\n // moved a significant distance.\n if (this.isMoving_(pointerEvent)) {\n this.updateActivePointers_(pointerEvent);\n this.dragging_ = true;\n const newEvent = new MapBrowserEvent(\n MapBrowserEventType.POINTERDRAG,\n this.map_,\n pointerEvent,\n this.dragging_,\n undefined,\n this.activePointers_\n );\n this.dispatchEvent(newEvent);\n }\n }\n\n /**\n * Wrap and relay a pointermove event.\n * @param {PointerEvent} pointerEvent Pointer\n * event.\n * @private\n */\n relayMoveEvent_(pointerEvent) {\n this.originalPointerMoveEvent_ = pointerEvent;\n const dragging = !!(this.down_ && this.isMoving_(pointerEvent));\n this.dispatchEvent(\n new MapBrowserEvent(\n MapBrowserEventType.POINTERMOVE,\n this.map_,\n pointerEvent,\n dragging\n )\n );\n }\n\n /**\n * Flexible handling of a `touch-action: none` css equivalent: because calling\n * `preventDefault()` on a `pointermove` event does not stop native page scrolling\n * and zooming, we also listen for `touchmove` and call `preventDefault()` on it\n * when an interaction (currently `DragPan` handles the event.\n * @param {TouchEvent} event Event.\n * @private\n */\n handleTouchMove_(event) {\n // Due to https://github.com/mpizenberg/elm-pep/issues/2, `this.originalPointerMoveEvent_`\n // may not be initialized yet when we get here on a platform without native pointer events,\n // when elm-pep is used as pointer events polyfill.\n const originalEvent = this.originalPointerMoveEvent_;\n if (\n (!originalEvent || originalEvent.defaultPrevented) &&\n (typeof event.cancelable !== 'boolean' || event.cancelable === true)\n ) {\n event.preventDefault();\n }\n }\n\n /**\n * @param {PointerEvent} pointerEvent Pointer\n * event.\n * @return {boolean} Is moving.\n * @private\n */\n isMoving_(pointerEvent) {\n return (\n this.dragging_ ||\n Math.abs(pointerEvent.clientX - this.down_.clientX) >\n this.moveTolerance_ ||\n Math.abs(pointerEvent.clientY - this.down_.clientY) > this.moveTolerance_\n );\n }\n\n /**\n * Clean up.\n */\n disposeInternal() {\n if (this.relayedListenerKey_) {\n unlistenByKey(this.relayedListenerKey_);\n this.relayedListenerKey_ = null;\n }\n this.element_.removeEventListener(\n EventType.TOUCHMOVE,\n this.boundHandleTouchMove_\n );\n\n if (this.pointerdownListenerKey_) {\n unlistenByKey(this.pointerdownListenerKey_);\n this.pointerdownListenerKey_ = null;\n }\n\n this.dragListenerKeys_.forEach(unlistenByKey);\n this.dragListenerKeys_.length = 0;\n\n this.element_ = null;\n super.disposeInternal();\n }\n}\n\nexport default MapBrowserEventHandler;\n","/**\n * @module ol/MapEventType\n */\n\n/**\n * @enum {string}\n */\nexport default {\n /**\n * Triggered after a map frame is rendered.\n * @event module:ol/MapEvent~MapEvent#postrender\n * @api\n */\n POSTRENDER: 'postrender',\n\n /**\n * Triggered when the map starts moving.\n * @event module:ol/MapEvent~MapEvent#movestart\n * @api\n */\n MOVESTART: 'movestart',\n\n /**\n * Triggered after the map is moved.\n * @event module:ol/MapEvent~MapEvent#moveend\n * @api\n */\n MOVEEND: 'moveend',\n\n /**\n * Triggered when loading of additional map data (tiles, images, features) starts.\n * @event module:ol/MapEvent~MapEvent#loadstart\n * @api\n */\n LOADSTART: 'loadstart',\n\n /**\n * Triggered when loading of additional map data has completed.\n * @event module:ol/MapEvent~MapEvent#loadend\n * @api\n */\n LOADEND: 'loadend',\n};\n\n/***\n * @typedef {'postrender'|'movestart'|'moveend'|'loadstart'|'loadend'} Types\n */\n","/**\n * @module ol/MapProperty\n */\n\n/**\n * @enum {string}\n */\nexport default {\n LAYERGROUP: 'layergroup',\n SIZE: 'size',\n TARGET: 'target',\n VIEW: 'view',\n};\n","/**\n * @module ol/structs/PriorityQueue\n */\nimport {assert} from '../asserts.js';\nimport {clear} from '../obj.js';\n\n/**\n * @type {number}\n */\nexport const DROP = Infinity;\n\n/**\n * @classdesc\n * Priority queue.\n *\n * The implementation is inspired from the Closure Library's Heap class and\n * Python's heapq module.\n *\n * See https://github.com/google/closure-library/blob/master/closure/goog/structs/heap.js\n * and https://hg.python.org/cpython/file/2.7/Lib/heapq.py.\n *\n * @template T\n */\nclass PriorityQueue {\n /**\n * @param {function(T): number} priorityFunction Priority function.\n * @param {function(T): string} keyFunction Key function.\n */\n constructor(priorityFunction, keyFunction) {\n /**\n * @type {function(T): number}\n * @private\n */\n this.priorityFunction_ = priorityFunction;\n\n /**\n * @type {function(T): string}\n * @private\n */\n this.keyFunction_ = keyFunction;\n\n /**\n * @type {Array}\n * @private\n */\n this.elements_ = [];\n\n /**\n * @type {Array}\n * @private\n */\n this.priorities_ = [];\n\n /**\n * @type {!Object}\n * @private\n */\n this.queuedElements_ = {};\n }\n\n /**\n * FIXME empty description for jsdoc\n */\n clear() {\n this.elements_.length = 0;\n this.priorities_.length = 0;\n clear(this.queuedElements_);\n }\n\n /**\n * Remove and return the highest-priority element. O(log N).\n * @return {T} Element.\n */\n dequeue() {\n const elements = this.elements_;\n const priorities = this.priorities_;\n const element = elements[0];\n if (elements.length == 1) {\n elements.length = 0;\n priorities.length = 0;\n } else {\n elements[0] = elements.pop();\n priorities[0] = priorities.pop();\n this.siftUp_(0);\n }\n const elementKey = this.keyFunction_(element);\n delete this.queuedElements_[elementKey];\n return element;\n }\n\n /**\n * Enqueue an element. O(log N).\n * @param {T} element Element.\n * @return {boolean} The element was added to the queue.\n */\n enqueue(element) {\n assert(!(this.keyFunction_(element) in this.queuedElements_), 31); // Tried to enqueue an `element` that was already added to the queue\n const priority = this.priorityFunction_(element);\n if (priority != DROP) {\n this.elements_.push(element);\n this.priorities_.push(priority);\n this.queuedElements_[this.keyFunction_(element)] = true;\n this.siftDown_(0, this.elements_.length - 1);\n return true;\n }\n return false;\n }\n\n /**\n * @return {number} Count.\n */\n getCount() {\n return this.elements_.length;\n }\n\n /**\n * Gets the index of the left child of the node at the given index.\n * @param {number} index The index of the node to get the left child for.\n * @return {number} The index of the left child.\n * @private\n */\n getLeftChildIndex_(index) {\n return index * 2 + 1;\n }\n\n /**\n * Gets the index of the right child of the node at the given index.\n * @param {number} index The index of the node to get the right child for.\n * @return {number} The index of the right child.\n * @private\n */\n getRightChildIndex_(index) {\n return index * 2 + 2;\n }\n\n /**\n * Gets the index of the parent of the node at the given index.\n * @param {number} index The index of the node to get the parent for.\n * @return {number} The index of the parent.\n * @private\n */\n getParentIndex_(index) {\n return (index - 1) >> 1;\n }\n\n /**\n * Make this a heap. O(N).\n * @private\n */\n heapify_() {\n let i;\n for (i = (this.elements_.length >> 1) - 1; i >= 0; i--) {\n this.siftUp_(i);\n }\n }\n\n /**\n * @return {boolean} Is empty.\n */\n isEmpty() {\n return this.elements_.length === 0;\n }\n\n /**\n * @param {string} key Key.\n * @return {boolean} Is key queued.\n */\n isKeyQueued(key) {\n return key in this.queuedElements_;\n }\n\n /**\n * @param {T} element Element.\n * @return {boolean} Is queued.\n */\n isQueued(element) {\n return this.isKeyQueued(this.keyFunction_(element));\n }\n\n /**\n * @param {number} index The index of the node to move down.\n * @private\n */\n siftUp_(index) {\n const elements = this.elements_;\n const priorities = this.priorities_;\n const count = elements.length;\n const element = elements[index];\n const priority = priorities[index];\n const startIndex = index;\n\n while (index < count >> 1) {\n const lIndex = this.getLeftChildIndex_(index);\n const rIndex = this.getRightChildIndex_(index);\n\n const smallerChildIndex =\n rIndex < count && priorities[rIndex] < priorities[lIndex]\n ? rIndex\n : lIndex;\n\n elements[index] = elements[smallerChildIndex];\n priorities[index] = priorities[smallerChildIndex];\n index = smallerChildIndex;\n }\n\n elements[index] = element;\n priorities[index] = priority;\n this.siftDown_(startIndex, index);\n }\n\n /**\n * @param {number} startIndex The index of the root.\n * @param {number} index The index of the node to move up.\n * @private\n */\n siftDown_(startIndex, index) {\n const elements = this.elements_;\n const priorities = this.priorities_;\n const element = elements[index];\n const priority = priorities[index];\n\n while (index > startIndex) {\n const parentIndex = this.getParentIndex_(index);\n if (priorities[parentIndex] > priority) {\n elements[index] = elements[parentIndex];\n priorities[index] = priorities[parentIndex];\n index = parentIndex;\n } else {\n break;\n }\n }\n elements[index] = element;\n priorities[index] = priority;\n }\n\n /**\n * FIXME empty description for jsdoc\n */\n reprioritize() {\n const priorityFunction = this.priorityFunction_;\n const elements = this.elements_;\n const priorities = this.priorities_;\n let index = 0;\n const n = elements.length;\n let element, i, priority;\n for (i = 0; i < n; ++i) {\n element = elements[i];\n priority = priorityFunction(element);\n if (priority == DROP) {\n delete this.queuedElements_[this.keyFunction_(element)];\n } else {\n priorities[index] = priority;\n elements[index++] = element;\n }\n }\n elements.length = index;\n priorities.length = index;\n this.heapify_();\n }\n}\n\nexport default PriorityQueue;\n","/**\n * @module ol/TileQueue\n */\nimport EventType from './events/EventType.js';\nimport PriorityQueue, {DROP} from './structs/PriorityQueue.js';\nimport TileState from './TileState.js';\n\n/**\n * @typedef {function(import(\"./Tile.js\").default, string, import(\"./coordinate.js\").Coordinate, number): number} PriorityFunction\n */\n\nclass TileQueue extends PriorityQueue {\n /**\n * @param {PriorityFunction} tilePriorityFunction Tile priority function.\n * @param {function(): ?} tileChangeCallback Function called on each tile change event.\n */\n constructor(tilePriorityFunction, tileChangeCallback) {\n super(\n /**\n * @param {Array} element Element.\n * @return {number} Priority.\n */\n function (element) {\n return tilePriorityFunction.apply(null, element);\n },\n /**\n * @param {Array} element Element.\n * @return {string} Key.\n */\n function (element) {\n return /** @type {import(\"./Tile.js\").default} */ (element[0]).getKey();\n }\n );\n\n /** @private */\n this.boundHandleTileChange_ = this.handleTileChange.bind(this);\n\n /**\n * @private\n * @type {function(): ?}\n */\n this.tileChangeCallback_ = tileChangeCallback;\n\n /**\n * @private\n * @type {number}\n */\n this.tilesLoading_ = 0;\n\n /**\n * @private\n * @type {!Object}\n */\n this.tilesLoadingKeys_ = {};\n }\n\n /**\n * @param {Array} element Element.\n * @return {boolean} The element was added to the queue.\n */\n enqueue(element) {\n const added = super.enqueue(element);\n if (added) {\n const tile = element[0];\n tile.addEventListener(EventType.CHANGE, this.boundHandleTileChange_);\n }\n return added;\n }\n\n /**\n * @return {number} Number of tiles loading.\n */\n getTilesLoading() {\n return this.tilesLoading_;\n }\n\n /**\n * @param {import(\"./events/Event.js\").default} event Event.\n * @protected\n */\n handleTileChange(event) {\n const tile = /** @type {import(\"./Tile.js\").default} */ (event.target);\n const state = tile.getState();\n if (\n state === TileState.LOADED ||\n state === TileState.ERROR ||\n state === TileState.EMPTY\n ) {\n if (state !== TileState.ERROR) {\n tile.removeEventListener(EventType.CHANGE, this.boundHandleTileChange_);\n }\n const tileKey = tile.getKey();\n if (tileKey in this.tilesLoadingKeys_) {\n delete this.tilesLoadingKeys_[tileKey];\n --this.tilesLoading_;\n }\n this.tileChangeCallback_();\n }\n }\n\n /**\n * @param {number} maxTotalLoading Maximum number tiles to load simultaneously.\n * @param {number} maxNewLoads Maximum number of new tiles to load.\n */\n loadMoreTiles(maxTotalLoading, maxNewLoads) {\n let newLoads = 0;\n let state, tile, tileKey;\n while (\n this.tilesLoading_ < maxTotalLoading &&\n newLoads < maxNewLoads &&\n this.getCount() > 0\n ) {\n tile = /** @type {import(\"./Tile.js\").default} */ (this.dequeue()[0]);\n tileKey = tile.getKey();\n state = tile.getState();\n if (state === TileState.IDLE && !(tileKey in this.tilesLoadingKeys_)) {\n this.tilesLoadingKeys_[tileKey] = true;\n ++this.tilesLoading_;\n ++newLoads;\n tile.load();\n }\n }\n }\n}\n\nexport default TileQueue;\n\n/**\n * @param {import('./Map.js').FrameState} frameState Frame state.\n * @param {import(\"./Tile.js\").default} tile Tile.\n * @param {string} tileSourceKey Tile source key.\n * @param {import(\"./coordinate.js\").Coordinate} tileCenter Tile center.\n * @param {number} tileResolution Tile resolution.\n * @return {number} Tile priority.\n */\nexport function getTilePriority(\n frameState,\n tile,\n tileSourceKey,\n tileCenter,\n tileResolution\n) {\n // Filter out tiles at higher zoom levels than the current zoom level, or that\n // are outside the visible extent.\n if (!frameState || !(tileSourceKey in frameState.wantedTiles)) {\n return DROP;\n }\n if (!frameState.wantedTiles[tileSourceKey][tile.getKey()]) {\n return DROP;\n }\n // Prioritize the highest zoom level tiles closest to the focus.\n // Tiles at higher zoom levels are prioritized using Math.log(tileResolution).\n // Within a zoom level, tiles are prioritized by the distance in pixels between\n // the center of the tile and the center of the viewport. The factor of 65536\n // means that the prioritization should behave as desired for tiles up to\n // 65536 * Math.log(2) = 45426 pixels from the focus.\n const center = frameState.viewState.center;\n const deltaX = tileCenter[0] - center[0];\n const deltaY = tileCenter[1] - center[1];\n return (\n 65536 * Math.log(tileResolution) +\n Math.sqrt(deltaX * deltaX + deltaY * deltaY) / tileResolution\n );\n}\n","/**\n * @module ol/control/Control\n */\nimport BaseObject from '../Object.js';\nimport MapEventType from '../MapEventType.js';\nimport {VOID} from '../functions.js';\nimport {listen, unlistenByKey} from '../events.js';\nimport {removeNode} from '../dom.js';\n\n/**\n * @typedef {Object} Options\n * @property {HTMLElement} [element] The element is the control's\n * container element. This only needs to be specified if you're developing\n * a custom control.\n * @property {function(import(\"../MapEvent.js\").default):void} [render] Function called when\n * the control should be re-rendered. This is called in a `requestAnimationFrame`\n * callback.\n * @property {HTMLElement|string} [target] Specify a target if you want\n * the control to be rendered outside of the map's viewport.\n */\n\n/**\n * @classdesc\n * A control is a visible widget with a DOM element in a fixed position on the\n * screen. They can involve user input (buttons), or be informational only;\n * the position is determined using CSS. By default these are placed in the\n * container with CSS class name `ol-overlaycontainer-stopevent`, but can use\n * any outside DOM element.\n *\n * This is the base class for controls. You can use it for simple custom\n * controls by creating the element with listeners, creating an instance:\n * ```js\n * const myControl = new Control({element: myElement});\n * ```\n * and then adding this to the map.\n *\n * The main advantage of having this as a control rather than a simple separate\n * DOM element is that preventing propagation is handled for you. Controls\n * will also be objects in a {@link module:ol/Collection~Collection}, so you can use their methods.\n *\n * You can also extend this base for your own control class. See\n * examples/custom-controls for an example of how to do this.\n *\n * @api\n */\nclass Control extends BaseObject {\n /**\n * @param {Options} options Control options.\n */\n constructor(options) {\n super();\n\n const element = options.element;\n if (element && !options.target && !element.style.pointerEvents) {\n element.style.pointerEvents = 'auto';\n }\n\n /**\n * @protected\n * @type {HTMLElement}\n */\n this.element = element ? element : null;\n\n /**\n * @private\n * @type {HTMLElement}\n */\n this.target_ = null;\n\n /**\n * @private\n * @type {import(\"../Map.js\").default|null}\n */\n this.map_ = null;\n\n /**\n * @protected\n * @type {!Array}\n */\n this.listenerKeys = [];\n\n if (options.render) {\n this.render = options.render;\n }\n\n if (options.target) {\n this.setTarget(options.target);\n }\n }\n\n /**\n * Clean up.\n */\n disposeInternal() {\n removeNode(this.element);\n super.disposeInternal();\n }\n\n /**\n * Get the map associated with this control.\n * @return {import(\"../Map.js\").default|null} Map.\n * @api\n */\n getMap() {\n return this.map_;\n }\n\n /**\n * Remove the control from its current map and attach it to the new map.\n * Pass `null` to just remove the control from the current map.\n * Subclasses may set up event handlers to get notified about changes to\n * the map here.\n * @param {import(\"../Map.js\").default|null} map Map.\n * @api\n */\n setMap(map) {\n if (this.map_) {\n removeNode(this.element);\n }\n for (let i = 0, ii = this.listenerKeys.length; i < ii; ++i) {\n unlistenByKey(this.listenerKeys[i]);\n }\n this.listenerKeys.length = 0;\n this.map_ = map;\n if (map) {\n const target = this.target_\n ? this.target_\n : map.getOverlayContainerStopEvent();\n target.appendChild(this.element);\n if (this.render !== VOID) {\n this.listenerKeys.push(\n listen(map, MapEventType.POSTRENDER, this.render, this)\n );\n }\n map.render();\n }\n }\n\n /**\n * Renders the control.\n * @param {import(\"../MapEvent.js\").default} mapEvent Map event.\n * @api\n */\n render(mapEvent) {}\n\n /**\n * This function is used to set a target element for the control. It has no\n * effect if it is called after the control has been added to the map (i.e.\n * after `setMap` is called on the control). If no `target` is set in the\n * options passed to the control constructor and if `setTarget` is not called\n * then the control is added to the map's overlay container.\n * @param {HTMLElement|string} target Target.\n * @api\n */\n setTarget(target) {\n this.target_ =\n typeof target === 'string' ? document.getElementById(target) : target;\n }\n}\n\nexport default Control;\n","/**\n * @module ol/control/Attribution\n */\nimport Control from './Control.js';\nimport EventType from '../events/EventType.js';\nimport {CLASS_COLLAPSED, CLASS_CONTROL, CLASS_UNSELECTABLE} from '../css.js';\nimport {equals} from '../array.js';\nimport {removeChildren, replaceNode} from '../dom.js';\n\n/**\n * @typedef {Object} Options\n * @property {string} [className='ol-attribution'] CSS class name.\n * @property {HTMLElement|string} [target] Specify a target if you\n * want the control to be rendered outside of the map's\n * viewport.\n * @property {boolean} [collapsible] Specify if attributions can\n * be collapsed. If not specified, sources control this behavior with their\n * `attributionsCollapsible` setting.\n * @property {boolean} [collapsed=true] Specify if attributions should\n * be collapsed at startup.\n * @property {string} [tipLabel='Attributions'] Text label to use for the button tip.\n * @property {string|HTMLElement} [label='i'] Text label to use for the\n * collapsed attributions button.\n * Instead of text, also an element (e.g. a `span` element) can be used.\n * @property {string} [expandClassName=className + '-expand'] CSS class name for the\n * collapsed attributions button.\n * @property {string|HTMLElement} [collapseLabel='›'] Text label to use\n * for the expanded attributions button.\n * Instead of text, also an element (e.g. a `span` element) can be used.\n * @property {string} [collapseClassName=className + '-collapse'] CSS class name for the\n * expanded attributions button.\n * @property {function(import(\"../MapEvent.js\").default):void} [render] Function called when\n * the control should be re-rendered. This is called in a `requestAnimationFrame`\n * callback.\n */\n\n/**\n * @classdesc\n * Control to show all the attributions associated with the layer sources\n * in the map. This control is one of the default controls included in maps.\n * By default it will show in the bottom right portion of the map, but this can\n * be changed by using a css selector for `.ol-attribution`.\n *\n * @api\n */\nclass Attribution extends Control {\n /**\n * @param {Options} [options] Attribution options.\n */\n constructor(options) {\n options = options ? options : {};\n\n super({\n element: document.createElement('div'),\n render: options.render,\n target: options.target,\n });\n\n /**\n * @private\n * @type {HTMLElement}\n */\n this.ulElement_ = document.createElement('ul');\n\n /**\n * @private\n * @type {boolean}\n */\n this.collapsed_ =\n options.collapsed !== undefined ? options.collapsed : true;\n\n /**\n * @private\n * @type {boolean}\n */\n this.userCollapsed_ = this.collapsed_;\n\n /**\n * @private\n * @type {boolean}\n */\n this.overrideCollapsible_ = options.collapsible !== undefined;\n\n /**\n * @private\n * @type {boolean}\n */\n this.collapsible_ =\n options.collapsible !== undefined ? options.collapsible : true;\n\n if (!this.collapsible_) {\n this.collapsed_ = false;\n }\n\n const className =\n options.className !== undefined ? options.className : 'ol-attribution';\n\n const tipLabel =\n options.tipLabel !== undefined ? options.tipLabel : 'Attributions';\n\n const expandClassName =\n options.expandClassName !== undefined\n ? options.expandClassName\n : className + '-expand';\n\n const collapseLabel =\n options.collapseLabel !== undefined ? options.collapseLabel : '\\u203A';\n\n const collapseClassName =\n options.collapseClassName !== undefined\n ? options.collapseClassName\n : className + '-collapse';\n\n if (typeof collapseLabel === 'string') {\n /**\n * @private\n * @type {HTMLElement}\n */\n this.collapseLabel_ = document.createElement('span');\n this.collapseLabel_.textContent = collapseLabel;\n this.collapseLabel_.className = collapseClassName;\n } else {\n this.collapseLabel_ = collapseLabel;\n }\n\n const label = options.label !== undefined ? options.label : 'i';\n\n if (typeof label === 'string') {\n /**\n * @private\n * @type {HTMLElement}\n */\n this.label_ = document.createElement('span');\n this.label_.textContent = label;\n this.label_.className = expandClassName;\n } else {\n this.label_ = label;\n }\n\n const activeLabel =\n this.collapsible_ && !this.collapsed_ ? this.collapseLabel_ : this.label_;\n\n /**\n * @private\n * @type {HTMLElement}\n */\n this.toggleButton_ = document.createElement('button');\n this.toggleButton_.setAttribute('type', 'button');\n this.toggleButton_.setAttribute('aria-expanded', String(!this.collapsed_));\n this.toggleButton_.title = tipLabel;\n this.toggleButton_.appendChild(activeLabel);\n\n this.toggleButton_.addEventListener(\n EventType.CLICK,\n this.handleClick_.bind(this),\n false\n );\n\n const cssClasses =\n className +\n ' ' +\n CLASS_UNSELECTABLE +\n ' ' +\n CLASS_CONTROL +\n (this.collapsed_ && this.collapsible_ ? ' ' + CLASS_COLLAPSED : '') +\n (this.collapsible_ ? '' : ' ol-uncollapsible');\n const element = this.element;\n element.className = cssClasses;\n element.appendChild(this.toggleButton_);\n element.appendChild(this.ulElement_);\n\n /**\n * A list of currently rendered resolutions.\n * @type {Array}\n * @private\n */\n this.renderedAttributions_ = [];\n\n /**\n * @private\n * @type {boolean}\n */\n this.renderedVisible_ = true;\n }\n\n /**\n * Collect a list of visible attributions and set the collapsible state.\n * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n * @return {Array} Attributions.\n * @private\n */\n collectSourceAttributions_(frameState) {\n const visibleAttributions = Array.from(\n new Set(\n this.getMap()\n .getAllLayers()\n .flatMap((layer) => layer.getAttributions(frameState))\n )\n );\n\n const collapsible = !this.getMap()\n .getAllLayers()\n .some(\n (layer) =>\n layer.getSource() &&\n layer.getSource().getAttributionsCollapsible() === false\n );\n if (!this.overrideCollapsible_) {\n this.setCollapsible(collapsible);\n }\n return visibleAttributions;\n }\n\n /**\n * @private\n * @param {?import(\"../Map.js\").FrameState} frameState Frame state.\n */\n updateElement_(frameState) {\n if (!frameState) {\n if (this.renderedVisible_) {\n this.element.style.display = 'none';\n this.renderedVisible_ = false;\n }\n return;\n }\n\n const attributions = this.collectSourceAttributions_(frameState);\n\n const visible = attributions.length > 0;\n if (this.renderedVisible_ != visible) {\n this.element.style.display = visible ? '' : 'none';\n this.renderedVisible_ = visible;\n }\n\n if (equals(attributions, this.renderedAttributions_)) {\n return;\n }\n\n removeChildren(this.ulElement_);\n\n // append the attributions\n for (let i = 0, ii = attributions.length; i < ii; ++i) {\n const element = document.createElement('li');\n element.innerHTML = attributions[i];\n this.ulElement_.appendChild(element);\n }\n\n this.renderedAttributions_ = attributions;\n }\n\n /**\n * @param {MouseEvent} event The event to handle\n * @private\n */\n handleClick_(event) {\n event.preventDefault();\n this.handleToggle_();\n this.userCollapsed_ = this.collapsed_;\n }\n\n /**\n * @private\n */\n handleToggle_() {\n this.element.classList.toggle(CLASS_COLLAPSED);\n if (this.collapsed_) {\n replaceNode(this.collapseLabel_, this.label_);\n } else {\n replaceNode(this.label_, this.collapseLabel_);\n }\n this.collapsed_ = !this.collapsed_;\n this.toggleButton_.setAttribute('aria-expanded', String(!this.collapsed_));\n }\n\n /**\n * Return `true` if the attribution is collapsible, `false` otherwise.\n * @return {boolean} True if the widget is collapsible.\n * @api\n */\n getCollapsible() {\n return this.collapsible_;\n }\n\n /**\n * Set whether the attribution should be collapsible.\n * @param {boolean} collapsible True if the widget is collapsible.\n * @api\n */\n setCollapsible(collapsible) {\n if (this.collapsible_ === collapsible) {\n return;\n }\n this.collapsible_ = collapsible;\n this.element.classList.toggle('ol-uncollapsible');\n if (this.userCollapsed_) {\n this.handleToggle_();\n }\n }\n\n /**\n * Collapse or expand the attribution according to the passed parameter. Will\n * not do anything if the attribution isn't collapsible or if the current\n * collapsed state is already the one requested.\n * @param {boolean} collapsed True if the widget is collapsed.\n * @api\n */\n setCollapsed(collapsed) {\n this.userCollapsed_ = collapsed;\n if (!this.collapsible_ || this.collapsed_ === collapsed) {\n return;\n }\n this.handleToggle_();\n }\n\n /**\n * Return `true` when the attribution is currently collapsed or `false`\n * otherwise.\n * @return {boolean} True if the widget is collapsed.\n * @api\n */\n getCollapsed() {\n return this.collapsed_;\n }\n\n /**\n * Update the attribution element.\n * @param {import(\"../MapEvent.js\").default} mapEvent Map event.\n * @override\n */\n render(mapEvent) {\n this.updateElement_(mapEvent.frameState);\n }\n}\n\nexport default Attribution;\n","/**\n * @module ol/control/Rotate\n */\nimport Control from './Control.js';\nimport EventType from '../events/EventType.js';\nimport {CLASS_CONTROL, CLASS_HIDDEN, CLASS_UNSELECTABLE} from '../css.js';\nimport {easeOut} from '../easing.js';\n\n/**\n * @typedef {Object} Options\n * @property {string} [className='ol-rotate'] CSS class name.\n * @property {string|HTMLElement} [label='⇧'] Text label to use for the rotate button.\n * Instead of text, also an element (e.g. a `span` element) can be used.\n * @property {string} [tipLabel='Reset rotation'] Text label to use for the rotate tip.\n * @property {string} [compassClassName='ol-compass'] CSS class name for the compass.\n * @property {number} [duration=250] Animation duration in milliseconds.\n * @property {boolean} [autoHide=true] Hide the control when rotation is 0.\n * @property {function(import(\"../MapEvent.js\").default):void} [render] Function called when the control should\n * be re-rendered. This is called in a `requestAnimationFrame` callback.\n * @property {function():void} [resetNorth] Function called when the control is clicked.\n * This will override the default `resetNorth`.\n * @property {HTMLElement|string} [target] Specify a target if you want the control to be\n * rendered outside of the map's viewport.\n */\n\n/**\n * @classdesc\n * A button control to reset rotation to 0.\n * To style this control use css selector `.ol-rotate`. A `.ol-hidden` css\n * selector is added to the button when the rotation is 0.\n *\n * @api\n */\nclass Rotate extends Control {\n /**\n * @param {Options} [options] Rotate options.\n */\n constructor(options) {\n options = options ? options : {};\n\n super({\n element: document.createElement('div'),\n render: options.render,\n target: options.target,\n });\n\n const className =\n options.className !== undefined ? options.className : 'ol-rotate';\n\n const label = options.label !== undefined ? options.label : '\\u21E7';\n\n const compassClassName =\n options.compassClassName !== undefined\n ? options.compassClassName\n : 'ol-compass';\n\n /**\n * @type {HTMLElement}\n * @private\n */\n this.label_ = null;\n\n if (typeof label === 'string') {\n this.label_ = document.createElement('span');\n this.label_.className = compassClassName;\n this.label_.textContent = label;\n } else {\n this.label_ = label;\n this.label_.classList.add(compassClassName);\n }\n\n const tipLabel = options.tipLabel ? options.tipLabel : 'Reset rotation';\n\n const button = document.createElement('button');\n button.className = className + '-reset';\n button.setAttribute('type', 'button');\n button.title = tipLabel;\n button.appendChild(this.label_);\n\n button.addEventListener(\n EventType.CLICK,\n this.handleClick_.bind(this),\n false\n );\n\n const cssClasses =\n className + ' ' + CLASS_UNSELECTABLE + ' ' + CLASS_CONTROL;\n const element = this.element;\n element.className = cssClasses;\n element.appendChild(button);\n\n this.callResetNorth_ = options.resetNorth ? options.resetNorth : undefined;\n\n /**\n * @type {number}\n * @private\n */\n this.duration_ = options.duration !== undefined ? options.duration : 250;\n\n /**\n * @type {boolean}\n * @private\n */\n this.autoHide_ = options.autoHide !== undefined ? options.autoHide : true;\n\n /**\n * @private\n * @type {number|undefined}\n */\n this.rotation_ = undefined;\n\n if (this.autoHide_) {\n this.element.classList.add(CLASS_HIDDEN);\n }\n }\n\n /**\n * @param {MouseEvent} event The event to handle\n * @private\n */\n handleClick_(event) {\n event.preventDefault();\n if (this.callResetNorth_ !== undefined) {\n this.callResetNorth_();\n } else {\n this.resetNorth_();\n }\n }\n\n /**\n * @private\n */\n resetNorth_() {\n const map = this.getMap();\n const view = map.getView();\n if (!view) {\n // the map does not have a view, so we can't act\n // upon it\n return;\n }\n const rotation = view.getRotation();\n if (rotation !== undefined) {\n if (this.duration_ > 0 && rotation % (2 * Math.PI) !== 0) {\n view.animate({\n rotation: 0,\n duration: this.duration_,\n easing: easeOut,\n });\n } else {\n view.setRotation(0);\n }\n }\n }\n\n /**\n * Update the rotate control element.\n * @param {import(\"../MapEvent.js\").default} mapEvent Map event.\n * @override\n */\n render(mapEvent) {\n const frameState = mapEvent.frameState;\n if (!frameState) {\n return;\n }\n const rotation = frameState.viewState.rotation;\n if (rotation != this.rotation_) {\n const transform = 'rotate(' + rotation + 'rad)';\n if (this.autoHide_) {\n const contains = this.element.classList.contains(CLASS_HIDDEN);\n if (!contains && rotation === 0) {\n this.element.classList.add(CLASS_HIDDEN);\n } else if (contains && rotation !== 0) {\n this.element.classList.remove(CLASS_HIDDEN);\n }\n }\n this.label_.style.transform = transform;\n }\n this.rotation_ = rotation;\n }\n}\n\nexport default Rotate;\n","/**\n * @module ol/control/Zoom\n */\nimport Control from './Control.js';\nimport EventType from '../events/EventType.js';\nimport {CLASS_CONTROL, CLASS_UNSELECTABLE} from '../css.js';\nimport {easeOut} from '../easing.js';\n\n/**\n * @typedef {Object} Options\n * @property {number} [duration=250] Animation duration in milliseconds.\n * @property {string} [className='ol-zoom'] CSS class name.\n * @property {string} [zoomInClassName=className + '-in'] CSS class name for the zoom-in button.\n * @property {string} [zoomOutClassName=className + '-out'] CSS class name for the zoom-out button.\n * @property {string|HTMLElement} [zoomInLabel='+'] Text label to use for the zoom-in\n * button. Instead of text, also an element (e.g. a `span` element) can be used.\n * @property {string|HTMLElement} [zoomOutLabel='–'] Text label to use for the zoom-out button.\n * Instead of text, also an element (e.g. a `span` element) can be used.\n * @property {string} [zoomInTipLabel='Zoom in'] Text label to use for the button tip.\n * @property {string} [zoomOutTipLabel='Zoom out'] Text label to use for the button tip.\n * @property {number} [delta=1] The zoom delta applied on each click.\n * @property {HTMLElement|string} [target] Specify a target if you want the control to be\n * rendered outside of the map's viewport.\n */\n\n/**\n * @classdesc\n * A control with 2 buttons, one for zoom in and one for zoom out.\n * This control is one of the default controls of a map. To style this control\n * use css selectors `.ol-zoom-in` and `.ol-zoom-out`.\n *\n * @api\n */\nclass Zoom extends Control {\n /**\n * @param {Options} [options] Zoom options.\n */\n constructor(options) {\n options = options ? options : {};\n\n super({\n element: document.createElement('div'),\n target: options.target,\n });\n\n const className =\n options.className !== undefined ? options.className : 'ol-zoom';\n\n const delta = options.delta !== undefined ? options.delta : 1;\n\n const zoomInClassName =\n options.zoomInClassName !== undefined\n ? options.zoomInClassName\n : className + '-in';\n\n const zoomOutClassName =\n options.zoomOutClassName !== undefined\n ? options.zoomOutClassName\n : className + '-out';\n\n const zoomInLabel =\n options.zoomInLabel !== undefined ? options.zoomInLabel : '+';\n const zoomOutLabel =\n options.zoomOutLabel !== undefined ? options.zoomOutLabel : '\\u2013';\n\n const zoomInTipLabel =\n options.zoomInTipLabel !== undefined ? options.zoomInTipLabel : 'Zoom in';\n const zoomOutTipLabel =\n options.zoomOutTipLabel !== undefined\n ? options.zoomOutTipLabel\n : 'Zoom out';\n\n const inElement = document.createElement('button');\n inElement.className = zoomInClassName;\n inElement.setAttribute('type', 'button');\n inElement.title = zoomInTipLabel;\n inElement.appendChild(\n typeof zoomInLabel === 'string'\n ? document.createTextNode(zoomInLabel)\n : zoomInLabel\n );\n\n inElement.addEventListener(\n EventType.CLICK,\n this.handleClick_.bind(this, delta),\n false\n );\n\n const outElement = document.createElement('button');\n outElement.className = zoomOutClassName;\n outElement.setAttribute('type', 'button');\n outElement.title = zoomOutTipLabel;\n outElement.appendChild(\n typeof zoomOutLabel === 'string'\n ? document.createTextNode(zoomOutLabel)\n : zoomOutLabel\n );\n\n outElement.addEventListener(\n EventType.CLICK,\n this.handleClick_.bind(this, -delta),\n false\n );\n\n const cssClasses =\n className + ' ' + CLASS_UNSELECTABLE + ' ' + CLASS_CONTROL;\n const element = this.element;\n element.className = cssClasses;\n element.appendChild(inElement);\n element.appendChild(outElement);\n\n /**\n * @type {number}\n * @private\n */\n this.duration_ = options.duration !== undefined ? options.duration : 250;\n }\n\n /**\n * @param {number} delta Zoom delta.\n * @param {MouseEvent} event The event to handle\n * @private\n */\n handleClick_(delta, event) {\n event.preventDefault();\n this.zoomByDelta_(delta);\n }\n\n /**\n * @param {number} delta Zoom delta.\n * @private\n */\n zoomByDelta_(delta) {\n const map = this.getMap();\n const view = map.getView();\n if (!view) {\n // the map does not have a view, so we can't act\n // upon it\n return;\n }\n const currentZoom = view.getZoom();\n if (currentZoom !== undefined) {\n const newZoom = view.getConstrainedZoom(currentZoom + delta);\n if (this.duration_ > 0) {\n if (view.getAnimating()) {\n view.cancelAnimations();\n }\n view.animate({\n zoom: newZoom,\n duration: this.duration_,\n easing: easeOut,\n });\n } else {\n view.setZoom(newZoom);\n }\n }\n }\n}\n\nexport default Zoom;\n","/**\n * @module ol/control/defaults\n */\nimport Attribution from './Attribution.js';\nimport Collection from '../Collection.js';\nimport Rotate from './Rotate.js';\nimport Zoom from './Zoom.js';\n\n/**\n * @typedef {Object} DefaultsOptions\n * @property {boolean} [attribution=true] Include\n * {@link module:ol/control/Attribution~Attribution}.\n * @property {import(\"./Attribution.js\").Options} [attributionOptions]\n * Options for {@link module:ol/control/Attribution~Attribution}.\n * @property {boolean} [rotate=true] Include\n * {@link module:ol/control/Rotate~Rotate}.\n * @property {import(\"./Rotate.js\").Options} [rotateOptions] Options\n * for {@link module:ol/control/Rotate~Rotate}.\n * @property {boolean} [zoom] Include {@link module:ol/control/Zoom~Zoom}.\n * @property {import(\"./Zoom.js\").Options} [zoomOptions] Options for\n * {@link module:ol/control/Zoom~Zoom}.\n */\n\n/**\n * Set of controls included in maps by default. Unless configured otherwise,\n * this returns a collection containing an instance of each of the following\n * controls:\n * * {@link module:ol/control/Zoom~Zoom}\n * * {@link module:ol/control/Rotate~Rotate}\n * * {@link module:ol/control/Attribution~Attribution}\n *\n * @param {DefaultsOptions} [options] Options for the default controls.\n * @return {Collection} A collection of controls\n * to be used with the {@link module:ol/Map~Map} constructor's `controls` option.\n * @api\n */\nexport function defaults(options) {\n options = options ? options : {};\n\n /** @type {Collection} */\n const controls = new Collection();\n\n const zoomControl = options.zoom !== undefined ? options.zoom : true;\n if (zoomControl) {\n controls.push(new Zoom(options.zoomOptions));\n }\n\n const rotateControl = options.rotate !== undefined ? options.rotate : true;\n if (rotateControl) {\n controls.push(new Rotate(options.rotateOptions));\n }\n\n const attributionControl =\n options.attribution !== undefined ? options.attribution : true;\n if (attributionControl) {\n controls.push(new Attribution(options.attributionOptions));\n }\n\n return controls;\n}\n","/**\n * @module ol/interaction/Property\n */\n\n/**\n * @enum {string}\n */\nexport default {\n ACTIVE: 'active',\n};\n","/**\n * @module ol/interaction/Interaction\n */\nimport BaseObject from '../Object.js';\nimport InteractionProperty from './Property.js';\nimport {easeOut, linear} from '../easing.js';\n\n/***\n * @template Return\n * @typedef {import(\"../Observable\").OnSignature &\n * import(\"../Observable\").OnSignature &\n * import(\"../Observable\").CombinedOnSignature} InteractionOnSignature\n */\n\n/**\n * Object literal with config options for interactions.\n * @typedef {Object} InteractionOptions\n * @property {function(import(\"../MapBrowserEvent.js\").default):boolean} handleEvent\n * Method called by the map to notify the interaction that a browser event was\n * dispatched to the map. If the function returns a falsy value, propagation of\n * the event to other interactions in the map's interactions chain will be\n * prevented (this includes functions with no explicit return). The interactions\n * are traversed in reverse order of the interactions collection of the map.\n */\n\n/**\n * @classdesc\n * Abstract base class; normally only used for creating subclasses and not\n * instantiated in apps.\n * User actions that change the state of the map. Some are similar to controls,\n * but are not associated with a DOM element.\n * For example, {@link module:ol/interaction/KeyboardZoom~KeyboardZoom} is\n * functionally the same as {@link module:ol/control/Zoom~Zoom}, but triggered\n * by a keyboard event not a button element event.\n * Although interactions do not have a DOM element, some of them do render\n * vectors and so are visible on the screen.\n * @api\n */\nclass Interaction extends BaseObject {\n /**\n * @param {InteractionOptions} [options] Options.\n */\n constructor(options) {\n super();\n\n /***\n * @type {InteractionOnSignature}\n */\n this.on;\n\n /***\n * @type {InteractionOnSignature}\n */\n this.once;\n\n /***\n * @type {InteractionOnSignature}\n */\n this.un;\n\n if (options && options.handleEvent) {\n this.handleEvent = options.handleEvent;\n }\n\n /**\n * @private\n * @type {import(\"../Map.js\").default|null}\n */\n this.map_ = null;\n\n this.setActive(true);\n }\n\n /**\n * Return whether the interaction is currently active.\n * @return {boolean} `true` if the interaction is active, `false` otherwise.\n * @observable\n * @api\n */\n getActive() {\n return /** @type {boolean} */ (this.get(InteractionProperty.ACTIVE));\n }\n\n /**\n * Get the map associated with this interaction.\n * @return {import(\"../Map.js\").default|null} Map.\n * @api\n */\n getMap() {\n return this.map_;\n }\n\n /**\n * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event}.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} `false` to stop event propagation.\n * @api\n */\n handleEvent(mapBrowserEvent) {\n return true;\n }\n\n /**\n * Activate or deactivate the interaction.\n * @param {boolean} active Active.\n * @observable\n * @api\n */\n setActive(active) {\n this.set(InteractionProperty.ACTIVE, active);\n }\n\n /**\n * Remove the interaction from its current map and attach it to the new map.\n * Subclasses may set up event handlers to get notified about changes to\n * the map here.\n * @param {import(\"../Map.js\").default|null} map Map.\n */\n setMap(map) {\n this.map_ = map;\n }\n}\n\n/**\n * @param {import(\"../View.js\").default} view View.\n * @param {import(\"../coordinate.js\").Coordinate} delta Delta.\n * @param {number} [duration] Duration.\n */\nexport function pan(view, delta, duration) {\n const currentCenter = view.getCenterInternal();\n if (currentCenter) {\n const center = [currentCenter[0] + delta[0], currentCenter[1] + delta[1]];\n view.animateInternal({\n duration: duration !== undefined ? duration : 250,\n easing: linear,\n center: view.getConstrainedCenter(center),\n });\n }\n}\n\n/**\n * @param {import(\"../View.js\").default} view View.\n * @param {number} delta Delta from previous zoom level.\n * @param {import(\"../coordinate.js\").Coordinate} [anchor] Anchor coordinate in the user projection.\n * @param {number} [duration] Duration.\n */\nexport function zoomByDelta(view, delta, anchor, duration) {\n const currentZoom = view.getZoom();\n\n if (currentZoom === undefined) {\n return;\n }\n\n const newZoom = view.getConstrainedZoom(currentZoom + delta);\n const newResolution = view.getResolutionForZoom(newZoom);\n\n if (view.getAnimating()) {\n view.cancelAnimations();\n }\n view.animate({\n resolution: newResolution,\n anchor: anchor,\n duration: duration !== undefined ? duration : 250,\n easing: easeOut,\n });\n}\n\nexport default Interaction;\n","/**\n * @module ol/interaction/DoubleClickZoom\n */\nimport Interaction, {zoomByDelta} from './Interaction.js';\nimport MapBrowserEventType from '../MapBrowserEventType.js';\n\n/**\n * @typedef {Object} Options\n * @property {number} [duration=250] Animation duration in milliseconds.\n * @property {number} [delta=1] The zoom delta applied on each double click.\n */\n\n/**\n * @classdesc\n * Allows the user to zoom by double-clicking on the map.\n * @api\n */\nclass DoubleClickZoom extends Interaction {\n /**\n * @param {Options} [options] Options.\n */\n constructor(options) {\n super();\n\n options = options ? options : {};\n\n /**\n * @private\n * @type {number}\n */\n this.delta_ = options.delta ? options.delta : 1;\n\n /**\n * @private\n * @type {number}\n */\n this.duration_ = options.duration !== undefined ? options.duration : 250;\n }\n\n /**\n * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} (if it was a\n * doubleclick) and eventually zooms the map.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} `false` to stop event propagation.\n */\n handleEvent(mapBrowserEvent) {\n let stopEvent = false;\n if (mapBrowserEvent.type == MapBrowserEventType.DBLCLICK) {\n const browserEvent = /** @type {MouseEvent} */ (\n mapBrowserEvent.originalEvent\n );\n const map = mapBrowserEvent.map;\n const anchor = mapBrowserEvent.coordinate;\n const delta = browserEvent.shiftKey ? -this.delta_ : this.delta_;\n const view = map.getView();\n zoomByDelta(view, delta, anchor, this.duration_);\n browserEvent.preventDefault();\n stopEvent = true;\n }\n return !stopEvent;\n }\n}\n\nexport default DoubleClickZoom;\n","/**\n * @module ol/interaction/Pointer\n */\nimport Interaction from './Interaction.js';\nimport MapBrowserEventType from '../MapBrowserEventType.js';\n\n/**\n * @typedef {Object} Options\n * @property {function(import(\"../MapBrowserEvent.js\").default):boolean} [handleDownEvent]\n * Function handling \"down\" events. If the function returns `true` then a drag\n * sequence is started.\n * @property {function(import(\"../MapBrowserEvent.js\").default):void} [handleDragEvent]\n * Function handling \"drag\" events. This function is called on \"move\" events\n * during a drag sequence.\n * @property {function(import(\"../MapBrowserEvent.js\").default):boolean} [handleEvent]\n * Method called by the map to notify the interaction that a browser event was\n * dispatched to the map. The function may return `false` to prevent the\n * propagation of the event to other interactions in the map's interactions\n * chain.\n * @property {function(import(\"../MapBrowserEvent.js\").default):void} [handleMoveEvent]\n * Function handling \"move\" events. This function is called on \"move\" events.\n * This functions is also called during a drag sequence, so during a drag\n * sequence both the `handleDragEvent` function and this function are called.\n * If `handleDownEvent` is defined and it returns true this function will not\n * be called during a drag sequence.\n * @property {function(import(\"../MapBrowserEvent.js\").default):boolean} [handleUpEvent]\n * Function handling \"up\" events. If the function returns `false` then the\n * current drag sequence is stopped.\n * @property {function(boolean):boolean} [stopDown]\n * Should the down event be propagated to other interactions, or should be\n * stopped?\n */\n\n/**\n * @classdesc\n * Base class that calls user-defined functions on `down`, `move` and `up`\n * events. This class also manages \"drag sequences\".\n *\n * When the `handleDownEvent` user function returns `true` a drag sequence is\n * started. During a drag sequence the `handleDragEvent` user function is\n * called on `move` events. The drag sequence ends when the `handleUpEvent`\n * user function is called and returns `false`.\n * @api\n */\nclass PointerInteraction extends Interaction {\n /**\n * @param {Options} [options] Options.\n */\n constructor(options) {\n options = options ? options : {};\n\n super(\n /** @type {import(\"./Interaction.js\").InteractionOptions} */ (options)\n );\n\n if (options.handleDownEvent) {\n this.handleDownEvent = options.handleDownEvent;\n }\n\n if (options.handleDragEvent) {\n this.handleDragEvent = options.handleDragEvent;\n }\n\n if (options.handleMoveEvent) {\n this.handleMoveEvent = options.handleMoveEvent;\n }\n\n if (options.handleUpEvent) {\n this.handleUpEvent = options.handleUpEvent;\n }\n\n if (options.stopDown) {\n this.stopDown = options.stopDown;\n }\n\n /**\n * @type {boolean}\n * @protected\n */\n this.handlingDownUpSequence = false;\n\n /**\n * @type {Array}\n * @protected\n */\n this.targetPointers = [];\n }\n\n /**\n * Returns the current number of pointers involved in the interaction,\n * e.g. `2` when two fingers are used.\n * @return {number} The number of pointers.\n * @api\n */\n getPointerCount() {\n return this.targetPointers.length;\n }\n\n /**\n * Handle pointer down events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n * @return {boolean} If the event was consumed.\n * @protected\n */\n handleDownEvent(mapBrowserEvent) {\n return false;\n }\n\n /**\n * Handle pointer drag events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n * @protected\n */\n handleDragEvent(mapBrowserEvent) {}\n\n /**\n * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} and may call into\n * other functions, if event sequences like e.g. 'drag' or 'down-up' etc. are\n * detected.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} `false` to stop event propagation.\n * @api\n */\n handleEvent(mapBrowserEvent) {\n if (!mapBrowserEvent.originalEvent) {\n return true;\n }\n\n let stopEvent = false;\n this.updateTrackedPointers_(mapBrowserEvent);\n if (this.handlingDownUpSequence) {\n if (mapBrowserEvent.type == MapBrowserEventType.POINTERDRAG) {\n this.handleDragEvent(mapBrowserEvent);\n // prevent page scrolling during dragging\n mapBrowserEvent.originalEvent.preventDefault();\n } else if (mapBrowserEvent.type == MapBrowserEventType.POINTERUP) {\n const handledUp = this.handleUpEvent(mapBrowserEvent);\n this.handlingDownUpSequence =\n handledUp && this.targetPointers.length > 0;\n }\n } else {\n if (mapBrowserEvent.type == MapBrowserEventType.POINTERDOWN) {\n const handled = this.handleDownEvent(mapBrowserEvent);\n this.handlingDownUpSequence = handled;\n stopEvent = this.stopDown(handled);\n } else if (mapBrowserEvent.type == MapBrowserEventType.POINTERMOVE) {\n this.handleMoveEvent(mapBrowserEvent);\n }\n }\n return !stopEvent;\n }\n\n /**\n * Handle pointer move events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n * @protected\n */\n handleMoveEvent(mapBrowserEvent) {}\n\n /**\n * Handle pointer up events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n * @return {boolean} If the event was consumed.\n * @protected\n */\n handleUpEvent(mapBrowserEvent) {\n return false;\n }\n\n /**\n * This function is used to determine if \"down\" events should be propagated\n * to other interactions or should be stopped.\n * @param {boolean} handled Was the event handled by the interaction?\n * @return {boolean} Should the `down` event be stopped?\n */\n stopDown(handled) {\n return handled;\n }\n\n /**\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n * @private\n */\n updateTrackedPointers_(mapBrowserEvent) {\n if (mapBrowserEvent.activePointers) {\n this.targetPointers = mapBrowserEvent.activePointers;\n }\n }\n}\n\n/**\n * @param {Array} pointerEvents List of events.\n * @return {{clientX: number, clientY: number}} Centroid pixel.\n */\nexport function centroid(pointerEvents) {\n const length = pointerEvents.length;\n let clientX = 0;\n let clientY = 0;\n for (let i = 0; i < length; i++) {\n clientX += pointerEvents[i].clientX;\n clientY += pointerEvents[i].clientY;\n }\n return {clientX: clientX / length, clientY: clientY / length};\n}\n\nexport default PointerInteraction;\n","/**\n * @module ol/events/condition\n */\nimport MapBrowserEventType from '../MapBrowserEventType.js';\nimport {FALSE, TRUE} from '../functions.js';\nimport {MAC, WEBKIT} from '../has.js';\nimport {assert} from '../asserts.js';\n\n/**\n * A function that takes an {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a\n * `{boolean}`. If the condition is met, true should be returned.\n *\n * @typedef {function(this: ?, import(\"../MapBrowserEvent.js\").default): boolean} Condition\n */\n\n/**\n * Creates a condition function that passes when all provided conditions pass.\n * @param {...Condition} var_args Conditions to check.\n * @return {Condition} Condition function.\n */\nexport function all(var_args) {\n const conditions = arguments;\n /**\n * @param {import(\"../MapBrowserEvent.js\").default} event Event.\n * @return {boolean} All conditions passed.\n */\n return function (event) {\n let pass = true;\n for (let i = 0, ii = conditions.length; i < ii; ++i) {\n pass = pass && conditions[i](event);\n if (!pass) {\n break;\n }\n }\n return pass;\n };\n}\n\n/**\n * Return `true` if only the alt-key is pressed, `false` otherwise (e.g. when\n * additionally the shift-key is pressed).\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if only the alt key is pressed.\n * @api\n */\nexport const altKeyOnly = function (mapBrowserEvent) {\n const originalEvent = /** @type {KeyboardEvent|MouseEvent|TouchEvent} */ (\n mapBrowserEvent.originalEvent\n );\n return (\n originalEvent.altKey &&\n !(originalEvent.metaKey || originalEvent.ctrlKey) &&\n !originalEvent.shiftKey\n );\n};\n\n/**\n * Return `true` if only the alt-key and shift-key is pressed, `false` otherwise\n * (e.g. when additionally the platform-modifier-key is pressed).\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if only the alt and shift keys are pressed.\n * @api\n */\nexport const altShiftKeysOnly = function (mapBrowserEvent) {\n const originalEvent = /** @type {KeyboardEvent|MouseEvent|TouchEvent} */ (\n mapBrowserEvent.originalEvent\n );\n return (\n originalEvent.altKey &&\n !(originalEvent.metaKey || originalEvent.ctrlKey) &&\n originalEvent.shiftKey\n );\n};\n\n/**\n * Return `true` if the map has the focus. This condition requires a map target\n * element with a `tabindex` attribute, e.g. `
`.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} event Map browser event.\n * @return {boolean} The map has the focus.\n * @api\n */\nexport const focus = function (event) {\n const targetElement = event.map.getTargetElement();\n const activeElement = event.map.getOwnerDocument().activeElement;\n return targetElement.contains(activeElement);\n};\n\n/**\n * Return `true` if the map has the focus or no 'tabindex' attribute set.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} event Map browser event.\n * @return {boolean} The map container has the focus or no 'tabindex' attribute.\n */\nexport const focusWithTabindex = function (event) {\n return event.map.getTargetElement().hasAttribute('tabindex')\n ? focus(event)\n : true;\n};\n\n/**\n * Return always true.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True.\n * @api\n */\nexport const always = TRUE;\n\n/**\n * Return `true` if the event is a `click` event, `false` otherwise.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if the event is a map `click` event.\n * @api\n */\nexport const click = function (mapBrowserEvent) {\n return mapBrowserEvent.type == MapBrowserEventType.CLICK;\n};\n\n/**\n * Return `true` if the event has an \"action\"-producing mouse button.\n *\n * By definition, this includes left-click on windows/linux, and left-click\n * without the ctrl key on Macs.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} The result.\n */\nexport const mouseActionButton = function (mapBrowserEvent) {\n const originalEvent = /** @type {MouseEvent} */ (\n mapBrowserEvent.originalEvent\n );\n return originalEvent.button == 0 && !(WEBKIT && MAC && originalEvent.ctrlKey);\n};\n\n/**\n * Return always false.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} False.\n * @api\n */\nexport const never = FALSE;\n\n/**\n * Return `true` if the browser event is a `pointermove` event, `false`\n * otherwise.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if the browser event is a `pointermove` event.\n * @api\n */\nexport const pointerMove = function (mapBrowserEvent) {\n return mapBrowserEvent.type == 'pointermove';\n};\n\n/**\n * Return `true` if the event is a map `singleclick` event, `false` otherwise.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if the event is a map `singleclick` event.\n * @api\n */\nexport const singleClick = function (mapBrowserEvent) {\n return mapBrowserEvent.type == MapBrowserEventType.SINGLECLICK;\n};\n\n/**\n * Return `true` if the event is a map `dblclick` event, `false` otherwise.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if the event is a map `dblclick` event.\n * @api\n */\nexport const doubleClick = function (mapBrowserEvent) {\n return mapBrowserEvent.type == MapBrowserEventType.DBLCLICK;\n};\n\n/**\n * Return `true` if no modifier key (alt-, shift- or platform-modifier-key) is\n * pressed.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True only if there no modifier keys are pressed.\n * @api\n */\nexport const noModifierKeys = function (mapBrowserEvent) {\n const originalEvent = /** @type {KeyboardEvent|MouseEvent|TouchEvent} */ (\n mapBrowserEvent.originalEvent\n );\n return (\n !originalEvent.altKey &&\n !(originalEvent.metaKey || originalEvent.ctrlKey) &&\n !originalEvent.shiftKey\n );\n};\n\n/**\n * Return `true` if only the platform-modifier-key (the meta-key on Mac,\n * ctrl-key otherwise) is pressed, `false` otherwise (e.g. when additionally\n * the shift-key is pressed).\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if only the platform modifier key is pressed.\n * @api\n */\nexport const platformModifierKeyOnly = function (mapBrowserEvent) {\n const originalEvent = /** @type {KeyboardEvent|MouseEvent|TouchEvent} */ (\n mapBrowserEvent.originalEvent\n );\n return (\n !originalEvent.altKey &&\n (MAC ? originalEvent.metaKey : originalEvent.ctrlKey) &&\n !originalEvent.shiftKey\n );\n};\n\n/**\n * Return `true` if the platform-modifier-key (the meta-key on Mac,\n * ctrl-key otherwise) is pressed.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if the platform modifier key is pressed.\n * @api\n */\nexport const platformModifierKey = function (mapBrowserEvent) {\n const originalEvent = /** @type {KeyboardEvent|MouseEvent|TouchEvent} */ (\n mapBrowserEvent.originalEvent\n );\n return MAC ? originalEvent.metaKey : originalEvent.ctrlKey;\n};\n\n/**\n * Return `true` if only the shift-key is pressed, `false` otherwise (e.g. when\n * additionally the alt-key is pressed).\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if only the shift key is pressed.\n * @api\n */\nexport const shiftKeyOnly = function (mapBrowserEvent) {\n const originalEvent = /** @type {KeyboardEvent|MouseEvent|TouchEvent} */ (\n mapBrowserEvent.originalEvent\n );\n return (\n !originalEvent.altKey &&\n !(originalEvent.metaKey || originalEvent.ctrlKey) &&\n originalEvent.shiftKey\n );\n};\n\n/**\n * Return `true` if the target element is not editable, i.e. not an `input`,\n * `select`, or `textarea` element and no `contenteditable` attribute is\n * set or inherited, `false` otherwise.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True only if the target element is not editable.\n * @api\n */\nexport const targetNotEditable = function (mapBrowserEvent) {\n const originalEvent = /** @type {KeyboardEvent|MouseEvent|TouchEvent} */ (\n mapBrowserEvent.originalEvent\n );\n const tagName = /** @type {Element} */ (originalEvent.target).tagName;\n return (\n tagName !== 'INPUT' &&\n tagName !== 'SELECT' &&\n tagName !== 'TEXTAREA' &&\n // `isContentEditable` is only available on `HTMLElement`, but it may also be a\n // different type like `SVGElement`.\n // @ts-ignore\n !originalEvent.target.isContentEditable\n );\n};\n\n/**\n * Return `true` if the event originates from a mouse device.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if the event originates from a mouse device.\n * @api\n */\nexport const mouseOnly = function (mapBrowserEvent) {\n const pointerEvent = /** @type {import(\"../MapBrowserEvent\").default} */ (\n mapBrowserEvent\n ).originalEvent;\n assert(pointerEvent !== undefined, 56); // mapBrowserEvent must originate from a pointer event\n // see https://www.w3.org/TR/pointerevents/#widl-PointerEvent-pointerType\n return pointerEvent.pointerType == 'mouse';\n};\n\n/**\n * Return `true` if the event originates from a touchable device.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if the event originates from a touchable device.\n * @api\n */\nexport const touchOnly = function (mapBrowserEvent) {\n const pointerEvt = /** @type {import(\"../MapBrowserEvent\").default} */ (\n mapBrowserEvent\n ).originalEvent;\n assert(pointerEvt !== undefined, 56); // mapBrowserEvent must originate from a pointer event\n // see https://www.w3.org/TR/pointerevents/#widl-PointerEvent-pointerType\n return pointerEvt.pointerType === 'touch';\n};\n\n/**\n * Return `true` if the event originates from a digital pen.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if the event originates from a digital pen.\n * @api\n */\nexport const penOnly = function (mapBrowserEvent) {\n const pointerEvt = /** @type {import(\"../MapBrowserEvent\").default} */ (\n mapBrowserEvent\n ).originalEvent;\n assert(pointerEvt !== undefined, 56); // mapBrowserEvent must originate from a pointer event\n // see https://www.w3.org/TR/pointerevents/#widl-PointerEvent-pointerType\n return pointerEvt.pointerType === 'pen';\n};\n\n/**\n * Return `true` if the event originates from a primary pointer in\n * contact with the surface or if the left mouse button is pressed.\n * See https://www.w3.org/TR/pointerevents/#button-states.\n *\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} True if the event originates from a primary pointer.\n * @api\n */\nexport const primaryAction = function (mapBrowserEvent) {\n const pointerEvent = /** @type {import(\"../MapBrowserEvent\").default} */ (\n mapBrowserEvent\n ).originalEvent;\n assert(pointerEvent !== undefined, 56); // mapBrowserEvent must originate from a pointer event\n return pointerEvent.isPrimary && pointerEvent.button === 0;\n};\n","/**\n * @module ol/interaction/DragPan\n */\nimport PointerInteraction, {\n centroid as centroidFromPointers,\n} from './Pointer.js';\nimport {FALSE} from '../functions.js';\nimport {\n all,\n focusWithTabindex,\n noModifierKeys,\n primaryAction,\n} from '../events/condition.js';\nimport {easeOut} from '../easing.js';\nimport {\n rotate as rotateCoordinate,\n scale as scaleCoordinate,\n} from '../coordinate.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"../events/condition.js\").Condition} [condition] A function that takes an {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a boolean\n * to indicate whether that event should be handled.\n * Default is {@link module:ol/events/condition.noModifierKeys} and {@link module:ol/events/condition.primaryAction}.\n * @property {boolean} [onFocusOnly=false] When the map's target has a `tabindex` attribute set,\n * the interaction will only handle events when the map has the focus.\n * @property {import(\"../Kinetic.js\").default} [kinetic] Kinetic inertia to apply to the pan.\n */\n\n/**\n * @classdesc\n * Allows the user to pan the map by dragging the map.\n * @api\n */\nclass DragPan extends PointerInteraction {\n /**\n * @param {Options} [options] Options.\n */\n constructor(options) {\n super({\n stopDown: FALSE,\n });\n\n options = options ? options : {};\n\n /**\n * @private\n * @type {import(\"../Kinetic.js\").default|undefined}\n */\n this.kinetic_ = options.kinetic;\n\n /**\n * @type {import(\"../pixel.js\").Pixel}\n */\n this.lastCentroid = null;\n\n /**\n * @type {number}\n */\n this.lastPointersCount_;\n\n /**\n * @type {boolean}\n */\n this.panning_ = false;\n\n const condition = options.condition\n ? options.condition\n : all(noModifierKeys, primaryAction);\n\n /**\n * @private\n * @type {import(\"../events/condition.js\").Condition}\n */\n this.condition_ = options.onFocusOnly\n ? all(focusWithTabindex, condition)\n : condition;\n\n /**\n * @private\n * @type {boolean}\n */\n this.noKinetic_ = false;\n }\n\n /**\n * Handle pointer drag events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n */\n handleDragEvent(mapBrowserEvent) {\n const map = mapBrowserEvent.map;\n if (!this.panning_) {\n this.panning_ = true;\n map.getView().beginInteraction();\n }\n const targetPointers = this.targetPointers;\n const centroid = map.getEventPixel(centroidFromPointers(targetPointers));\n if (targetPointers.length == this.lastPointersCount_) {\n if (this.kinetic_) {\n this.kinetic_.update(centroid[0], centroid[1]);\n }\n if (this.lastCentroid) {\n const delta = [\n this.lastCentroid[0] - centroid[0],\n centroid[1] - this.lastCentroid[1],\n ];\n const map = mapBrowserEvent.map;\n const view = map.getView();\n scaleCoordinate(delta, view.getResolution());\n rotateCoordinate(delta, view.getRotation());\n view.adjustCenterInternal(delta);\n }\n } else if (this.kinetic_) {\n // reset so we don't overestimate the kinetic energy after\n // after one finger down, tiny drag, second finger down\n this.kinetic_.begin();\n }\n this.lastCentroid = centroid;\n this.lastPointersCount_ = targetPointers.length;\n mapBrowserEvent.originalEvent.preventDefault();\n }\n\n /**\n * Handle pointer up events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n * @return {boolean} If the event was consumed.\n */\n handleUpEvent(mapBrowserEvent) {\n const map = mapBrowserEvent.map;\n const view = map.getView();\n if (this.targetPointers.length === 0) {\n if (!this.noKinetic_ && this.kinetic_ && this.kinetic_.end()) {\n const distance = this.kinetic_.getDistance();\n const angle = this.kinetic_.getAngle();\n const center = view.getCenterInternal();\n const centerpx = map.getPixelFromCoordinateInternal(center);\n const dest = map.getCoordinateFromPixelInternal([\n centerpx[0] - distance * Math.cos(angle),\n centerpx[1] - distance * Math.sin(angle),\n ]);\n view.animateInternal({\n center: view.getConstrainedCenter(dest),\n duration: 500,\n easing: easeOut,\n });\n }\n if (this.panning_) {\n this.panning_ = false;\n view.endInteraction();\n }\n return false;\n }\n if (this.kinetic_) {\n // reset so we don't overestimate the kinetic energy after\n // after one finger up, tiny drag, second finger up\n this.kinetic_.begin();\n }\n this.lastCentroid = null;\n return true;\n }\n\n /**\n * Handle pointer down events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n * @return {boolean} If the event was consumed.\n */\n handleDownEvent(mapBrowserEvent) {\n if (this.targetPointers.length > 0 && this.condition_(mapBrowserEvent)) {\n const map = mapBrowserEvent.map;\n const view = map.getView();\n this.lastCentroid = null;\n // stop any current animation\n if (view.getAnimating()) {\n view.cancelAnimations();\n }\n if (this.kinetic_) {\n this.kinetic_.begin();\n }\n // No kinetic as soon as more than one pointer on the screen is\n // detected. This is to prevent nasty pans after pinch.\n this.noKinetic_ = this.targetPointers.length > 1;\n return true;\n }\n return false;\n }\n}\n\nexport default DragPan;\n","/**\n * @module ol/interaction/DragRotate\n */\nimport PointerInteraction from './Pointer.js';\nimport {FALSE} from '../functions.js';\nimport {\n altShiftKeysOnly,\n mouseActionButton,\n mouseOnly,\n} from '../events/condition.js';\nimport {disable} from '../rotationconstraint.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"../events/condition.js\").Condition} [condition] A function that takes an\n * {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a boolean\n * to indicate whether that event should be handled.\n * Default is {@link module:ol/events/condition.altShiftKeysOnly}.\n * @property {number} [duration=250] Animation duration in milliseconds.\n */\n\n/**\n * @classdesc\n * Allows the user to rotate the map by clicking and dragging on the map,\n * normally combined with an {@link module:ol/events/condition} that limits\n * it to when the alt and shift keys are held down.\n *\n * This interaction is only supported for mouse devices.\n * @api\n */\nclass DragRotate extends PointerInteraction {\n /**\n * @param {Options} [options] Options.\n */\n constructor(options) {\n options = options ? options : {};\n\n super({\n stopDown: FALSE,\n });\n\n /**\n * @private\n * @type {import(\"../events/condition.js\").Condition}\n */\n this.condition_ = options.condition ? options.condition : altShiftKeysOnly;\n\n /**\n * @private\n * @type {number|undefined}\n */\n this.lastAngle_ = undefined;\n\n /**\n * @private\n * @type {number}\n */\n this.duration_ = options.duration !== undefined ? options.duration : 250;\n }\n\n /**\n * Handle pointer drag events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n */\n handleDragEvent(mapBrowserEvent) {\n if (!mouseOnly(mapBrowserEvent)) {\n return;\n }\n\n const map = mapBrowserEvent.map;\n const view = map.getView();\n if (view.getConstraints().rotation === disable) {\n return;\n }\n const size = map.getSize();\n const offset = mapBrowserEvent.pixel;\n const theta = Math.atan2(size[1] / 2 - offset[1], offset[0] - size[0] / 2);\n if (this.lastAngle_ !== undefined) {\n const delta = theta - this.lastAngle_;\n view.adjustRotationInternal(-delta);\n }\n this.lastAngle_ = theta;\n }\n\n /**\n * Handle pointer up events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n * @return {boolean} If the event was consumed.\n */\n handleUpEvent(mapBrowserEvent) {\n if (!mouseOnly(mapBrowserEvent)) {\n return true;\n }\n\n const map = mapBrowserEvent.map;\n const view = map.getView();\n view.endInteraction(this.duration_);\n return false;\n }\n\n /**\n * Handle pointer down events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n * @return {boolean} If the event was consumed.\n */\n handleDownEvent(mapBrowserEvent) {\n if (!mouseOnly(mapBrowserEvent)) {\n return false;\n }\n\n if (\n mouseActionButton(mapBrowserEvent) &&\n this.condition_(mapBrowserEvent)\n ) {\n const map = mapBrowserEvent.map;\n map.getView().beginInteraction();\n this.lastAngle_ = undefined;\n return true;\n }\n return false;\n }\n}\n\nexport default DragRotate;\n","/**\n * @module ol/render/Box\n */\n\nimport Disposable from '../Disposable.js';\nimport Polygon from '../geom/Polygon.js';\n\nclass RenderBox extends Disposable {\n /**\n * @param {string} className CSS class name.\n */\n constructor(className) {\n super();\n\n /**\n * @type {import(\"../geom/Polygon.js\").default}\n * @private\n */\n this.geometry_ = null;\n\n /**\n * @type {HTMLDivElement}\n * @private\n */\n this.element_ = document.createElement('div');\n this.element_.style.position = 'absolute';\n this.element_.style.pointerEvents = 'auto';\n this.element_.className = 'ol-box ' + className;\n\n /**\n * @private\n * @type {import(\"../Map.js\").default|null}\n */\n this.map_ = null;\n\n /**\n * @private\n * @type {import(\"../pixel.js\").Pixel}\n */\n this.startPixel_ = null;\n\n /**\n * @private\n * @type {import(\"../pixel.js\").Pixel}\n */\n this.endPixel_ = null;\n }\n\n /**\n * Clean up.\n */\n disposeInternal() {\n this.setMap(null);\n }\n\n /**\n * @private\n */\n render_() {\n const startPixel = this.startPixel_;\n const endPixel = this.endPixel_;\n const px = 'px';\n const style = this.element_.style;\n style.left = Math.min(startPixel[0], endPixel[0]) + px;\n style.top = Math.min(startPixel[1], endPixel[1]) + px;\n style.width = Math.abs(endPixel[0] - startPixel[0]) + px;\n style.height = Math.abs(endPixel[1] - startPixel[1]) + px;\n }\n\n /**\n * @param {import(\"../Map.js\").default|null} map Map.\n */\n setMap(map) {\n if (this.map_) {\n this.map_.getOverlayContainer().removeChild(this.element_);\n const style = this.element_.style;\n style.left = 'inherit';\n style.top = 'inherit';\n style.width = 'inherit';\n style.height = 'inherit';\n }\n this.map_ = map;\n if (this.map_) {\n this.map_.getOverlayContainer().appendChild(this.element_);\n }\n }\n\n /**\n * @param {import(\"../pixel.js\").Pixel} startPixel Start pixel.\n * @param {import(\"../pixel.js\").Pixel} endPixel End pixel.\n */\n setPixels(startPixel, endPixel) {\n this.startPixel_ = startPixel;\n this.endPixel_ = endPixel;\n this.createOrUpdateGeometry();\n this.render_();\n }\n\n /**\n * Creates or updates the cached geometry.\n */\n createOrUpdateGeometry() {\n const startPixel = this.startPixel_;\n const endPixel = this.endPixel_;\n const pixels = [\n startPixel,\n [startPixel[0], endPixel[1]],\n endPixel,\n [endPixel[0], startPixel[1]],\n ];\n const coordinates = pixels.map(\n this.map_.getCoordinateFromPixelInternal,\n this.map_\n );\n // close the polygon\n coordinates[4] = coordinates[0].slice();\n if (!this.geometry_) {\n this.geometry_ = new Polygon([coordinates]);\n } else {\n this.geometry_.setCoordinates([coordinates]);\n }\n }\n\n /**\n * @return {import(\"../geom/Polygon.js\").default} Geometry.\n */\n getGeometry() {\n return this.geometry_;\n }\n}\n\nexport default RenderBox;\n","/**\n * @module ol/interaction/DragBox\n */\n// FIXME draw drag box\nimport Event from '../events/Event.js';\nimport PointerInteraction from './Pointer.js';\nimport RenderBox from '../render/Box.js';\nimport {mouseActionButton} from '../events/condition.js';\n\n/**\n * A function that takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and two\n * {@link module:ol/pixel~Pixel}s and returns a `{boolean}`. If the condition is met,\n * true should be returned.\n * @typedef {function(this: ?, import(\"../MapBrowserEvent.js\").default, import(\"../pixel.js\").Pixel, import(\"../pixel.js\").Pixel):boolean} EndCondition\n */\n\n/**\n * @typedef {Object} Options\n * @property {string} [className='ol-dragbox'] CSS class name for styling the box.\n * @property {import(\"../events/condition.js\").Condition} [condition] A function that takes an {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a boolean\n * to indicate whether that event should be handled.\n * Default is {@link ol/events/condition~mouseActionButton}.\n * @property {number} [minArea=64] The minimum area of the box in pixel, this value is used by the default\n * `boxEndCondition` function.\n * @property {EndCondition} [boxEndCondition] A function that takes a {@link module:ol/MapBrowserEvent~MapBrowserEvent} and two\n * {@link module:ol/pixel~Pixel}s to indicate whether a `boxend` event should be fired.\n * Default is `true` if the area of the box is bigger than the `minArea` option.\n * @property {function(this:DragBox, import(\"../MapBrowserEvent.js\").default):void} [onBoxEnd] Code to execute just\n * before `boxend` is fired.\n */\n\n/**\n * @enum {string}\n */\nconst DragBoxEventType = {\n /**\n * Triggered upon drag box start.\n * @event DragBoxEvent#boxstart\n * @api\n */\n BOXSTART: 'boxstart',\n\n /**\n * Triggered on drag when box is active.\n * @event DragBoxEvent#boxdrag\n * @api\n */\n BOXDRAG: 'boxdrag',\n\n /**\n * Triggered upon drag box end.\n * @event DragBoxEvent#boxend\n * @api\n */\n BOXEND: 'boxend',\n\n /**\n * Triggered upon drag box canceled.\n * @event DragBoxEvent#boxcancel\n * @api\n */\n BOXCANCEL: 'boxcancel',\n};\n\n/**\n * @classdesc\n * Events emitted by {@link module:ol/interaction/DragBox~DragBox} instances are instances of\n * this type.\n */\nexport class DragBoxEvent extends Event {\n /**\n * @param {string} type The event type.\n * @param {import(\"../coordinate.js\").Coordinate} coordinate The event coordinate.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Originating event.\n */\n constructor(type, coordinate, mapBrowserEvent) {\n super(type);\n\n /**\n * The coordinate of the drag event.\n * @const\n * @type {import(\"../coordinate.js\").Coordinate}\n * @api\n */\n this.coordinate = coordinate;\n\n /**\n * @const\n * @type {import(\"../MapBrowserEvent.js\").default}\n * @api\n */\n this.mapBrowserEvent = mapBrowserEvent;\n }\n}\n\n/***\n * @template Return\n * @typedef {import(\"../Observable\").OnSignature &\n * import(\"../Observable\").OnSignature &\n * import(\"../Observable\").OnSignature<'boxcancel'|'boxdrag'|'boxend'|'boxstart', DragBoxEvent, Return> &\n * import(\"../Observable\").CombinedOnSignature} DragBoxOnSignature\n */\n\n/**\n * @classdesc\n * Allows the user to draw a vector box by clicking and dragging on the map,\n * normally combined with an {@link module:ol/events/condition} that limits\n * it to when the shift or other key is held down. This is used, for example,\n * for zooming to a specific area of the map\n * (see {@link module:ol/interaction/DragZoom~DragZoom} and\n * {@link module:ol/interaction/DragRotateAndZoom~DragRotateAndZoom}).\n *\n * @fires DragBoxEvent\n * @api\n */\nclass DragBox extends PointerInteraction {\n /**\n * @param {Options} [options] Options.\n */\n constructor(options) {\n super();\n\n /***\n * @type {DragBoxOnSignature}\n */\n this.on;\n\n /***\n * @type {DragBoxOnSignature}\n */\n this.once;\n\n /***\n * @type {DragBoxOnSignature}\n */\n this.un;\n\n options = options ? options : {};\n\n /**\n * @type {import(\"../render/Box.js\").default}\n * @private\n */\n this.box_ = new RenderBox(options.className || 'ol-dragbox');\n\n /**\n * @type {number}\n * @private\n */\n this.minArea_ = options.minArea !== undefined ? options.minArea : 64;\n\n if (options.onBoxEnd) {\n this.onBoxEnd = options.onBoxEnd;\n }\n\n /**\n * @type {import(\"../pixel.js\").Pixel}\n * @private\n */\n this.startPixel_ = null;\n\n /**\n * @private\n * @type {import(\"../events/condition.js\").Condition}\n */\n this.condition_ = options.condition ? options.condition : mouseActionButton;\n\n /**\n * @private\n * @type {EndCondition}\n */\n this.boxEndCondition_ = options.boxEndCondition\n ? options.boxEndCondition\n : this.defaultBoxEndCondition;\n }\n\n /**\n * The default condition for determining whether the boxend event\n * should fire.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent The originating MapBrowserEvent\n * leading to the box end.\n * @param {import(\"../pixel.js\").Pixel} startPixel The starting pixel of the box.\n * @param {import(\"../pixel.js\").Pixel} endPixel The end pixel of the box.\n * @return {boolean} Whether or not the boxend condition should be fired.\n */\n defaultBoxEndCondition(mapBrowserEvent, startPixel, endPixel) {\n const width = endPixel[0] - startPixel[0];\n const height = endPixel[1] - startPixel[1];\n return width * width + height * height >= this.minArea_;\n }\n\n /**\n * Returns geometry of last drawn box.\n * @return {import(\"../geom/Polygon.js\").default} Geometry.\n * @api\n */\n getGeometry() {\n return this.box_.getGeometry();\n }\n\n /**\n * Handle pointer drag events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n */\n handleDragEvent(mapBrowserEvent) {\n this.box_.setPixels(this.startPixel_, mapBrowserEvent.pixel);\n\n this.dispatchEvent(\n new DragBoxEvent(\n DragBoxEventType.BOXDRAG,\n mapBrowserEvent.coordinate,\n mapBrowserEvent\n )\n );\n }\n\n /**\n * Handle pointer up events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n * @return {boolean} If the event was consumed.\n */\n handleUpEvent(mapBrowserEvent) {\n this.box_.setMap(null);\n\n const completeBox = this.boxEndCondition_(\n mapBrowserEvent,\n this.startPixel_,\n mapBrowserEvent.pixel\n );\n if (completeBox) {\n this.onBoxEnd(mapBrowserEvent);\n }\n this.dispatchEvent(\n new DragBoxEvent(\n completeBox ? DragBoxEventType.BOXEND : DragBoxEventType.BOXCANCEL,\n mapBrowserEvent.coordinate,\n mapBrowserEvent\n )\n );\n return false;\n }\n\n /**\n * Handle pointer down events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n * @return {boolean} If the event was consumed.\n */\n handleDownEvent(mapBrowserEvent) {\n if (this.condition_(mapBrowserEvent)) {\n this.startPixel_ = mapBrowserEvent.pixel;\n this.box_.setMap(mapBrowserEvent.map);\n this.box_.setPixels(this.startPixel_, this.startPixel_);\n this.dispatchEvent(\n new DragBoxEvent(\n DragBoxEventType.BOXSTART,\n mapBrowserEvent.coordinate,\n mapBrowserEvent\n )\n );\n return true;\n }\n return false;\n }\n\n /**\n * Function to execute just before `onboxend` is fired\n * @param {import(\"../MapBrowserEvent.js\").default} event Event.\n */\n onBoxEnd(event) {}\n}\n\nexport default DragBox;\n","/**\n * @module ol/interaction/DragZoom\n */\nimport DragBox from './DragBox.js';\nimport {easeOut} from '../easing.js';\nimport {shiftKeyOnly} from '../events/condition.js';\n\n/**\n * @typedef {Object} Options\n * @property {string} [className='ol-dragzoom'] CSS class name for styling the\n * box.\n * @property {import(\"../events/condition.js\").Condition} [condition] A function that\n * takes an {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a\n * boolean to indicate whether that event should be handled.\n * Default is {@link module:ol/events/condition.shiftKeyOnly}.\n * @property {number} [duration=200] Animation duration in milliseconds.\n * @property {boolean} [out=false] Use interaction for zooming out.\n * @property {number} [minArea=64] The minimum area of the box in pixel, this value is used by the parent default\n * `boxEndCondition` function.\n */\n\n/**\n * @classdesc\n * Allows the user to zoom the map by clicking and dragging on the map,\n * normally combined with an {@link module:ol/events/condition} that limits\n * it to when a key, shift by default, is held down.\n *\n * To change the style of the box, use CSS and the `.ol-dragzoom` selector, or\n * your custom one configured with `className`.\n * @api\n */\nclass DragZoom extends DragBox {\n /**\n * @param {Options} [options] Options.\n */\n constructor(options) {\n options = options ? options : {};\n\n const condition = options.condition ? options.condition : shiftKeyOnly;\n\n super({\n condition: condition,\n className: options.className || 'ol-dragzoom',\n minArea: options.minArea,\n });\n\n /**\n * @private\n * @type {number}\n */\n this.duration_ = options.duration !== undefined ? options.duration : 200;\n\n /**\n * @private\n * @type {boolean}\n */\n this.out_ = options.out !== undefined ? options.out : false;\n }\n\n /**\n * Function to execute just before `onboxend` is fired\n * @param {import(\"../MapBrowserEvent.js\").default} event Event.\n */\n onBoxEnd(event) {\n const map = this.getMap();\n const view = /** @type {!import(\"../View.js\").default} */ (map.getView());\n let geometry = this.getGeometry();\n\n if (this.out_) {\n const rotatedExtent = view.rotatedExtentForGeometry(geometry);\n const resolution = view.getResolutionForExtentInternal(rotatedExtent);\n const factor = view.getResolution() / resolution;\n geometry = geometry.clone();\n geometry.scale(factor * factor);\n }\n\n view.fitInternal(geometry, {\n duration: this.duration_,\n easing: easeOut,\n });\n }\n}\n\nexport default DragZoom;\n","/**\n * @module ol/events/Key\n */\n\n/**\n * @enum {string}\n * @const\n */\nexport default {\n LEFT: 'ArrowLeft',\n UP: 'ArrowUp',\n RIGHT: 'ArrowRight',\n DOWN: 'ArrowDown',\n};\n","/**\n * @module ol/interaction/KeyboardPan\n */\nimport EventType from '../events/EventType.js';\nimport Interaction, {pan} from './Interaction.js';\nimport Key from '../events/Key.js';\nimport {noModifierKeys, targetNotEditable} from '../events/condition.js';\nimport {rotate as rotateCoordinate} from '../coordinate.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"../events/condition.js\").Condition} [condition] A function that\n * takes an {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a\n * boolean to indicate whether that event should be handled. Default is\n * {@link module:ol/events/condition.noModifierKeys} and\n * {@link module:ol/events/condition.targetNotEditable}.\n * @property {number} [duration=100] Animation duration in milliseconds.\n * @property {number} [pixelDelta=128] The amount of pixels to pan on each key\n * press.\n */\n\n/**\n * @classdesc\n * Allows the user to pan the map using keyboard arrows.\n * Note that, although this interaction is by default included in maps,\n * the keys can only be used when browser focus is on the element to which\n * the keyboard events are attached. By default, this is the map div,\n * though you can change this with the `keyboardEventTarget` in\n * {@link module:ol/Map~Map}. `document` never loses focus but, for any other\n * element, focus will have to be on, and returned to, this element if the keys\n * are to function.\n * See also {@link module:ol/interaction/KeyboardZoom~KeyboardZoom}.\n * @api\n */\nclass KeyboardPan extends Interaction {\n /**\n * @param {Options} [options] Options.\n */\n constructor(options) {\n super();\n\n options = options || {};\n\n /**\n * @private\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Browser event.\n * @return {boolean} Combined condition result.\n */\n this.defaultCondition_ = function (mapBrowserEvent) {\n return (\n noModifierKeys(mapBrowserEvent) && targetNotEditable(mapBrowserEvent)\n );\n };\n\n /**\n * @private\n * @type {import(\"../events/condition.js\").Condition}\n */\n this.condition_ =\n options.condition !== undefined\n ? options.condition\n : this.defaultCondition_;\n\n /**\n * @private\n * @type {number}\n */\n this.duration_ = options.duration !== undefined ? options.duration : 100;\n\n /**\n * @private\n * @type {number}\n */\n this.pixelDelta_ =\n options.pixelDelta !== undefined ? options.pixelDelta : 128;\n }\n\n /**\n * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} if it was a\n * `KeyEvent`, and decides the direction to pan to (if an arrow key was\n * pressed).\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} `false` to stop event propagation.\n */\n handleEvent(mapBrowserEvent) {\n let stopEvent = false;\n if (mapBrowserEvent.type == EventType.KEYDOWN) {\n const keyEvent = /** @type {KeyboardEvent} */ (\n mapBrowserEvent.originalEvent\n );\n const key = keyEvent.key;\n if (\n this.condition_(mapBrowserEvent) &&\n (key == Key.DOWN ||\n key == Key.LEFT ||\n key == Key.RIGHT ||\n key == Key.UP)\n ) {\n const map = mapBrowserEvent.map;\n const view = map.getView();\n const mapUnitsDelta = view.getResolution() * this.pixelDelta_;\n let deltaX = 0,\n deltaY = 0;\n if (key == Key.DOWN) {\n deltaY = -mapUnitsDelta;\n } else if (key == Key.LEFT) {\n deltaX = -mapUnitsDelta;\n } else if (key == Key.RIGHT) {\n deltaX = mapUnitsDelta;\n } else {\n deltaY = mapUnitsDelta;\n }\n const delta = [deltaX, deltaY];\n rotateCoordinate(delta, view.getRotation());\n pan(view, delta, this.duration_);\n keyEvent.preventDefault();\n stopEvent = true;\n }\n }\n return !stopEvent;\n }\n}\n\nexport default KeyboardPan;\n","/**\n * @module ol/interaction/KeyboardZoom\n */\nimport EventType from '../events/EventType.js';\nimport Interaction, {zoomByDelta} from './Interaction.js';\nimport {platformModifierKey, targetNotEditable} from '../events/condition.js';\n\n/**\n * @typedef {Object} Options\n * @property {number} [duration=100] Animation duration in milliseconds.\n * @property {import(\"../events/condition.js\").Condition} [condition] A function that\n * takes an {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a\n * boolean to indicate whether that event should be handled. The default condition is\n * that {@link module:ol/events/condition.targetNotEditable} is fulfilled and that\n * the platform modifier key isn't pressed\n * (!{@link module:ol/events/condition.platformModifierKey}).\n * @property {number} [delta=1] The zoom level delta on each key press.\n */\n\n/**\n * @classdesc\n * Allows the user to zoom the map using keyboard + and -.\n * Note that, although this interaction is by default included in maps,\n * the keys can only be used when browser focus is on the element to which\n * the keyboard events are attached. By default, this is the map div,\n * though you can change this with the `keyboardEventTarget` in\n * {@link module:ol/Map~Map}. `document` never loses focus but, for any other\n * element, focus will have to be on, and returned to, this element if the keys\n * are to function.\n * See also {@link module:ol/interaction/KeyboardPan~KeyboardPan}.\n * @api\n */\nclass KeyboardZoom extends Interaction {\n /**\n * @param {Options} [options] Options.\n */\n constructor(options) {\n super();\n\n options = options ? options : {};\n\n /**\n * @private\n * @type {import(\"../events/condition.js\").Condition}\n */\n this.condition_ = options.condition\n ? options.condition\n : function (mapBrowserEvent) {\n return (\n !platformModifierKey(mapBrowserEvent) &&\n targetNotEditable(mapBrowserEvent)\n );\n };\n\n /**\n * @private\n * @type {number}\n */\n this.delta_ = options.delta ? options.delta : 1;\n\n /**\n * @private\n * @type {number}\n */\n this.duration_ = options.duration !== undefined ? options.duration : 100;\n }\n\n /**\n * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} if it was a\n * `KeyEvent`, and decides whether to zoom in or out (depending on whether the\n * key pressed was '+' or '-').\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} `false` to stop event propagation.\n */\n handleEvent(mapBrowserEvent) {\n let stopEvent = false;\n if (\n mapBrowserEvent.type == EventType.KEYDOWN ||\n mapBrowserEvent.type == EventType.KEYPRESS\n ) {\n const keyEvent = /** @type {KeyboardEvent} */ (\n mapBrowserEvent.originalEvent\n );\n const key = keyEvent.key;\n if (this.condition_(mapBrowserEvent) && (key === '+' || key === '-')) {\n const map = mapBrowserEvent.map;\n const delta = key === '+' ? this.delta_ : -this.delta_;\n const view = map.getView();\n zoomByDelta(view, delta, undefined, this.duration_);\n keyEvent.preventDefault();\n stopEvent = true;\n }\n }\n return !stopEvent;\n }\n}\n\nexport default KeyboardZoom;\n","/**\n * @module ol/interaction/MouseWheelZoom\n */\nimport EventType from '../events/EventType.js';\nimport Interaction, {zoomByDelta} from './Interaction.js';\nimport {DEVICE_PIXEL_RATIO, FIREFOX} from '../has.js';\nimport {all, always, focusWithTabindex} from '../events/condition.js';\nimport {clamp} from '../math.js';\n\n/**\n * @typedef {'trackpad' | 'wheel'} Mode\n */\n\n/**\n * @typedef {Object} Options\n * @property {import(\"../events/condition.js\").Condition} [condition] A function that\n * takes an {@link module:ol/MapBrowserEvent~MapBrowserEvent} and returns a\n * boolean to indicate whether that event should be handled. Default is\n * {@link module:ol/events/condition.always}.\n * @property {boolean} [onFocusOnly=false] When the map's target has a `tabindex` attribute set,\n * the interaction will only handle events when the map has the focus.\n * @property {number} [maxDelta=1] Maximum mouse wheel delta.\n * @property {number} [duration=250] Animation duration in milliseconds.\n * @property {number} [timeout=80] Mouse wheel timeout duration in milliseconds.\n * @property {boolean} [useAnchor=true] Enable zooming using the mouse's\n * location as the anchor. When set to `false`, zooming in and out will zoom to\n * the center of the screen instead of zooming on the mouse's location.\n * @property {boolean} [constrainResolution=false] If true, the mouse wheel zoom\n * event will always animate to the closest zoom level after an interaction;\n * false means intermediary zoom levels are allowed.\n */\n\n/**\n * @classdesc\n * Allows the user to zoom the map by scrolling the mouse wheel.\n * @api\n */\nclass MouseWheelZoom extends Interaction {\n /**\n * @param {Options} [options] Options.\n */\n constructor(options) {\n options = options ? options : {};\n\n super(\n /** @type {import(\"./Interaction.js\").InteractionOptions} */ (options)\n );\n\n /**\n * @private\n * @type {number}\n */\n this.totalDelta_ = 0;\n\n /**\n * @private\n * @type {number}\n */\n this.lastDelta_ = 0;\n\n /**\n * @private\n * @type {number}\n */\n this.maxDelta_ = options.maxDelta !== undefined ? options.maxDelta : 1;\n\n /**\n * @private\n * @type {number}\n */\n this.duration_ = options.duration !== undefined ? options.duration : 250;\n\n /**\n * @private\n * @type {number}\n */\n this.timeout_ = options.timeout !== undefined ? options.timeout : 80;\n\n /**\n * @private\n * @type {boolean}\n */\n this.useAnchor_ =\n options.useAnchor !== undefined ? options.useAnchor : true;\n\n /**\n * @private\n * @type {boolean}\n */\n this.constrainResolution_ =\n options.constrainResolution !== undefined\n ? options.constrainResolution\n : false;\n\n const condition = options.condition ? options.condition : always;\n\n /**\n * @private\n * @type {import(\"../events/condition.js\").Condition}\n */\n this.condition_ = options.onFocusOnly\n ? all(focusWithTabindex, condition)\n : condition;\n\n /**\n * @private\n * @type {?import(\"../coordinate.js\").Coordinate}\n */\n this.lastAnchor_ = null;\n\n /**\n * @private\n * @type {number|undefined}\n */\n this.startTime_ = undefined;\n\n /**\n * @private\n * @type {ReturnType}\n */\n this.timeoutId_;\n\n /**\n * @private\n * @type {Mode|undefined}\n */\n this.mode_ = undefined;\n\n /**\n * Trackpad events separated by this delay will be considered separate\n * interactions.\n * @private\n * @type {number}\n */\n this.trackpadEventGap_ = 400;\n\n /**\n * @private\n * @type {ReturnType}\n */\n this.trackpadTimeoutId_;\n\n /**\n * The number of delta values per zoom level\n * @private\n * @type {number}\n */\n this.deltaPerZoom_ = 300;\n }\n\n /**\n * @private\n */\n endInteraction_() {\n this.trackpadTimeoutId_ = undefined;\n const map = this.getMap();\n if (!map) {\n return;\n }\n const view = map.getView();\n view.endInteraction(\n undefined,\n this.lastDelta_ ? (this.lastDelta_ > 0 ? 1 : -1) : 0,\n this.lastAnchor_\n );\n }\n\n /**\n * Handles the {@link module:ol/MapBrowserEvent~MapBrowserEvent map browser event} (if it was a mousewheel-event) and eventually\n * zooms the map.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Map browser event.\n * @return {boolean} `false` to stop event propagation.\n */\n handleEvent(mapBrowserEvent) {\n if (!this.condition_(mapBrowserEvent)) {\n return true;\n }\n const type = mapBrowserEvent.type;\n if (type !== EventType.WHEEL) {\n return true;\n }\n\n const map = mapBrowserEvent.map;\n const wheelEvent = /** @type {WheelEvent} */ (\n mapBrowserEvent.originalEvent\n );\n wheelEvent.preventDefault();\n\n if (this.useAnchor_) {\n this.lastAnchor_ = mapBrowserEvent.coordinate;\n }\n\n // Delta normalisation inspired by\n // https://github.com/mapbox/mapbox-gl-js/blob/001c7b9/js/ui/handler/scroll_zoom.js\n let delta;\n if (mapBrowserEvent.type == EventType.WHEEL) {\n delta = wheelEvent.deltaY;\n if (FIREFOX && wheelEvent.deltaMode === WheelEvent.DOM_DELTA_PIXEL) {\n delta /= DEVICE_PIXEL_RATIO;\n }\n if (wheelEvent.deltaMode === WheelEvent.DOM_DELTA_LINE) {\n delta *= 40;\n }\n }\n\n if (delta === 0) {\n return false;\n }\n this.lastDelta_ = delta;\n\n const now = Date.now();\n\n if (this.startTime_ === undefined) {\n this.startTime_ = now;\n }\n\n if (!this.mode_ || now - this.startTime_ > this.trackpadEventGap_) {\n this.mode_ = Math.abs(delta) < 4 ? 'trackpad' : 'wheel';\n }\n\n const view = map.getView();\n if (\n this.mode_ === 'trackpad' &&\n !(view.getConstrainResolution() || this.constrainResolution_)\n ) {\n if (this.trackpadTimeoutId_) {\n clearTimeout(this.trackpadTimeoutId_);\n } else {\n if (view.getAnimating()) {\n view.cancelAnimations();\n }\n view.beginInteraction();\n }\n this.trackpadTimeoutId_ = setTimeout(\n this.endInteraction_.bind(this),\n this.timeout_\n );\n view.adjustZoom(-delta / this.deltaPerZoom_, this.lastAnchor_);\n this.startTime_ = now;\n return false;\n }\n\n this.totalDelta_ += delta;\n\n const timeLeft = Math.max(this.timeout_ - (now - this.startTime_), 0);\n\n clearTimeout(this.timeoutId_);\n this.timeoutId_ = setTimeout(\n this.handleWheelZoom_.bind(this, map),\n timeLeft\n );\n\n return false;\n }\n\n /**\n * @private\n * @param {import(\"../Map.js\").default} map Map.\n */\n handleWheelZoom_(map) {\n const view = map.getView();\n if (view.getAnimating()) {\n view.cancelAnimations();\n }\n let delta =\n -clamp(\n this.totalDelta_,\n -this.maxDelta_ * this.deltaPerZoom_,\n this.maxDelta_ * this.deltaPerZoom_\n ) / this.deltaPerZoom_;\n if (view.getConstrainResolution() || this.constrainResolution_) {\n // view has a zoom constraint, zoom by 1\n delta = delta ? (delta > 0 ? 1 : -1) : 0;\n }\n zoomByDelta(view, delta, this.lastAnchor_, this.duration_);\n\n this.mode_ = undefined;\n this.totalDelta_ = 0;\n this.lastAnchor_ = null;\n this.startTime_ = undefined;\n this.timeoutId_ = undefined;\n }\n\n /**\n * Enable or disable using the mouse's location as an anchor when zooming\n * @param {boolean} useAnchor true to zoom to the mouse's location, false\n * to zoom to the center of the map\n * @api\n */\n setMouseAnchor(useAnchor) {\n this.useAnchor_ = useAnchor;\n if (!useAnchor) {\n this.lastAnchor_ = null;\n }\n }\n}\n\nexport default MouseWheelZoom;\n","/**\n * @module ol/interaction/PinchRotate\n */\nimport PointerInteraction, {\n centroid as centroidFromPointers,\n} from './Pointer.js';\nimport {FALSE} from '../functions.js';\nimport {disable} from '../rotationconstraint.js';\n\n/**\n * @typedef {Object} Options\n * @property {number} [duration=250] The duration of the animation in\n * milliseconds.\n * @property {number} [threshold=0.3] Minimal angle in radians to start a rotation.\n */\n\n/**\n * @classdesc\n * Allows the user to rotate the map by twisting with two fingers\n * on a touch screen.\n * @api\n */\nclass PinchRotate extends PointerInteraction {\n /**\n * @param {Options} [options] Options.\n */\n constructor(options) {\n options = options ? options : {};\n\n const pointerOptions = /** @type {import(\"./Pointer.js\").Options} */ (\n options\n );\n\n if (!pointerOptions.stopDown) {\n pointerOptions.stopDown = FALSE;\n }\n\n super(pointerOptions);\n\n /**\n * @private\n * @type {import(\"../coordinate.js\").Coordinate}\n */\n this.anchor_ = null;\n\n /**\n * @private\n * @type {number|undefined}\n */\n this.lastAngle_ = undefined;\n\n /**\n * @private\n * @type {boolean}\n */\n this.rotating_ = false;\n\n /**\n * @private\n * @type {number}\n */\n this.rotationDelta_ = 0.0;\n\n /**\n * @private\n * @type {number}\n */\n this.threshold_ = options.threshold !== undefined ? options.threshold : 0.3;\n\n /**\n * @private\n * @type {number}\n */\n this.duration_ = options.duration !== undefined ? options.duration : 250;\n }\n\n /**\n * Handle pointer drag events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n */\n handleDragEvent(mapBrowserEvent) {\n let rotationDelta = 0.0;\n\n const touch0 = this.targetPointers[0];\n const touch1 = this.targetPointers[1];\n\n // angle between touches\n const angle = Math.atan2(\n touch1.clientY - touch0.clientY,\n touch1.clientX - touch0.clientX\n );\n\n if (this.lastAngle_ !== undefined) {\n const delta = angle - this.lastAngle_;\n this.rotationDelta_ += delta;\n if (!this.rotating_ && Math.abs(this.rotationDelta_) > this.threshold_) {\n this.rotating_ = true;\n }\n rotationDelta = delta;\n }\n this.lastAngle_ = angle;\n\n const map = mapBrowserEvent.map;\n const view = map.getView();\n if (view.getConstraints().rotation === disable) {\n return;\n }\n\n // rotate anchor point.\n // FIXME: should be the intersection point between the lines:\n // touch0,touch1 and previousTouch0,previousTouch1\n this.anchor_ = map.getCoordinateFromPixelInternal(\n map.getEventPixel(centroidFromPointers(this.targetPointers))\n );\n\n // rotate\n if (this.rotating_) {\n map.render();\n view.adjustRotationInternal(rotationDelta, this.anchor_);\n }\n }\n\n /**\n * Handle pointer up events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n * @return {boolean} If the event was consumed.\n */\n handleUpEvent(mapBrowserEvent) {\n if (this.targetPointers.length < 2) {\n const map = mapBrowserEvent.map;\n const view = map.getView();\n view.endInteraction(this.duration_);\n return false;\n }\n return true;\n }\n\n /**\n * Handle pointer down events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n * @return {boolean} If the event was consumed.\n */\n handleDownEvent(mapBrowserEvent) {\n if (this.targetPointers.length >= 2) {\n const map = mapBrowserEvent.map;\n this.anchor_ = null;\n this.lastAngle_ = undefined;\n this.rotating_ = false;\n this.rotationDelta_ = 0.0;\n if (!this.handlingDownUpSequence) {\n map.getView().beginInteraction();\n }\n return true;\n }\n return false;\n }\n}\n\nexport default PinchRotate;\n","/**\n * @module ol/interaction/PinchZoom\n */\nimport PointerInteraction, {\n centroid as centroidFromPointers,\n} from './Pointer.js';\nimport {FALSE} from '../functions.js';\n\n/**\n * @typedef {Object} Options\n * @property {number} [duration=400] Animation duration in milliseconds.\n */\n\n/**\n * @classdesc\n * Allows the user to zoom the map by pinching with two fingers\n * on a touch screen.\n * @api\n */\nclass PinchZoom extends PointerInteraction {\n /**\n * @param {Options} [options] Options.\n */\n constructor(options) {\n options = options ? options : {};\n\n const pointerOptions = /** @type {import(\"./Pointer.js\").Options} */ (\n options\n );\n\n if (!pointerOptions.stopDown) {\n pointerOptions.stopDown = FALSE;\n }\n\n super(pointerOptions);\n\n /**\n * @private\n * @type {import(\"../coordinate.js\").Coordinate}\n */\n this.anchor_ = null;\n\n /**\n * @private\n * @type {number}\n */\n this.duration_ = options.duration !== undefined ? options.duration : 400;\n\n /**\n * @private\n * @type {number|undefined}\n */\n this.lastDistance_ = undefined;\n\n /**\n * @private\n * @type {number}\n */\n this.lastScaleDelta_ = 1;\n }\n\n /**\n * Handle pointer drag events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n */\n handleDragEvent(mapBrowserEvent) {\n let scaleDelta = 1.0;\n\n const touch0 = this.targetPointers[0];\n const touch1 = this.targetPointers[1];\n const dx = touch0.clientX - touch1.clientX;\n const dy = touch0.clientY - touch1.clientY;\n\n // distance between touches\n const distance = Math.sqrt(dx * dx + dy * dy);\n\n if (this.lastDistance_ !== undefined) {\n scaleDelta = this.lastDistance_ / distance;\n }\n this.lastDistance_ = distance;\n\n const map = mapBrowserEvent.map;\n const view = map.getView();\n\n if (scaleDelta != 1.0) {\n this.lastScaleDelta_ = scaleDelta;\n }\n\n // scale anchor point.\n this.anchor_ = map.getCoordinateFromPixelInternal(\n map.getEventPixel(centroidFromPointers(this.targetPointers))\n );\n\n // scale, bypass the resolution constraint\n map.render();\n view.adjustResolutionInternal(scaleDelta, this.anchor_);\n }\n\n /**\n * Handle pointer up events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n * @return {boolean} If the event was consumed.\n */\n handleUpEvent(mapBrowserEvent) {\n if (this.targetPointers.length < 2) {\n const map = mapBrowserEvent.map;\n const view = map.getView();\n const direction = this.lastScaleDelta_ > 1 ? 1 : -1;\n view.endInteraction(this.duration_, direction);\n return false;\n }\n return true;\n }\n\n /**\n * Handle pointer down events.\n * @param {import(\"../MapBrowserEvent.js\").default} mapBrowserEvent Event.\n * @return {boolean} If the event was consumed.\n */\n handleDownEvent(mapBrowserEvent) {\n if (this.targetPointers.length >= 2) {\n const map = mapBrowserEvent.map;\n this.anchor_ = null;\n this.lastDistance_ = undefined;\n this.lastScaleDelta_ = 1;\n if (!this.handlingDownUpSequence) {\n map.getView().beginInteraction();\n }\n return true;\n }\n return false;\n }\n}\n\nexport default PinchZoom;\n","/**\n * @module ol/interaction/defaults\n */\nimport Collection from '../Collection.js';\nimport DoubleClickZoom from './DoubleClickZoom.js';\nimport DragPan from './DragPan.js';\nimport DragRotate from './DragRotate.js';\nimport DragZoom from './DragZoom.js';\nimport KeyboardPan from './KeyboardPan.js';\nimport KeyboardZoom from './KeyboardZoom.js';\nimport Kinetic from '../Kinetic.js';\nimport MouseWheelZoom from './MouseWheelZoom.js';\nimport PinchRotate from './PinchRotate.js';\nimport PinchZoom from './PinchZoom.js';\n\n/**\n * @typedef {Object} DefaultsOptions\n * @property {boolean} [altShiftDragRotate=true] Whether Alt-Shift-drag rotate is\n * desired.\n * @property {boolean} [onFocusOnly=false] Interact only when the map has the\n * focus. This affects the `MouseWheelZoom` and `DragPan` interactions and is\n * useful when page scroll is desired for maps that do not have the browser's\n * focus.\n * @property {boolean} [doubleClickZoom=true] Whether double click zoom is\n * desired.\n * @property {boolean} [keyboard=true] Whether keyboard interaction is desired.\n * @property {boolean} [mouseWheelZoom=true] Whether mousewheel zoom is desired.\n * @property {boolean} [shiftDragZoom=true] Whether Shift-drag zoom is desired.\n * @property {boolean} [dragPan=true] Whether drag pan is desired.\n * @property {boolean} [pinchRotate=true] Whether pinch rotate is desired.\n * @property {boolean} [pinchZoom=true] Whether pinch zoom is desired.\n * @property {number} [zoomDelta] Zoom level delta when using keyboard or double click zoom.\n * @property {number} [zoomDuration] Duration of the zoom animation in\n * milliseconds.\n */\n\n/**\n * Set of interactions included in maps by default. Specific interactions can be\n * excluded by setting the appropriate option to false in the constructor\n * options, but the order of the interactions is fixed. If you want to specify\n * a different order for interactions, you will need to create your own\n * {@link module:ol/interaction/Interaction~Interaction} instances and insert\n * them into a {@link module:ol/Collection~Collection} in the order you want\n * before creating your {@link module:ol/Map~Map} instance. Changing the order can\n * be of interest if the event propagation needs to be stopped at a point.\n * The default set of interactions, in sequence, is:\n * * {@link module:ol/interaction/DragRotate~DragRotate}\n * * {@link module:ol/interaction/DoubleClickZoom~DoubleClickZoom}\n * * {@link module:ol/interaction/DragPan~DragPan}\n * * {@link module:ol/interaction/PinchRotate~PinchRotate}\n * * {@link module:ol/interaction/PinchZoom~PinchZoom}\n * * {@link module:ol/interaction/KeyboardPan~KeyboardPan}\n * * {@link module:ol/interaction/KeyboardZoom~KeyboardZoom}\n * * {@link module:ol/interaction/MouseWheelZoom~MouseWheelZoom}\n * * {@link module:ol/interaction/DragZoom~DragZoom}\n *\n * @param {DefaultsOptions} [options] Defaults options.\n * @return {Collection}\n * A collection of interactions to be used with the {@link module:ol/Map~Map}\n * constructor's `interactions` option.\n * @api\n */\nexport function defaults(options) {\n options = options ? options : {};\n\n /** @type {Collection} */\n const interactions = new Collection();\n\n const kinetic = new Kinetic(-0.005, 0.05, 100);\n\n const altShiftDragRotate =\n options.altShiftDragRotate !== undefined\n ? options.altShiftDragRotate\n : true;\n if (altShiftDragRotate) {\n interactions.push(new DragRotate());\n }\n\n const doubleClickZoom =\n options.doubleClickZoom !== undefined ? options.doubleClickZoom : true;\n if (doubleClickZoom) {\n interactions.push(\n new DoubleClickZoom({\n delta: options.zoomDelta,\n duration: options.zoomDuration,\n })\n );\n }\n\n const dragPan = options.dragPan !== undefined ? options.dragPan : true;\n if (dragPan) {\n interactions.push(\n new DragPan({\n onFocusOnly: options.onFocusOnly,\n kinetic: kinetic,\n })\n );\n }\n\n const pinchRotate =\n options.pinchRotate !== undefined ? options.pinchRotate : true;\n if (pinchRotate) {\n interactions.push(new PinchRotate());\n }\n\n const pinchZoom = options.pinchZoom !== undefined ? options.pinchZoom : true;\n if (pinchZoom) {\n interactions.push(\n new PinchZoom({\n duration: options.zoomDuration,\n })\n );\n }\n\n const keyboard = options.keyboard !== undefined ? options.keyboard : true;\n if (keyboard) {\n interactions.push(new KeyboardPan());\n interactions.push(\n new KeyboardZoom({\n delta: options.zoomDelta,\n duration: options.zoomDuration,\n })\n );\n }\n\n const mouseWheelZoom =\n options.mouseWheelZoom !== undefined ? options.mouseWheelZoom : true;\n if (mouseWheelZoom) {\n interactions.push(\n new MouseWheelZoom({\n onFocusOnly: options.onFocusOnly,\n duration: options.zoomDuration,\n })\n );\n }\n\n const shiftDragZoom =\n options.shiftDragZoom !== undefined ? options.shiftDragZoom : true;\n if (shiftDragZoom) {\n interactions.push(\n new DragZoom({\n duration: options.zoomDuration,\n })\n );\n }\n\n return interactions;\n}\n","/**\n * @module ol/size\n */\n\n/**\n * An array of numbers representing a size: `[width, height]`.\n * @typedef {Array} Size\n * @api\n */\n\n/**\n * Returns a buffered size.\n * @param {Size} size Size.\n * @param {number} num The amount by which to buffer.\n * @param {Size} [dest] Optional reusable size array.\n * @return {Size} The buffered size.\n */\nexport function buffer(size, num, dest) {\n if (dest === undefined) {\n dest = [0, 0];\n }\n dest[0] = size[0] + 2 * num;\n dest[1] = size[1] + 2 * num;\n return dest;\n}\n\n/**\n * Determines if a size has a positive area.\n * @param {Size} size The size to test.\n * @return {boolean} The size has a positive area.\n */\nexport function hasArea(size) {\n return size[0] > 0 && size[1] > 0;\n}\n\n/**\n * Returns a size scaled by a ratio. The result will be an array of integers.\n * @param {Size} size Size.\n * @param {number} ratio Ratio.\n * @param {Size} [dest] Optional reusable size array.\n * @return {Size} The scaled size.\n */\nexport function scale(size, ratio, dest) {\n if (dest === undefined) {\n dest = [0, 0];\n }\n dest[0] = (size[0] * ratio + 0.5) | 0;\n dest[1] = (size[1] * ratio + 0.5) | 0;\n return dest;\n}\n\n/**\n * Returns an `Size` array for the passed in number (meaning: square) or\n * `Size` array.\n * (meaning: non-square),\n * @param {number|Size} size Width and height.\n * @param {Size} [dest] Optional reusable size array.\n * @return {Size} Size.\n * @api\n */\nexport function toSize(size, dest) {\n if (Array.isArray(size)) {\n return size;\n }\n if (dest === undefined) {\n dest = [size, size];\n } else {\n dest[0] = size;\n dest[1] = size;\n }\n return dest;\n}\n","/**\n * @module ol/Map\n */\nimport BaseObject from './Object.js';\nimport Collection from './Collection.js';\nimport CollectionEventType from './CollectionEventType.js';\nimport CompositeMapRenderer from './renderer/Composite.js';\nimport EventType from './events/EventType.js';\nimport Layer from './layer/Layer.js';\nimport LayerGroup, {GroupEvent} from './layer/Group.js';\nimport MapBrowserEvent from './MapBrowserEvent.js';\nimport MapBrowserEventHandler from './MapBrowserEventHandler.js';\nimport MapBrowserEventType from './MapBrowserEventType.js';\nimport MapEvent from './MapEvent.js';\nimport MapEventType from './MapEventType.js';\nimport MapProperty from './MapProperty.js';\nimport ObjectEventType from './ObjectEventType.js';\nimport PointerEventType from './pointer/EventType.js';\nimport RenderEventType from './render/EventType.js';\nimport TileQueue, {getTilePriority} from './TileQueue.js';\nimport View from './View.js';\nimport ViewHint from './ViewHint.js';\nimport {DEVICE_PIXEL_RATIO, PASSIVE_EVENT_LISTENERS} from './has.js';\nimport {TRUE} from './functions.js';\nimport {\n apply as applyTransform,\n create as createTransform,\n} from './transform.js';\nimport {assert} from './asserts.js';\nimport {\n clone,\n createOrUpdateEmpty,\n equals as equalsExtent,\n getForViewAndSize,\n isEmpty,\n} from './extent.js';\nimport {defaults as defaultControls} from './control/defaults.js';\nimport {defaults as defaultInteractions} from './interaction/defaults.js';\nimport {equals} from './array.js';\nimport {fromUserCoordinate, toUserCoordinate} from './proj.js';\nimport {getUid} from './util.js';\nimport {hasArea} from './size.js';\nimport {listen, unlistenByKey} from './events.js';\nimport {removeNode} from './dom.js';\nimport {warn} from './console.js';\n\n/**\n * State of the current frame. Only `pixelRatio`, `time` and `viewState` should\n * be used in applications.\n * @typedef {Object} FrameState\n * @property {number} pixelRatio The pixel ratio of the frame.\n * @property {number} time The time when rendering of the frame was requested.\n * @property {import(\"./View.js\").State} viewState The state of the current view.\n * @property {boolean} animate Animate.\n * @property {import(\"./transform.js\").Transform} coordinateToPixelTransform CoordinateToPixelTransform.\n * @property {import(\"rbush\").default} declutterTree DeclutterTree.\n * @property {null|import(\"./extent.js\").Extent} extent Extent (in view projection coordinates).\n * @property {import(\"./extent.js\").Extent} [nextExtent] Next extent during an animation series.\n * @property {number} index Index.\n * @property {Array} layerStatesArray LayerStatesArray.\n * @property {number} layerIndex LayerIndex.\n * @property {import(\"./transform.js\").Transform} pixelToCoordinateTransform PixelToCoordinateTransform.\n * @property {Array} postRenderFunctions PostRenderFunctions.\n * @property {import(\"./size.js\").Size} size Size.\n * @property {TileQueue} tileQueue TileQueue.\n * @property {!Object>} usedTiles UsedTiles.\n * @property {Array} viewHints ViewHints.\n * @property {!Object>} wantedTiles WantedTiles.\n * @property {string} mapId The id of the map.\n * @property {Object} renderTargets Identifiers of previously rendered elements.\n */\n\n/**\n * @typedef {function(Map, ?FrameState): any} PostRenderFunction\n */\n\n/**\n * @typedef {Object} AtPixelOptions\n * @property {undefined|function(import(\"./layer/Layer.js\").default): boolean} [layerFilter] Layer filter\n * function. The filter function will receive one argument, the\n * {@link module:ol/layer/Layer~Layer layer-candidate} and it should return a boolean value.\n * Only layers which are visible and for which this function returns `true`\n * will be tested for features. By default, all visible layers will be tested.\n * @property {number} [hitTolerance=0] Hit-detection tolerance in css pixels. Pixels\n * inside the radius around the given position will be checked for features.\n * @property {boolean} [checkWrapped=true] Check-Wrapped Will check for wrapped geometries inside the range of\n * +/- 1 world width. Works only if a projection is used that can be wrapped.\n */\n\n/**\n * @typedef {Object} MapOptionsInternal\n * @property {Collection} [controls] Controls.\n * @property {Collection} [interactions] Interactions.\n * @property {HTMLElement|Document} keyboardEventTarget KeyboardEventTarget.\n * @property {Collection} overlays Overlays.\n * @property {Object} values Values.\n */\n\n/**\n * @typedef {import(\"./ObjectEventType\").Types|'change:layergroup'|'change:size'|'change:target'|'change:view'} MapObjectEventTypes\n */\n\n/***\n * @template Return\n * @typedef {import(\"./Observable\").OnSignature &\n * import(\"./Observable\").OnSignature &\n * import(\"./Observable\").OnSignature &\n * import(\"./Observable\").OnSignature &\n * import(\"./Observable\").OnSignature &\n * import(\"./Observable\").CombinedOnSignature} MapEventHandler\n */\n\n/**\n * Object literal with config options for the map.\n * @typedef {Object} MapOptions\n * @property {Collection|Array} [controls]\n * Controls initially added to the map. If not specified,\n * {@link module:ol/control/defaults.defaults} is used.\n * @property {number} [pixelRatio=window.devicePixelRatio] The ratio between\n * physical pixels and device-independent pixels (dips) on the device.\n * @property {Collection|Array} [interactions]\n * Interactions that are initially added to the map. If not specified,\n * {@link module:ol/interaction/defaults.defaults} is used.\n * @property {HTMLElement|Document|string} [keyboardEventTarget] The element to\n * listen to keyboard events on. This determines when the `KeyboardPan` and\n * `KeyboardZoom` interactions trigger. For example, if this option is set to\n * `document` the keyboard interactions will always trigger. If this option is\n * not specified, the element the library listens to keyboard events on is the\n * map target (i.e. the user-provided div for the map). If this is not\n * `document`, the target element needs to be focused for key events to be\n * emitted, requiring that the target element has a `tabindex` attribute.\n * @property {Array|Collection|LayerGroup} [layers]\n * Layers. If this is not defined, a map with no layers will be rendered. Note\n * that layers are rendered in the order supplied, so if you want, for example,\n * a vector layer to appear on top of a tile layer, it must come after the tile\n * layer.\n * @property {number} [maxTilesLoading=16] Maximum number tiles to load\n * simultaneously.\n * @property {number} [moveTolerance=1] The minimum distance in pixels the\n * cursor must move to be detected as a map move event instead of a click.\n * Increasing this value can make it easier to click on the map.\n * @property {Collection|Array} [overlays]\n * Overlays initially added to the map. By default, no overlays are added.\n * @property {HTMLElement|string} [target] The container for the map, either the\n * element itself or the `id` of the element. If not specified at construction\n * time, {@link module:ol/Map~Map#setTarget} must be called for the map to be\n * rendered. If passed by element, the container can be in a secondary document.\n * **Note:** CSS `transform` support for the target element is limited to `scale`.\n * @property {View|Promise} [view] The map's view. No layer sources will be\n * fetched unless this is specified at construction time or through\n * {@link module:ol/Map~Map#setView}.\n */\n\n/**\n * @param {import(\"./layer/Base.js\").default} layer Layer.\n */\nfunction removeLayerMapProperty(layer) {\n if (layer instanceof Layer) {\n layer.setMapInternal(null);\n return;\n }\n if (layer instanceof LayerGroup) {\n layer.getLayers().forEach(removeLayerMapProperty);\n }\n}\n\n/**\n * @param {import(\"./layer/Base.js\").default} layer Layer.\n * @param {Map} map Map.\n */\nfunction setLayerMapProperty(layer, map) {\n if (layer instanceof Layer) {\n layer.setMapInternal(map);\n return;\n }\n if (layer instanceof LayerGroup) {\n const layers = layer.getLayers().getArray();\n for (let i = 0, ii = layers.length; i < ii; ++i) {\n setLayerMapProperty(layers[i], map);\n }\n }\n}\n\n/**\n * @classdesc\n * The map is the core component of OpenLayers. For a map to render, a view,\n * one or more layers, and a target container are needed:\n *\n * import Map from 'ol/Map.js';\n * import View from 'ol/View.js';\n * import TileLayer from 'ol/layer/Tile.js';\n * import OSM from 'ol/source/OSM.js';\n *\n * const map = new Map({\n * view: new View({\n * center: [0, 0],\n * zoom: 1,\n * }),\n * layers: [\n * new TileLayer({\n * source: new OSM(),\n * }),\n * ],\n * target: 'map',\n * });\n *\n * The above snippet creates a map using a {@link module:ol/layer/Tile~TileLayer} to\n * display {@link module:ol/source/OSM~OSM} OSM data and render it to a DOM\n * element with the id `map`.\n *\n * The constructor places a viewport container (with CSS class name\n * `ol-viewport`) in the target element (see `getViewport()`), and then two\n * further elements within the viewport: one with CSS class name\n * `ol-overlaycontainer-stopevent` for controls and some overlays, and one with\n * CSS class name `ol-overlaycontainer` for other overlays (see the `stopEvent`\n * option of {@link module:ol/Overlay~Overlay} for the difference). The map\n * itself is placed in a further element within the viewport.\n *\n * Layers are stored as a {@link module:ol/Collection~Collection} in\n * layerGroups. A top-level group is provided by the library. This is what is\n * accessed by `getLayerGroup` and `setLayerGroup`. Layers entered in the\n * options are added to this group, and `addLayer` and `removeLayer` change the\n * layer collection in the group. `getLayers` is a convenience function for\n * `getLayerGroup().getLayers()`. Note that {@link module:ol/layer/Group~LayerGroup}\n * is a subclass of {@link module:ol/layer/Base~BaseLayer}, so layers entered in the\n * options or added with `addLayer` can be groups, which can contain further\n * groups, and so on.\n *\n * @fires import(\"./MapBrowserEvent.js\").MapBrowserEvent\n * @fires import(\"./MapEvent.js\").MapEvent\n * @fires import(\"./render/Event.js\").default#precompose\n * @fires import(\"./render/Event.js\").default#postcompose\n * @fires import(\"./render/Event.js\").default#rendercomplete\n * @api\n */\nclass Map extends BaseObject {\n /**\n * @param {MapOptions} [options] Map options.\n */\n constructor(options) {\n super();\n\n options = options || {};\n\n /***\n * @type {MapEventHandler}\n */\n this.on;\n\n /***\n * @type {MapEventHandler}\n */\n this.once;\n\n /***\n * @type {MapEventHandler}\n */\n this.un;\n\n const optionsInternal = createOptionsInternal(options);\n\n /**\n * @private\n * @type {boolean|undefined}\n */\n this.renderComplete_;\n\n /**\n * @private\n * @type {boolean}\n */\n this.loaded_ = true;\n\n /** @private */\n this.boundHandleBrowserEvent_ = this.handleBrowserEvent.bind(this);\n\n /**\n * @type {number}\n * @private\n */\n this.maxTilesLoading_ =\n options.maxTilesLoading !== undefined ? options.maxTilesLoading : 16;\n\n /**\n * @private\n * @type {number}\n */\n this.pixelRatio_ =\n options.pixelRatio !== undefined\n ? options.pixelRatio\n : DEVICE_PIXEL_RATIO;\n\n /**\n * @private\n * @type {ReturnType}\n */\n this.postRenderTimeoutHandle_;\n\n /**\n * @private\n * @type {number|undefined}\n */\n this.animationDelayKey_;\n\n /**\n * @private\n */\n this.animationDelay_ = this.animationDelay_.bind(this);\n\n /**\n * @private\n * @type {import(\"./transform.js\").Transform}\n */\n this.coordinateToPixelTransform_ = createTransform();\n\n /**\n * @private\n * @type {import(\"./transform.js\").Transform}\n */\n this.pixelToCoordinateTransform_ = createTransform();\n\n /**\n * @private\n * @type {number}\n */\n this.frameIndex_ = 0;\n\n /**\n * @private\n * @type {?FrameState}\n */\n this.frameState_ = null;\n\n /**\n * The extent at the previous 'moveend' event.\n * @private\n * @type {import(\"./extent.js\").Extent}\n */\n this.previousExtent_ = null;\n\n /**\n * @private\n * @type {?import(\"./events.js\").EventsKey}\n */\n this.viewPropertyListenerKey_ = null;\n\n /**\n * @private\n * @type {?import(\"./events.js\").EventsKey}\n */\n this.viewChangeListenerKey_ = null;\n\n /**\n * @private\n * @type {?Array}\n */\n this.layerGroupPropertyListenerKeys_ = null;\n\n /**\n * @private\n * @type {!HTMLElement}\n */\n this.viewport_ = document.createElement('div');\n this.viewport_.className =\n 'ol-viewport' + ('ontouchstart' in window ? ' ol-touch' : '');\n this.viewport_.style.position = 'relative';\n this.viewport_.style.overflow = 'hidden';\n this.viewport_.style.width = '100%';\n this.viewport_.style.height = '100%';\n\n /**\n * @private\n * @type {!HTMLElement}\n */\n this.overlayContainer_ = document.createElement('div');\n this.overlayContainer_.style.position = 'absolute';\n this.overlayContainer_.style.zIndex = '0';\n this.overlayContainer_.style.width = '100%';\n this.overlayContainer_.style.height = '100%';\n this.overlayContainer_.style.pointerEvents = 'none';\n this.overlayContainer_.className = 'ol-overlaycontainer';\n this.viewport_.appendChild(this.overlayContainer_);\n\n /**\n * @private\n * @type {!HTMLElement}\n */\n this.overlayContainerStopEvent_ = document.createElement('div');\n this.overlayContainerStopEvent_.style.position = 'absolute';\n this.overlayContainerStopEvent_.style.zIndex = '0';\n this.overlayContainerStopEvent_.style.width = '100%';\n this.overlayContainerStopEvent_.style.height = '100%';\n this.overlayContainerStopEvent_.style.pointerEvents = 'none';\n this.overlayContainerStopEvent_.className = 'ol-overlaycontainer-stopevent';\n this.viewport_.appendChild(this.overlayContainerStopEvent_);\n\n /**\n * @private\n * @type {MapBrowserEventHandler}\n */\n this.mapBrowserEventHandler_ = null;\n\n /**\n * @private\n * @type {number}\n */\n this.moveTolerance_ = options.moveTolerance;\n\n /**\n * @private\n * @type {HTMLElement|Document}\n */\n this.keyboardEventTarget_ = optionsInternal.keyboardEventTarget;\n\n /**\n * @private\n * @type {?Array}\n */\n this.targetChangeHandlerKeys_ = null;\n\n /**\n * @private\n * @type {HTMLElement|null}\n */\n this.targetElement_ = null;\n\n /**\n * @type {ResizeObserver}\n */\n this.resizeObserver_ = new ResizeObserver(() => this.updateSize());\n\n /**\n * @type {Collection}\n * @protected\n */\n this.controls = optionsInternal.controls || defaultControls();\n\n /**\n * @type {Collection}\n * @protected\n */\n this.interactions =\n optionsInternal.interactions ||\n defaultInteractions({\n onFocusOnly: true,\n });\n\n /**\n * @type {Collection}\n * @private\n */\n this.overlays_ = optionsInternal.overlays;\n\n /**\n * A lookup of overlays by id.\n * @private\n * @type {Object}\n */\n this.overlayIdIndex_ = {};\n\n /**\n * @type {import(\"./renderer/Map.js\").default|null}\n * @private\n */\n this.renderer_ = null;\n\n /**\n * @private\n * @type {!Array}\n */\n this.postRenderFunctions_ = [];\n\n /**\n * @private\n * @type {TileQueue}\n */\n this.tileQueue_ = new TileQueue(\n this.getTilePriority.bind(this),\n this.handleTileChange_.bind(this)\n );\n\n this.addChangeListener(\n MapProperty.LAYERGROUP,\n this.handleLayerGroupChanged_\n );\n this.addChangeListener(MapProperty.VIEW, this.handleViewChanged_);\n this.addChangeListener(MapProperty.SIZE, this.handleSizeChanged_);\n this.addChangeListener(MapProperty.TARGET, this.handleTargetChanged_);\n\n // setProperties will trigger the rendering of the map if the map\n // is \"defined\" already.\n this.setProperties(optionsInternal.values);\n\n const map = this;\n if (options.view && !(options.view instanceof View)) {\n options.view.then(function (viewOptions) {\n map.setView(new View(viewOptions));\n });\n }\n\n this.controls.addEventListener(\n CollectionEventType.ADD,\n /**\n * @param {import(\"./Collection.js\").CollectionEvent} event CollectionEvent\n */\n (event) => {\n event.element.setMap(this);\n }\n );\n\n this.controls.addEventListener(\n CollectionEventType.REMOVE,\n /**\n * @param {import(\"./Collection.js\").CollectionEvent} event CollectionEvent.\n */\n (event) => {\n event.element.setMap(null);\n }\n );\n\n this.interactions.addEventListener(\n CollectionEventType.ADD,\n /**\n * @param {import(\"./Collection.js\").CollectionEvent} event CollectionEvent.\n */\n (event) => {\n event.element.setMap(this);\n }\n );\n\n this.interactions.addEventListener(\n CollectionEventType.REMOVE,\n /**\n * @param {import(\"./Collection.js\").CollectionEvent} event CollectionEvent.\n */\n (event) => {\n event.element.setMap(null);\n }\n );\n\n this.overlays_.addEventListener(\n CollectionEventType.ADD,\n /**\n * @param {import(\"./Collection.js\").CollectionEvent} event CollectionEvent.\n */\n (event) => {\n this.addOverlayInternal_(event.element);\n }\n );\n\n this.overlays_.addEventListener(\n CollectionEventType.REMOVE,\n /**\n * @param {import(\"./Collection.js\").CollectionEvent} event CollectionEvent.\n */\n (event) => {\n const id = event.element.getId();\n if (id !== undefined) {\n delete this.overlayIdIndex_[id.toString()];\n }\n event.element.setMap(null);\n }\n );\n\n this.controls.forEach(\n /**\n * @param {import(\"./control/Control.js\").default} control Control.\n */\n (control) => {\n control.setMap(this);\n }\n );\n\n this.interactions.forEach(\n /**\n * @param {import(\"./interaction/Interaction.js\").default} interaction Interaction.\n */\n (interaction) => {\n interaction.setMap(this);\n }\n );\n\n this.overlays_.forEach(this.addOverlayInternal_.bind(this));\n }\n\n /**\n * Add the given control to the map.\n * @param {import(\"./control/Control.js\").default} control Control.\n * @api\n */\n addControl(control) {\n this.getControls().push(control);\n }\n\n /**\n * Add the given interaction to the map. If you want to add an interaction\n * at another point of the collection use `getInteractions()` and the methods\n * available on {@link module:ol/Collection~Collection}. This can be used to\n * stop the event propagation from the handleEvent function. The interactions\n * get to handle the events in the reverse order of this collection.\n * @param {import(\"./interaction/Interaction.js\").default} interaction Interaction to add.\n * @api\n */\n addInteraction(interaction) {\n this.getInteractions().push(interaction);\n }\n\n /**\n * Adds the given layer to the top of this map. If you want to add a layer\n * elsewhere in the stack, use `getLayers()` and the methods available on\n * {@link module:ol/Collection~Collection}.\n * @param {import(\"./layer/Base.js\").default} layer Layer.\n * @api\n */\n addLayer(layer) {\n const layers = this.getLayerGroup().getLayers();\n layers.push(layer);\n }\n\n /**\n * @param {import(\"./layer/Group.js\").GroupEvent} event The layer add event.\n * @private\n */\n handleLayerAdd_(event) {\n setLayerMapProperty(event.layer, this);\n }\n\n /**\n * Add the given overlay to the map.\n * @param {import(\"./Overlay.js\").default} overlay Overlay.\n * @api\n */\n addOverlay(overlay) {\n this.getOverlays().push(overlay);\n }\n\n /**\n * This deals with map's overlay collection changes.\n * @param {import(\"./Overlay.js\").default} overlay Overlay.\n * @private\n */\n addOverlayInternal_(overlay) {\n const id = overlay.getId();\n if (id !== undefined) {\n this.overlayIdIndex_[id.toString()] = overlay;\n }\n overlay.setMap(this);\n }\n\n /**\n *\n * Clean up.\n */\n disposeInternal() {\n this.controls.clear();\n this.interactions.clear();\n this.overlays_.clear();\n this.resizeObserver_.disconnect();\n this.setTarget(null);\n super.disposeInternal();\n }\n\n /**\n * Detect features that intersect a pixel on the viewport, and execute a\n * callback with each intersecting feature. Layers included in the detection can\n * be configured through the `layerFilter` option in `options`.\n * @param {import(\"./pixel.js\").Pixel} pixel Pixel.\n * @param {function(import(\"./Feature.js\").FeatureLike, import(\"./layer/Layer.js\").default, import(\"./geom/SimpleGeometry.js\").default): T} callback Feature callback. The callback will be\n * called with two arguments. The first argument is one\n * {@link module:ol/Feature~Feature feature} or\n * {@link module:ol/render/Feature~RenderFeature render feature} at the pixel, the second is\n * the {@link module:ol/layer/Layer~Layer layer} of the feature and will be null for\n * unmanaged layers. To stop detection, callback functions can return a\n * truthy value.\n * @param {AtPixelOptions} [options] Optional options.\n * @return {T|undefined} Callback result, i.e. the return value of last\n * callback execution, or the first truthy callback return value.\n * @template T\n * @api\n */\n forEachFeatureAtPixel(pixel, callback, options) {\n if (!this.frameState_ || !this.renderer_) {\n return;\n }\n const coordinate = this.getCoordinateFromPixelInternal(pixel);\n options = options !== undefined ? options : {};\n const hitTolerance =\n options.hitTolerance !== undefined ? options.hitTolerance : 0;\n const layerFilter =\n options.layerFilter !== undefined ? options.layerFilter : TRUE;\n const checkWrapped = options.checkWrapped !== false;\n return this.renderer_.forEachFeatureAtCoordinate(\n coordinate,\n this.frameState_,\n hitTolerance,\n checkWrapped,\n callback,\n null,\n layerFilter,\n null\n );\n }\n\n /**\n * Get all features that intersect a pixel on the viewport.\n * @param {import(\"./pixel.js\").Pixel} pixel Pixel.\n * @param {AtPixelOptions} [options] Optional options.\n * @return {Array} The detected features or\n * an empty array if none were found.\n * @api\n */\n getFeaturesAtPixel(pixel, options) {\n const features = [];\n this.forEachFeatureAtPixel(\n pixel,\n function (feature) {\n features.push(feature);\n },\n options\n );\n return features;\n }\n\n /**\n * Get all layers from all layer groups.\n * @return {Array} Layers.\n * @api\n */\n getAllLayers() {\n const layers = [];\n function addLayersFrom(layerGroup) {\n layerGroup.forEach(function (layer) {\n if (layer instanceof LayerGroup) {\n addLayersFrom(layer.getLayers());\n } else {\n layers.push(layer);\n }\n });\n }\n addLayersFrom(this.getLayers());\n return layers;\n }\n\n /**\n * Detect if features intersect a pixel on the viewport. Layers included in the\n * detection can be configured through the `layerFilter` option.\n * @param {import(\"./pixel.js\").Pixel} pixel Pixel.\n * @param {AtPixelOptions} [options] Optional options.\n * @return {boolean} Is there a feature at the given pixel?\n * @api\n */\n hasFeatureAtPixel(pixel, options) {\n if (!this.frameState_ || !this.renderer_) {\n return false;\n }\n const coordinate = this.getCoordinateFromPixelInternal(pixel);\n options = options !== undefined ? options : {};\n const layerFilter =\n options.layerFilter !== undefined ? options.layerFilter : TRUE;\n const hitTolerance =\n options.hitTolerance !== undefined ? options.hitTolerance : 0;\n const checkWrapped = options.checkWrapped !== false;\n return this.renderer_.hasFeatureAtCoordinate(\n coordinate,\n this.frameState_,\n hitTolerance,\n checkWrapped,\n layerFilter,\n null\n );\n }\n\n /**\n * Returns the coordinate in user projection for a browser event.\n * @param {MouseEvent} event Event.\n * @return {import(\"./coordinate.js\").Coordinate} Coordinate.\n * @api\n */\n getEventCoordinate(event) {\n return this.getCoordinateFromPixel(this.getEventPixel(event));\n }\n\n /**\n * Returns the coordinate in view projection for a browser event.\n * @param {MouseEvent} event Event.\n * @return {import(\"./coordinate.js\").Coordinate} Coordinate.\n */\n getEventCoordinateInternal(event) {\n return this.getCoordinateFromPixelInternal(this.getEventPixel(event));\n }\n\n /**\n * Returns the map pixel position for a browser event relative to the viewport.\n * @param {UIEvent|{clientX: number, clientY: number}} event Event.\n * @return {import(\"./pixel.js\").Pixel} Pixel.\n * @api\n */\n getEventPixel(event) {\n const viewport = this.viewport_;\n const viewportPosition = viewport.getBoundingClientRect();\n const viewportSize = this.getSize();\n const scaleX = viewportPosition.width / viewportSize[0];\n const scaleY = viewportPosition.height / viewportSize[1];\n const eventPosition =\n //FIXME Are we really calling this with a TouchEvent anywhere?\n 'changedTouches' in event\n ? /** @type {TouchEvent} */ (event).changedTouches[0]\n : /** @type {MouseEvent} */ (event);\n\n return [\n (eventPosition.clientX - viewportPosition.left) / scaleX,\n (eventPosition.clientY - viewportPosition.top) / scaleY,\n ];\n }\n\n /**\n * Get the target in which this map is rendered.\n * Note that this returns what is entered as an option or in setTarget:\n * if that was an element, it returns an element; if a string, it returns that.\n * @return {HTMLElement|string|undefined} The Element or id of the Element that the\n * map is rendered in.\n * @observable\n * @api\n */\n getTarget() {\n return /** @type {HTMLElement|string|undefined} */ (\n this.get(MapProperty.TARGET)\n );\n }\n\n /**\n * Get the DOM element into which this map is rendered. In contrast to\n * `getTarget` this method always return an `Element`, or `null` if the\n * map has no target.\n * @return {HTMLElement} The element that the map is rendered in.\n * @api\n */\n getTargetElement() {\n return this.targetElement_;\n }\n\n /**\n * Get the coordinate for a given pixel. This returns a coordinate in the\n * user projection.\n * @param {import(\"./pixel.js\").Pixel} pixel Pixel position in the map viewport.\n * @return {import(\"./coordinate.js\").Coordinate} The coordinate for the pixel position.\n * @api\n */\n getCoordinateFromPixel(pixel) {\n return toUserCoordinate(\n this.getCoordinateFromPixelInternal(pixel),\n this.getView().getProjection()\n );\n }\n\n /**\n * Get the coordinate for a given pixel. This returns a coordinate in the\n * map view projection.\n * @param {import(\"./pixel.js\").Pixel} pixel Pixel position in the map viewport.\n * @return {import(\"./coordinate.js\").Coordinate} The coordinate for the pixel position.\n */\n getCoordinateFromPixelInternal(pixel) {\n const frameState = this.frameState_;\n if (!frameState) {\n return null;\n }\n return applyTransform(frameState.pixelToCoordinateTransform, pixel.slice());\n }\n\n /**\n * Get the map controls. Modifying this collection changes the controls\n * associated with the map.\n * @return {Collection} Controls.\n * @api\n */\n getControls() {\n return this.controls;\n }\n\n /**\n * Get the map overlays. Modifying this collection changes the overlays\n * associated with the map.\n * @return {Collection} Overlays.\n * @api\n */\n getOverlays() {\n return this.overlays_;\n }\n\n /**\n * Get an overlay by its identifier (the value returned by overlay.getId()).\n * Note that the index treats string and numeric identifiers as the same. So\n * `map.getOverlayById(2)` will return an overlay with id `'2'` or `2`.\n * @param {string|number} id Overlay identifier.\n * @return {import(\"./Overlay.js\").default} Overlay.\n * @api\n */\n getOverlayById(id) {\n const overlay = this.overlayIdIndex_[id.toString()];\n return overlay !== undefined ? overlay : null;\n }\n\n /**\n * Get the map interactions. Modifying this collection changes the interactions\n * associated with the map.\n *\n * Interactions are used for e.g. pan, zoom and rotate.\n * @return {Collection} Interactions.\n * @api\n */\n getInteractions() {\n return this.interactions;\n }\n\n /**\n * Get the layergroup associated with this map.\n * @return {LayerGroup} A layer group containing the layers in this map.\n * @observable\n * @api\n */\n getLayerGroup() {\n return /** @type {LayerGroup} */ (this.get(MapProperty.LAYERGROUP));\n }\n\n /**\n * Clear any existing layers and add layers to the map.\n * @param {Array|Collection} layers The layers to be added to the map.\n * @api\n */\n setLayers(layers) {\n const group = this.getLayerGroup();\n if (layers instanceof Collection) {\n group.setLayers(layers);\n return;\n }\n\n const collection = group.getLayers();\n collection.clear();\n collection.extend(layers);\n }\n\n /**\n * Get the collection of layers associated with this map.\n * @return {!Collection} Layers.\n * @api\n */\n getLayers() {\n const layers = this.getLayerGroup().getLayers();\n return layers;\n }\n\n /**\n * @return {boolean} Layers have sources that are still loading.\n */\n getLoadingOrNotReady() {\n const layerStatesArray = this.getLayerGroup().getLayerStatesArray();\n for (let i = 0, ii = layerStatesArray.length; i < ii; ++i) {\n const state = layerStatesArray[i];\n if (!state.visible) {\n continue;\n }\n const renderer = state.layer.getRenderer();\n if (renderer && !renderer.ready) {\n return true;\n }\n const source = state.layer.getSource();\n if (source && source.loading) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Get the pixel for a coordinate. This takes a coordinate in the user\n * projection and returns the corresponding pixel.\n * @param {import(\"./coordinate.js\").Coordinate} coordinate A map coordinate.\n * @return {import(\"./pixel.js\").Pixel} A pixel position in the map viewport.\n * @api\n */\n getPixelFromCoordinate(coordinate) {\n const viewCoordinate = fromUserCoordinate(\n coordinate,\n this.getView().getProjection()\n );\n return this.getPixelFromCoordinateInternal(viewCoordinate);\n }\n\n /**\n * Get the pixel for a coordinate. This takes a coordinate in the map view\n * projection and returns the corresponding pixel.\n * @param {import(\"./coordinate.js\").Coordinate} coordinate A map coordinate.\n * @return {import(\"./pixel.js\").Pixel} A pixel position in the map viewport.\n */\n getPixelFromCoordinateInternal(coordinate) {\n const frameState = this.frameState_;\n if (!frameState) {\n return null;\n }\n return applyTransform(\n frameState.coordinateToPixelTransform,\n coordinate.slice(0, 2)\n );\n }\n\n /**\n * Get the map renderer.\n * @return {import(\"./renderer/Map.js\").default|null} Renderer\n */\n getRenderer() {\n return this.renderer_;\n }\n\n /**\n * Get the size of this map.\n * @return {import(\"./size.js\").Size|undefined} The size in pixels of the map in the DOM.\n * @observable\n * @api\n */\n getSize() {\n return /** @type {import(\"./size.js\").Size|undefined} */ (\n this.get(MapProperty.SIZE)\n );\n }\n\n /**\n * Get the view associated with this map. A view manages properties such as\n * center and resolution.\n * @return {View} The view that controls this map.\n * @observable\n * @api\n */\n getView() {\n return /** @type {View} */ (this.get(MapProperty.VIEW));\n }\n\n /**\n * Get the element that serves as the map viewport.\n * @return {HTMLElement} Viewport.\n * @api\n */\n getViewport() {\n return this.viewport_;\n }\n\n /**\n * Get the element that serves as the container for overlays. Elements added to\n * this container will let mousedown and touchstart events through to the map,\n * so clicks and gestures on an overlay will trigger {@link module:ol/MapBrowserEvent~MapBrowserEvent}\n * events.\n * @return {!HTMLElement} The map's overlay container.\n */\n getOverlayContainer() {\n return this.overlayContainer_;\n }\n\n /**\n * Get the element that serves as a container for overlays that don't allow\n * event propagation. Elements added to this container won't let mousedown and\n * touchstart events through to the map, so clicks and gestures on an overlay\n * don't trigger any {@link module:ol/MapBrowserEvent~MapBrowserEvent}.\n * @return {!HTMLElement} The map's overlay container that stops events.\n */\n getOverlayContainerStopEvent() {\n return this.overlayContainerStopEvent_;\n }\n\n /**\n * @return {!Document} The document where the map is displayed.\n */\n getOwnerDocument() {\n const targetElement = this.getTargetElement();\n return targetElement ? targetElement.ownerDocument : document;\n }\n\n /**\n * @param {import(\"./Tile.js\").default} tile Tile.\n * @param {string} tileSourceKey Tile source key.\n * @param {import(\"./coordinate.js\").Coordinate} tileCenter Tile center.\n * @param {number} tileResolution Tile resolution.\n * @return {number} Tile priority.\n */\n getTilePriority(tile, tileSourceKey, tileCenter, tileResolution) {\n return getTilePriority(\n this.frameState_,\n tile,\n tileSourceKey,\n tileCenter,\n tileResolution\n );\n }\n\n /**\n * @param {UIEvent} browserEvent Browser event.\n * @param {string} [type] Type.\n */\n handleBrowserEvent(browserEvent, type) {\n type = type || browserEvent.type;\n const mapBrowserEvent = new MapBrowserEvent(type, this, browserEvent);\n this.handleMapBrowserEvent(mapBrowserEvent);\n }\n\n /**\n * @param {MapBrowserEvent} mapBrowserEvent The event to handle.\n */\n handleMapBrowserEvent(mapBrowserEvent) {\n if (!this.frameState_) {\n // With no view defined, we cannot translate pixels into geographical\n // coordinates so interactions cannot be used.\n return;\n }\n const originalEvent = /** @type {PointerEvent} */ (\n mapBrowserEvent.originalEvent\n );\n const eventType = originalEvent.type;\n if (\n eventType === PointerEventType.POINTERDOWN ||\n eventType === EventType.WHEEL ||\n eventType === EventType.KEYDOWN\n ) {\n const doc = this.getOwnerDocument();\n const rootNode = this.viewport_.getRootNode\n ? this.viewport_.getRootNode()\n : doc;\n const target = /** @type {Node} */ (originalEvent.target);\n if (\n // Abort if the target is a child of the container for elements whose events are not meant\n // to be handled by map interactions.\n this.overlayContainerStopEvent_.contains(target) ||\n // Abort if the event target is a child of the container that is no longer in the page.\n // It's possible for the target to no longer be in the page if it has been removed in an\n // event listener, this might happen in a Control that recreates it's content based on\n // user interaction either manually or via a render in something like https://reactjs.org/\n !(rootNode === doc ? doc.documentElement : rootNode).contains(target)\n ) {\n return;\n }\n }\n mapBrowserEvent.frameState = this.frameState_;\n if (this.dispatchEvent(mapBrowserEvent) !== false) {\n const interactionsArray = this.getInteractions().getArray().slice();\n for (let i = interactionsArray.length - 1; i >= 0; i--) {\n const interaction = interactionsArray[i];\n if (\n interaction.getMap() !== this ||\n !interaction.getActive() ||\n !this.getTargetElement()\n ) {\n continue;\n }\n const cont = interaction.handleEvent(mapBrowserEvent);\n if (!cont || mapBrowserEvent.propagationStopped) {\n break;\n }\n }\n }\n }\n\n /**\n * @protected\n */\n handlePostRender() {\n const frameState = this.frameState_;\n\n // Manage the tile queue\n // Image loads are expensive and a limited resource, so try to use them\n // efficiently:\n // * When the view is static we allow a large number of parallel tile loads\n // to complete the frame as quickly as possible.\n // * When animating or interacting, image loads can cause janks, so we reduce\n // the maximum number of loads per frame and limit the number of parallel\n // tile loads to remain reactive to view changes and to reduce the chance of\n // loading tiles that will quickly disappear from view.\n const tileQueue = this.tileQueue_;\n if (!tileQueue.isEmpty()) {\n let maxTotalLoading = this.maxTilesLoading_;\n let maxNewLoads = maxTotalLoading;\n if (frameState) {\n const hints = frameState.viewHints;\n if (hints[ViewHint.ANIMATING] || hints[ViewHint.INTERACTING]) {\n const lowOnFrameBudget = Date.now() - frameState.time > 8;\n maxTotalLoading = lowOnFrameBudget ? 0 : 8;\n maxNewLoads = lowOnFrameBudget ? 0 : 2;\n }\n }\n if (tileQueue.getTilesLoading() < maxTotalLoading) {\n tileQueue.reprioritize(); // FIXME only call if view has changed\n tileQueue.loadMoreTiles(maxTotalLoading, maxNewLoads);\n }\n }\n\n if (frameState && this.renderer_ && !frameState.animate) {\n if (this.renderComplete_ === true) {\n if (this.hasListener(RenderEventType.RENDERCOMPLETE)) {\n this.renderer_.dispatchRenderEvent(\n RenderEventType.RENDERCOMPLETE,\n frameState\n );\n }\n if (this.loaded_ === false) {\n this.loaded_ = true;\n this.dispatchEvent(\n new MapEvent(MapEventType.LOADEND, this, frameState)\n );\n }\n } else if (this.loaded_ === true) {\n this.loaded_ = false;\n this.dispatchEvent(\n new MapEvent(MapEventType.LOADSTART, this, frameState)\n );\n }\n }\n\n const postRenderFunctions = this.postRenderFunctions_;\n for (let i = 0, ii = postRenderFunctions.length; i < ii; ++i) {\n postRenderFunctions[i](this, frameState);\n }\n postRenderFunctions.length = 0;\n }\n\n /**\n * @private\n */\n handleSizeChanged_() {\n if (this.getView() && !this.getView().getAnimating()) {\n this.getView().resolveConstraints(0);\n }\n\n this.render();\n }\n\n /**\n * @private\n */\n handleTargetChanged_() {\n if (this.mapBrowserEventHandler_) {\n for (let i = 0, ii = this.targetChangeHandlerKeys_.length; i < ii; ++i) {\n unlistenByKey(this.targetChangeHandlerKeys_[i]);\n }\n this.targetChangeHandlerKeys_ = null;\n this.viewport_.removeEventListener(\n EventType.CONTEXTMENU,\n this.boundHandleBrowserEvent_\n );\n this.viewport_.removeEventListener(\n EventType.WHEEL,\n this.boundHandleBrowserEvent_\n );\n this.mapBrowserEventHandler_.dispose();\n this.mapBrowserEventHandler_ = null;\n removeNode(this.viewport_);\n }\n\n if (this.targetElement_) {\n this.resizeObserver_.unobserve(this.targetElement_);\n const rootNode = this.targetElement_.getRootNode();\n if (rootNode instanceof ShadowRoot) {\n this.resizeObserver_.unobserve(rootNode.host);\n }\n this.setSize(undefined);\n }\n\n // target may be undefined, null, a string or an Element.\n // If it's a string we convert it to an Element before proceeding.\n // If it's not now an Element we remove the viewport from the DOM.\n // If it's an Element we append the viewport element to it.\n\n const target = this.getTarget();\n const targetElement =\n typeof target === 'string' ? document.getElementById(target) : target;\n this.targetElement_ = targetElement;\n if (!targetElement) {\n if (this.renderer_) {\n clearTimeout(this.postRenderTimeoutHandle_);\n this.postRenderTimeoutHandle_ = undefined;\n this.postRenderFunctions_.length = 0;\n this.renderer_.dispose();\n this.renderer_ = null;\n }\n if (this.animationDelayKey_) {\n cancelAnimationFrame(this.animationDelayKey_);\n this.animationDelayKey_ = undefined;\n }\n } else {\n targetElement.appendChild(this.viewport_);\n if (!this.renderer_) {\n this.renderer_ = new CompositeMapRenderer(this);\n }\n\n this.mapBrowserEventHandler_ = new MapBrowserEventHandler(\n this,\n this.moveTolerance_\n );\n for (const key in MapBrowserEventType) {\n this.mapBrowserEventHandler_.addEventListener(\n MapBrowserEventType[key],\n this.handleMapBrowserEvent.bind(this)\n );\n }\n this.viewport_.addEventListener(\n EventType.CONTEXTMENU,\n this.boundHandleBrowserEvent_,\n false\n );\n this.viewport_.addEventListener(\n EventType.WHEEL,\n this.boundHandleBrowserEvent_,\n PASSIVE_EVENT_LISTENERS ? {passive: false} : false\n );\n\n const keyboardEventTarget = !this.keyboardEventTarget_\n ? targetElement\n : this.keyboardEventTarget_;\n this.targetChangeHandlerKeys_ = [\n listen(\n keyboardEventTarget,\n EventType.KEYDOWN,\n this.handleBrowserEvent,\n this\n ),\n listen(\n keyboardEventTarget,\n EventType.KEYPRESS,\n this.handleBrowserEvent,\n this\n ),\n ];\n const rootNode = targetElement.getRootNode();\n if (rootNode instanceof ShadowRoot) {\n this.resizeObserver_.observe(rootNode.host);\n }\n this.resizeObserver_.observe(targetElement);\n }\n\n this.updateSize();\n // updateSize calls setSize, so no need to call this.render\n // ourselves here.\n }\n\n /**\n * @private\n */\n handleTileChange_() {\n this.render();\n }\n\n /**\n * @private\n */\n handleViewPropertyChanged_() {\n this.render();\n }\n\n /**\n * @private\n */\n handleViewChanged_() {\n if (this.viewPropertyListenerKey_) {\n unlistenByKey(this.viewPropertyListenerKey_);\n this.viewPropertyListenerKey_ = null;\n }\n if (this.viewChangeListenerKey_) {\n unlistenByKey(this.viewChangeListenerKey_);\n this.viewChangeListenerKey_ = null;\n }\n const view = this.getView();\n if (view) {\n this.updateViewportSize_();\n\n this.viewPropertyListenerKey_ = listen(\n view,\n ObjectEventType.PROPERTYCHANGE,\n this.handleViewPropertyChanged_,\n this\n );\n this.viewChangeListenerKey_ = listen(\n view,\n EventType.CHANGE,\n this.handleViewPropertyChanged_,\n this\n );\n\n view.resolveConstraints(0);\n }\n this.render();\n }\n\n /**\n * @private\n */\n handleLayerGroupChanged_() {\n if (this.layerGroupPropertyListenerKeys_) {\n this.layerGroupPropertyListenerKeys_.forEach(unlistenByKey);\n this.layerGroupPropertyListenerKeys_ = null;\n }\n const layerGroup = this.getLayerGroup();\n if (layerGroup) {\n this.handleLayerAdd_(new GroupEvent('addlayer', layerGroup));\n this.layerGroupPropertyListenerKeys_ = [\n listen(layerGroup, ObjectEventType.PROPERTYCHANGE, this.render, this),\n listen(layerGroup, EventType.CHANGE, this.render, this),\n listen(layerGroup, 'addlayer', this.handleLayerAdd_, this),\n listen(layerGroup, 'removelayer', this.handleLayerRemove_, this),\n ];\n }\n this.render();\n }\n\n /**\n * @return {boolean} Is rendered.\n */\n isRendered() {\n return !!this.frameState_;\n }\n\n /**\n * @private\n */\n animationDelay_() {\n this.animationDelayKey_ = undefined;\n this.renderFrame_(Date.now());\n }\n\n /**\n * Requests an immediate render in a synchronous manner.\n * @api\n */\n renderSync() {\n if (this.animationDelayKey_) {\n cancelAnimationFrame(this.animationDelayKey_);\n }\n this.animationDelay_();\n }\n\n /**\n * Redraws all text after new fonts have loaded\n */\n redrawText() {\n const layerStates = this.getLayerGroup().getLayerStatesArray();\n for (let i = 0, ii = layerStates.length; i < ii; ++i) {\n const layer = layerStates[i].layer;\n if (layer.hasRenderer()) {\n layer.getRenderer().handleFontsChanged();\n }\n }\n }\n\n /**\n * Request a map rendering (at the next animation frame).\n * @api\n */\n render() {\n if (this.renderer_ && this.animationDelayKey_ === undefined) {\n this.animationDelayKey_ = requestAnimationFrame(this.animationDelay_);\n }\n }\n\n /**\n * This method is meant to be called in a layer's `prerender` listener. It causes all collected\n * declutter items to be decluttered and rendered on the map immediately. This is useful for\n * layers that need to appear entirely above the decluttered items of layers lower in the layer\n * stack.\n * @api\n */\n flushDeclutterItems() {\n const frameState = this.frameState_;\n if (!frameState) {\n return;\n }\n this.renderer_.flushDeclutterItems(frameState);\n }\n\n /**\n * Remove the given control from the map.\n * @param {import(\"./control/Control.js\").default} control Control.\n * @return {import(\"./control/Control.js\").default|undefined} The removed control (or undefined\n * if the control was not found).\n * @api\n */\n removeControl(control) {\n return this.getControls().remove(control);\n }\n\n /**\n * Remove the given interaction from the map.\n * @param {import(\"./interaction/Interaction.js\").default} interaction Interaction to remove.\n * @return {import(\"./interaction/Interaction.js\").default|undefined} The removed interaction (or\n * undefined if the interaction was not found).\n * @api\n */\n removeInteraction(interaction) {\n return this.getInteractions().remove(interaction);\n }\n\n /**\n * Removes the given layer from the map.\n * @param {import(\"./layer/Base.js\").default} layer Layer.\n * @return {import(\"./layer/Base.js\").default|undefined} The removed layer (or undefined if the\n * layer was not found).\n * @api\n */\n removeLayer(layer) {\n const layers = this.getLayerGroup().getLayers();\n return layers.remove(layer);\n }\n\n /**\n * @param {import(\"./layer/Group.js\").GroupEvent} event The layer remove event.\n * @private\n */\n handleLayerRemove_(event) {\n removeLayerMapProperty(event.layer);\n }\n\n /**\n * Remove the given overlay from the map.\n * @param {import(\"./Overlay.js\").default} overlay Overlay.\n * @return {import(\"./Overlay.js\").default|undefined} The removed overlay (or undefined\n * if the overlay was not found).\n * @api\n */\n removeOverlay(overlay) {\n return this.getOverlays().remove(overlay);\n }\n\n /**\n * @param {number} time Time.\n * @private\n */\n renderFrame_(time) {\n const size = this.getSize();\n const view = this.getView();\n const previousFrameState = this.frameState_;\n /** @type {?FrameState} */\n let frameState = null;\n if (size !== undefined && hasArea(size) && view && view.isDef()) {\n const viewHints = view.getHints(\n this.frameState_ ? this.frameState_.viewHints : undefined\n );\n const viewState = view.getState();\n frameState = {\n animate: false,\n coordinateToPixelTransform: this.coordinateToPixelTransform_,\n declutterTree: null,\n extent: getForViewAndSize(\n viewState.center,\n viewState.resolution,\n viewState.rotation,\n size\n ),\n index: this.frameIndex_++,\n layerIndex: 0,\n layerStatesArray: this.getLayerGroup().getLayerStatesArray(),\n pixelRatio: this.pixelRatio_,\n pixelToCoordinateTransform: this.pixelToCoordinateTransform_,\n postRenderFunctions: [],\n size: size,\n tileQueue: this.tileQueue_,\n time: time,\n usedTiles: {},\n viewState: viewState,\n viewHints: viewHints,\n wantedTiles: {},\n mapId: getUid(this),\n renderTargets: {},\n };\n if (viewState.nextCenter && viewState.nextResolution) {\n const rotation = isNaN(viewState.nextRotation)\n ? viewState.rotation\n : viewState.nextRotation;\n\n frameState.nextExtent = getForViewAndSize(\n viewState.nextCenter,\n viewState.nextResolution,\n rotation,\n size\n );\n }\n }\n\n this.frameState_ = frameState;\n this.renderer_.renderFrame(frameState);\n\n if (frameState) {\n if (frameState.animate) {\n this.render();\n }\n Array.prototype.push.apply(\n this.postRenderFunctions_,\n frameState.postRenderFunctions\n );\n\n if (previousFrameState) {\n const moveStart =\n !this.previousExtent_ ||\n (!isEmpty(this.previousExtent_) &&\n !equalsExtent(frameState.extent, this.previousExtent_));\n if (moveStart) {\n this.dispatchEvent(\n new MapEvent(MapEventType.MOVESTART, this, previousFrameState)\n );\n this.previousExtent_ = createOrUpdateEmpty(this.previousExtent_);\n }\n }\n\n const idle =\n this.previousExtent_ &&\n !frameState.viewHints[ViewHint.ANIMATING] &&\n !frameState.viewHints[ViewHint.INTERACTING] &&\n !equalsExtent(frameState.extent, this.previousExtent_);\n\n if (idle) {\n this.dispatchEvent(\n new MapEvent(MapEventType.MOVEEND, this, frameState)\n );\n clone(frameState.extent, this.previousExtent_);\n }\n }\n\n this.dispatchEvent(new MapEvent(MapEventType.POSTRENDER, this, frameState));\n\n this.renderComplete_ =\n this.hasListener(MapEventType.LOADSTART) ||\n this.hasListener(MapEventType.LOADEND) ||\n this.hasListener(RenderEventType.RENDERCOMPLETE)\n ? !this.tileQueue_.getTilesLoading() &&\n !this.tileQueue_.getCount() &&\n !this.getLoadingOrNotReady()\n : undefined;\n\n if (!this.postRenderTimeoutHandle_) {\n this.postRenderTimeoutHandle_ = setTimeout(() => {\n this.postRenderTimeoutHandle_ = undefined;\n this.handlePostRender();\n }, 0);\n }\n }\n\n /**\n * Sets the layergroup of this map.\n * @param {LayerGroup} layerGroup A layer group containing the layers in this map.\n * @observable\n * @api\n */\n setLayerGroup(layerGroup) {\n const oldLayerGroup = this.getLayerGroup();\n if (oldLayerGroup) {\n this.handleLayerRemove_(new GroupEvent('removelayer', oldLayerGroup));\n }\n this.set(MapProperty.LAYERGROUP, layerGroup);\n }\n\n /**\n * Set the size of this map.\n * @param {import(\"./size.js\").Size|undefined} size The size in pixels of the map in the DOM.\n * @observable\n * @api\n */\n setSize(size) {\n this.set(MapProperty.SIZE, size);\n }\n\n /**\n * Set the target element to render this map into.\n * @param {HTMLElement|string} [target] The Element or id of the Element\n * that the map is rendered in.\n * @observable\n * @api\n */\n setTarget(target) {\n this.set(MapProperty.TARGET, target);\n }\n\n /**\n * Set the view for this map.\n * @param {View|Promise} view The view that controls this map.\n * It is also possible to pass a promise that resolves to options for constructing a view. This\n * alternative allows view properties to be resolved by sources or other components that load\n * view-related metadata.\n * @observable\n * @api\n */\n setView(view) {\n if (!view || view instanceof View) {\n this.set(MapProperty.VIEW, view);\n return;\n }\n this.set(MapProperty.VIEW, new View());\n\n const map = this;\n view.then(function (viewOptions) {\n map.setView(new View(viewOptions));\n });\n }\n\n /**\n * Force a recalculation of the map viewport size. This should be called when\n * third-party code changes the size of the map viewport.\n * @api\n */\n updateSize() {\n const targetElement = this.getTargetElement();\n\n let size = undefined;\n if (targetElement) {\n const computedStyle = getComputedStyle(targetElement);\n const width =\n targetElement.offsetWidth -\n parseFloat(computedStyle['borderLeftWidth']) -\n parseFloat(computedStyle['paddingLeft']) -\n parseFloat(computedStyle['paddingRight']) -\n parseFloat(computedStyle['borderRightWidth']);\n const height =\n targetElement.offsetHeight -\n parseFloat(computedStyle['borderTopWidth']) -\n parseFloat(computedStyle['paddingTop']) -\n parseFloat(computedStyle['paddingBottom']) -\n parseFloat(computedStyle['borderBottomWidth']);\n if (!isNaN(width) && !isNaN(height)) {\n size = [width, height];\n if (\n !hasArea(size) &&\n !!(\n targetElement.offsetWidth ||\n targetElement.offsetHeight ||\n targetElement.getClientRects().length\n )\n ) {\n warn(\n \"No map visible because the map container's width or height are 0.\"\n );\n }\n }\n }\n\n const oldSize = this.getSize();\n if (size && (!oldSize || !equals(size, oldSize))) {\n this.setSize(size);\n this.updateViewportSize_();\n }\n }\n\n /**\n * Recomputes the viewport size and save it on the view object (if any)\n * @private\n */\n updateViewportSize_() {\n const view = this.getView();\n if (view) {\n let size = undefined;\n const computedStyle = getComputedStyle(this.viewport_);\n if (computedStyle.width && computedStyle.height) {\n size = [\n parseInt(computedStyle.width, 10),\n parseInt(computedStyle.height, 10),\n ];\n }\n view.setViewportSize(size);\n }\n }\n}\n\n/**\n * @param {MapOptions} options Map options.\n * @return {MapOptionsInternal} Internal map options.\n */\nfunction createOptionsInternal(options) {\n /**\n * @type {HTMLElement|Document}\n */\n let keyboardEventTarget = null;\n if (options.keyboardEventTarget !== undefined) {\n keyboardEventTarget =\n typeof options.keyboardEventTarget === 'string'\n ? document.getElementById(options.keyboardEventTarget)\n : options.keyboardEventTarget;\n }\n\n /**\n * @type {Object}\n */\n const values = {};\n\n const layerGroup =\n options.layers &&\n typeof (/** @type {?} */ (options.layers).getLayers) === 'function'\n ? /** @type {LayerGroup} */ (options.layers)\n : new LayerGroup({\n layers:\n /** @type {Collection|Array} */ (\n options.layers\n ),\n });\n values[MapProperty.LAYERGROUP] = layerGroup;\n\n values[MapProperty.TARGET] = options.target;\n\n values[MapProperty.VIEW] =\n options.view instanceof View ? options.view : new View();\n\n /** @type {Collection} */\n let controls;\n if (options.controls !== undefined) {\n if (Array.isArray(options.controls)) {\n controls = new Collection(options.controls.slice());\n } else {\n assert(\n typeof (/** @type {?} */ (options.controls).getArray) === 'function',\n 47\n ); // Expected `controls` to be an array or an `import(\"./Collection.js\").Collection`\n controls = options.controls;\n }\n }\n\n /** @type {Collection} */\n let interactions;\n if (options.interactions !== undefined) {\n if (Array.isArray(options.interactions)) {\n interactions = new Collection(options.interactions.slice());\n } else {\n assert(\n typeof (/** @type {?} */ (options.interactions).getArray) ===\n 'function',\n 48\n ); // Expected `interactions` to be an array or an `import(\"./Collection.js\").Collection`\n interactions = options.interactions;\n }\n }\n\n /** @type {Collection} */\n let overlays;\n if (options.overlays !== undefined) {\n if (Array.isArray(options.overlays)) {\n overlays = new Collection(options.overlays.slice());\n } else {\n assert(\n typeof (/** @type {?} */ (options.overlays).getArray) === 'function',\n 49\n ); // Expected `overlays` to be an array or an `import(\"./Collection.js\").Collection`\n overlays = options.overlays;\n }\n } else {\n overlays = new Collection();\n }\n\n return {\n controls: controls,\n interactions: interactions,\n keyboardEventTarget: keyboardEventTarget,\n overlays: overlays,\n values: values,\n };\n}\nexport default Map;\n","/**\n * @module ol/Overlay\n */\nimport BaseObject from './Object.js';\nimport MapEventType from './MapEventType.js';\nimport {CLASS_SELECTABLE} from './css.js';\nimport {containsExtent} from './extent.js';\nimport {listen, unlistenByKey} from './events.js';\nimport {outerHeight, outerWidth, removeChildren, removeNode} from './dom.js';\n\n/**\n * @typedef {'bottom-left' | 'bottom-center' | 'bottom-right' | 'center-left' | 'center-center' | 'center-right' | 'top-left' | 'top-center' | 'top-right'} Positioning\n * The overlay position: `'bottom-left'`, `'bottom-center'`, `'bottom-right'`,\n * `'center-left'`, `'center-center'`, `'center-right'`, `'top-left'`,\n * `'top-center'`, or `'top-right'`.\n */\n\n/**\n * @typedef {Object} Options\n * @property {number|string} [id] Set the overlay id. The overlay id can be used\n * with the {@link module:ol/Map~Map#getOverlayById} method.\n * @property {HTMLElement} [element] The overlay element.\n * @property {Array} [offset=[0, 0]] Offsets in pixels used when positioning\n * the overlay. The first element in the\n * array is the horizontal offset. A positive value shifts the overlay right.\n * The second element in the array is the vertical offset. A positive value\n * shifts the overlay down.\n * @property {import(\"./coordinate.js\").Coordinate} [position] The overlay position\n * in map projection.\n * @property {Positioning} [positioning='top-left'] Defines how\n * the overlay is actually positioned with respect to its `position` property.\n * Possible values are `'bottom-left'`, `'bottom-center'`, `'bottom-right'`,\n * `'center-left'`, `'center-center'`, `'center-right'`, `'top-left'`,\n * `'top-center'`, and `'top-right'`.\n * @property {boolean} [stopEvent=true] Whether event propagation to the map\n * viewport should be stopped. If `true` the overlay is placed in the same\n * container as that of the controls (CSS class name\n * `ol-overlaycontainer-stopevent`); if `false` it is placed in the container\n * with CSS class name specified by the `className` property.\n * @property {boolean} [insertFirst=true] Whether the overlay is inserted first\n * in the overlay container, or appended. If the overlay is placed in the same\n * container as that of the controls (see the `stopEvent` option) you will\n * probably set `insertFirst` to `true` so the overlay is displayed below the\n * controls.\n * @property {PanIntoViewOptions|boolean} [autoPan=false] Pan the map when calling\n * `setPosition`, so that the overlay is entirely visible in the current viewport.\n * @property {string} [className='ol-overlay-container ol-selectable'] CSS class\n * name.\n */\n\n/**\n * @typedef {Object} PanOptions\n * @property {number} [duration=1000] The duration of the animation in\n * milliseconds.\n * @property {function(number):number} [easing] The easing function to use. Can\n * be one from {@link module:ol/easing} or a custom function.\n * Default is {@link module:ol/easing.inAndOut}.\n */\n\n/**\n * @typedef {Object} PanIntoViewOptions\n * @property {PanOptions} [animation={}] The animation parameters for the pan\n * @property {number} [margin=20] The margin (in pixels) between the\n * overlay and the borders of the map when panning into view.\n */\n\n/**\n * @enum {string}\n * @protected\n */\nconst Property = {\n ELEMENT: 'element',\n MAP: 'map',\n OFFSET: 'offset',\n POSITION: 'position',\n POSITIONING: 'positioning',\n};\n\n/**\n * @typedef {import(\"./ObjectEventType\").Types|'change:element'|'change:map'|'change:offset'|'change:position'|\n * 'change:positioning'} OverlayObjectEventTypes\n */\n\n/***\n * @template Return\n * @typedef {import(\"./Observable\").OnSignature &\n * import(\"./Observable\").OnSignature &\n * import(\"./Observable\").CombinedOnSignature} OverlayOnSignature\n */\n\n/**\n * @classdesc\n * An element to be displayed over the map and attached to a single map\n * location. Like {@link module:ol/control/Control~Control}, Overlays are\n * visible widgets. Unlike Controls, they are not in a fixed position on the\n * screen, but are tied to a geographical coordinate, so panning the map will\n * move an Overlay but not a Control.\n *\n * Example:\n *\n * import Overlay from 'ol/Overlay.js';\n *\n * // ...\n * const popup = new Overlay({\n * element: document.getElementById('popup'),\n * });\n * popup.setPosition(coordinate);\n * map.addOverlay(popup);\n *\n * @api\n */\nclass Overlay extends BaseObject {\n /**\n * @param {Options} options Overlay options.\n */\n constructor(options) {\n super();\n\n /***\n * @type {OverlayOnSignature}\n */\n this.on;\n\n /***\n * @type {OverlayOnSignature}\n */\n this.once;\n\n /***\n * @type {OverlayOnSignature}\n */\n this.un;\n\n /**\n * @protected\n * @type {Options}\n */\n this.options = options;\n\n /**\n * @protected\n * @type {number|string|undefined}\n */\n this.id = options.id;\n\n /**\n * @protected\n * @type {boolean}\n */\n this.insertFirst =\n options.insertFirst !== undefined ? options.insertFirst : true;\n\n /**\n * @protected\n * @type {boolean}\n */\n this.stopEvent = options.stopEvent !== undefined ? options.stopEvent : true;\n\n /**\n * @protected\n * @type {HTMLElement}\n */\n this.element = document.createElement('div');\n this.element.className =\n options.className !== undefined\n ? options.className\n : 'ol-overlay-container ' + CLASS_SELECTABLE;\n this.element.style.position = 'absolute';\n this.element.style.pointerEvents = 'auto';\n\n /**\n * @protected\n * @type {PanIntoViewOptions|undefined}\n */\n this.autoPan = options.autoPan === true ? {} : options.autoPan || undefined;\n\n /**\n * @protected\n * @type {{transform_: string,\n * visible: boolean}}\n */\n this.rendered = {\n transform_: '',\n visible: true,\n };\n\n /**\n * @protected\n * @type {?import(\"./events.js\").EventsKey}\n */\n this.mapPostrenderListenerKey = null;\n\n this.addChangeListener(Property.ELEMENT, this.handleElementChanged);\n this.addChangeListener(Property.MAP, this.handleMapChanged);\n this.addChangeListener(Property.OFFSET, this.handleOffsetChanged);\n this.addChangeListener(Property.POSITION, this.handlePositionChanged);\n this.addChangeListener(Property.POSITIONING, this.handlePositioningChanged);\n\n if (options.element !== undefined) {\n this.setElement(options.element);\n }\n\n this.setOffset(options.offset !== undefined ? options.offset : [0, 0]);\n\n this.setPositioning(options.positioning || 'top-left');\n\n if (options.position !== undefined) {\n this.setPosition(options.position);\n }\n }\n\n /**\n * Get the DOM element of this overlay.\n * @return {HTMLElement|undefined} The Element containing the overlay.\n * @observable\n * @api\n */\n getElement() {\n return /** @type {HTMLElement|undefined} */ (this.get(Property.ELEMENT));\n }\n\n /**\n * Get the overlay identifier which is set on constructor.\n * @return {number|string|undefined} Id.\n * @api\n */\n getId() {\n return this.id;\n }\n\n /**\n * Get the map associated with this overlay.\n * @return {import(\"./Map.js\").default|null} The map that the\n * overlay is part of.\n * @observable\n * @api\n */\n getMap() {\n return /** @type {import(\"./Map.js\").default|null} */ (\n this.get(Property.MAP) || null\n );\n }\n\n /**\n * Get the offset of this overlay.\n * @return {Array} The offset.\n * @observable\n * @api\n */\n getOffset() {\n return /** @type {Array} */ (this.get(Property.OFFSET));\n }\n\n /**\n * Get the current position of this overlay.\n * @return {import(\"./coordinate.js\").Coordinate|undefined} The spatial point that the overlay is\n * anchored at.\n * @observable\n * @api\n */\n getPosition() {\n return /** @type {import(\"./coordinate.js\").Coordinate|undefined} */ (\n this.get(Property.POSITION)\n );\n }\n\n /**\n * Get the current positioning of this overlay.\n * @return {Positioning} How the overlay is positioned\n * relative to its point on the map.\n * @observable\n * @api\n */\n getPositioning() {\n return /** @type {Positioning} */ (this.get(Property.POSITIONING));\n }\n\n /**\n * @protected\n */\n handleElementChanged() {\n removeChildren(this.element);\n const element = this.getElement();\n if (element) {\n this.element.appendChild(element);\n }\n }\n\n /**\n * @protected\n */\n handleMapChanged() {\n if (this.mapPostrenderListenerKey) {\n removeNode(this.element);\n unlistenByKey(this.mapPostrenderListenerKey);\n this.mapPostrenderListenerKey = null;\n }\n const map = this.getMap();\n if (map) {\n this.mapPostrenderListenerKey = listen(\n map,\n MapEventType.POSTRENDER,\n this.render,\n this\n );\n this.updatePixelPosition();\n const container = this.stopEvent\n ? map.getOverlayContainerStopEvent()\n : map.getOverlayContainer();\n if (this.insertFirst) {\n container.insertBefore(this.element, container.childNodes[0] || null);\n } else {\n container.appendChild(this.element);\n }\n this.performAutoPan();\n }\n }\n\n /**\n * @protected\n */\n render() {\n this.updatePixelPosition();\n }\n\n /**\n * @protected\n */\n handleOffsetChanged() {\n this.updatePixelPosition();\n }\n\n /**\n * @protected\n */\n handlePositionChanged() {\n this.updatePixelPosition();\n this.performAutoPan();\n }\n\n /**\n * @protected\n */\n handlePositioningChanged() {\n this.updatePixelPosition();\n }\n\n /**\n * Set the DOM element to be associated with this overlay.\n * @param {HTMLElement|undefined} element The Element containing the overlay.\n * @observable\n * @api\n */\n setElement(element) {\n this.set(Property.ELEMENT, element);\n }\n\n /**\n * Set the map to be associated with this overlay.\n * @param {import(\"./Map.js\").default|null} map The map that the\n * overlay is part of. Pass `null` to just remove the overlay from the current map.\n * @observable\n * @api\n */\n setMap(map) {\n this.set(Property.MAP, map);\n }\n\n /**\n * Set the offset for this overlay.\n * @param {Array} offset Offset.\n * @observable\n * @api\n */\n setOffset(offset) {\n this.set(Property.OFFSET, offset);\n }\n\n /**\n * Set the position for this overlay. If the position is `undefined` the\n * overlay is hidden.\n * @param {import(\"./coordinate.js\").Coordinate|undefined} position The spatial point that the overlay\n * is anchored at.\n * @observable\n * @api\n */\n setPosition(position) {\n this.set(Property.POSITION, position);\n }\n\n /**\n * Pan the map so that the overlay is entirely visible in the current viewport\n * (if necessary) using the configured autoPan parameters\n * @protected\n */\n performAutoPan() {\n if (this.autoPan) {\n this.panIntoView(this.autoPan);\n }\n }\n\n /**\n * Pan the map so that the overlay is entirely visible in the current viewport\n * (if necessary).\n * @param {PanIntoViewOptions} [panIntoViewOptions] Options for the pan action\n * @api\n */\n panIntoView(panIntoViewOptions) {\n const map = this.getMap();\n\n if (!map || !map.getTargetElement() || !this.get(Property.POSITION)) {\n return;\n }\n\n const mapRect = this.getRect(map.getTargetElement(), map.getSize());\n const element = this.getElement();\n const overlayRect = this.getRect(element, [\n outerWidth(element),\n outerHeight(element),\n ]);\n\n panIntoViewOptions = panIntoViewOptions || {};\n\n const myMargin =\n panIntoViewOptions.margin === undefined ? 20 : panIntoViewOptions.margin;\n if (!containsExtent(mapRect, overlayRect)) {\n // the overlay is not completely inside the viewport, so pan the map\n const offsetLeft = overlayRect[0] - mapRect[0];\n const offsetRight = mapRect[2] - overlayRect[2];\n const offsetTop = overlayRect[1] - mapRect[1];\n const offsetBottom = mapRect[3] - overlayRect[3];\n\n const delta = [0, 0];\n if (offsetLeft < 0) {\n // move map to the left\n delta[0] = offsetLeft - myMargin;\n } else if (offsetRight < 0) {\n // move map to the right\n delta[0] = Math.abs(offsetRight) + myMargin;\n }\n if (offsetTop < 0) {\n // move map up\n delta[1] = offsetTop - myMargin;\n } else if (offsetBottom < 0) {\n // move map down\n delta[1] = Math.abs(offsetBottom) + myMargin;\n }\n\n if (delta[0] !== 0 || delta[1] !== 0) {\n const center = /** @type {import(\"./coordinate.js\").Coordinate} */ (\n map.getView().getCenterInternal()\n );\n const centerPx = map.getPixelFromCoordinateInternal(center);\n if (!centerPx) {\n return;\n }\n const newCenterPx = [centerPx[0] + delta[0], centerPx[1] + delta[1]];\n\n const panOptions = panIntoViewOptions.animation || {};\n map.getView().animateInternal({\n center: map.getCoordinateFromPixelInternal(newCenterPx),\n duration: panOptions.duration,\n easing: panOptions.easing,\n });\n }\n }\n }\n\n /**\n * Get the extent of an element relative to the document\n * @param {HTMLElement} element The element.\n * @param {import(\"./size.js\").Size} size The size of the element.\n * @return {import(\"./extent.js\").Extent} The extent.\n * @protected\n */\n getRect(element, size) {\n const box = element.getBoundingClientRect();\n const offsetX = box.left + window.pageXOffset;\n const offsetY = box.top + window.pageYOffset;\n return [offsetX, offsetY, offsetX + size[0], offsetY + size[1]];\n }\n\n /**\n * Set the positioning for this overlay.\n * @param {Positioning} positioning how the overlay is\n * positioned relative to its point on the map.\n * @observable\n * @api\n */\n setPositioning(positioning) {\n this.set(Property.POSITIONING, positioning);\n }\n\n /**\n * Modify the visibility of the element.\n * @param {boolean} visible Element visibility.\n * @protected\n */\n setVisible(visible) {\n if (this.rendered.visible !== visible) {\n this.element.style.display = visible ? '' : 'none';\n this.rendered.visible = visible;\n }\n }\n\n /**\n * Update pixel position.\n * @protected\n */\n updatePixelPosition() {\n const map = this.getMap();\n const position = this.getPosition();\n if (!map || !map.isRendered() || !position) {\n this.setVisible(false);\n return;\n }\n\n const pixel = map.getPixelFromCoordinate(position);\n const mapSize = map.getSize();\n this.updateRenderedPosition(pixel, mapSize);\n }\n\n /**\n * @param {import(\"./pixel.js\").Pixel} pixel The pixel location.\n * @param {import(\"./size.js\").Size|undefined} mapSize The map size.\n * @protected\n */\n updateRenderedPosition(pixel, mapSize) {\n const style = this.element.style;\n const offset = this.getOffset();\n\n const positioning = this.getPositioning();\n\n this.setVisible(true);\n\n const x = Math.round(pixel[0] + offset[0]) + 'px';\n const y = Math.round(pixel[1] + offset[1]) + 'px';\n let posX = '0%';\n let posY = '0%';\n if (\n positioning == 'bottom-right' ||\n positioning == 'center-right' ||\n positioning == 'top-right'\n ) {\n posX = '-100%';\n } else if (\n positioning == 'bottom-center' ||\n positioning == 'center-center' ||\n positioning == 'top-center'\n ) {\n posX = '-50%';\n }\n if (\n positioning == 'bottom-left' ||\n positioning == 'bottom-center' ||\n positioning == 'bottom-right'\n ) {\n posY = '-100%';\n } else if (\n positioning == 'center-left' ||\n positioning == 'center-center' ||\n positioning == 'center-right'\n ) {\n posY = '-50%';\n }\n const transform = `translate(${posX}, ${posY}) translate(${x}, ${y})`;\n if (this.rendered.transform_ != transform) {\n this.rendered.transform_ = transform;\n style.transform = transform;\n }\n }\n\n /**\n * returns the options this Overlay has been created with\n * @return {Options} overlay options\n */\n getOptions() {\n return this.options;\n }\n}\n\nexport default Overlay;\n","/**\n * @module ol/structs/LRUCache\n */\n\nimport {assert} from '../asserts.js';\n\n/**\n * @typedef {Object} Entry\n * @property {string} key_ Key.\n * @property {Object} newer Newer.\n * @property {Object} older Older.\n * @property {*} value_ Value.\n */\n\n/**\n * @classdesc\n * Implements a Least-Recently-Used cache where the keys do not conflict with\n * Object's properties (e.g. 'hasOwnProperty' is not allowed as a key). Expiring\n * items from the cache is the responsibility of the user.\n *\n * @fires import(\"../events/Event.js\").default\n * @template T\n */\nclass LRUCache {\n /**\n * @param {number} [highWaterMark] High water mark.\n */\n constructor(highWaterMark) {\n /**\n * Desired max cache size after expireCache(). If set to 0, no cache entries\n * will be pruned at all.\n * @type {number}\n */\n this.highWaterMark = highWaterMark !== undefined ? highWaterMark : 2048;\n\n /**\n * @private\n * @type {number}\n */\n this.count_ = 0;\n\n /**\n * @private\n * @type {!Object}\n */\n this.entries_ = {};\n\n /**\n * @private\n * @type {?Entry}\n */\n this.oldest_ = null;\n\n /**\n * @private\n * @type {?Entry}\n */\n this.newest_ = null;\n }\n\n /**\n * @return {boolean} Can expire cache.\n */\n canExpireCache() {\n return this.highWaterMark > 0 && this.getCount() > this.highWaterMark;\n }\n\n /**\n * Expire the cache.\n * @param {!Object} [keep] Keys to keep. To be implemented by subclasses.\n */\n expireCache(keep) {\n while (this.canExpireCache()) {\n this.pop();\n }\n }\n\n /**\n * FIXME empty description for jsdoc\n */\n clear() {\n this.count_ = 0;\n this.entries_ = {};\n this.oldest_ = null;\n this.newest_ = null;\n }\n\n /**\n * @param {string} key Key.\n * @return {boolean} Contains key.\n */\n containsKey(key) {\n return this.entries_.hasOwnProperty(key);\n }\n\n /**\n * @param {function(T, string, LRUCache): ?} f The function\n * to call for every entry from the oldest to the newer. This function takes\n * 3 arguments (the entry value, the entry key and the LRUCache object).\n * The return value is ignored.\n */\n forEach(f) {\n let entry = this.oldest_;\n while (entry) {\n f(entry.value_, entry.key_, this);\n entry = entry.newer;\n }\n }\n\n /**\n * @param {string} key Key.\n * @param {*} [options] Options (reserved for subclasses).\n * @return {T} Value.\n */\n get(key, options) {\n const entry = this.entries_[key];\n assert(entry !== undefined, 15); // Tried to get a value for a key that does not exist in the cache\n if (entry === this.newest_) {\n return entry.value_;\n }\n if (entry === this.oldest_) {\n this.oldest_ = /** @type {Entry} */ (this.oldest_.newer);\n this.oldest_.older = null;\n } else {\n entry.newer.older = entry.older;\n entry.older.newer = entry.newer;\n }\n entry.newer = null;\n entry.older = this.newest_;\n this.newest_.newer = entry;\n this.newest_ = entry;\n return entry.value_;\n }\n\n /**\n * Remove an entry from the cache.\n * @param {string} key The entry key.\n * @return {T} The removed entry.\n */\n remove(key) {\n const entry = this.entries_[key];\n assert(entry !== undefined, 15); // Tried to get a value for a key that does not exist in the cache\n if (entry === this.newest_) {\n this.newest_ = /** @type {Entry} */ (entry.older);\n if (this.newest_) {\n this.newest_.newer = null;\n }\n } else if (entry === this.oldest_) {\n this.oldest_ = /** @type {Entry} */ (entry.newer);\n if (this.oldest_) {\n this.oldest_.older = null;\n }\n } else {\n entry.newer.older = entry.older;\n entry.older.newer = entry.newer;\n }\n delete this.entries_[key];\n --this.count_;\n return entry.value_;\n }\n\n /**\n * @return {number} Count.\n */\n getCount() {\n return this.count_;\n }\n\n /**\n * @return {Array} Keys.\n */\n getKeys() {\n const keys = new Array(this.count_);\n let i = 0;\n let entry;\n for (entry = this.newest_; entry; entry = entry.older) {\n keys[i++] = entry.key_;\n }\n return keys;\n }\n\n /**\n * @return {Array} Values.\n */\n getValues() {\n const values = new Array(this.count_);\n let i = 0;\n let entry;\n for (entry = this.newest_; entry; entry = entry.older) {\n values[i++] = entry.value_;\n }\n return values;\n }\n\n /**\n * @return {T} Last value.\n */\n peekLast() {\n return this.oldest_.value_;\n }\n\n /**\n * @return {string} Last key.\n */\n peekLastKey() {\n return this.oldest_.key_;\n }\n\n /**\n * Get the key of the newest item in the cache. Throws if the cache is empty.\n * @return {string} The newest key.\n */\n peekFirstKey() {\n return this.newest_.key_;\n }\n\n /**\n * Return an entry without updating least recently used time.\n * @param {string} key Key.\n * @return {T} Value.\n */\n peek(key) {\n if (!this.containsKey(key)) {\n return undefined;\n }\n return this.entries_[key].value_;\n }\n\n /**\n * @return {T} value Value.\n */\n pop() {\n const entry = this.oldest_;\n delete this.entries_[entry.key_];\n if (entry.newer) {\n entry.newer.older = null;\n }\n this.oldest_ = /** @type {Entry} */ (entry.newer);\n if (!this.oldest_) {\n this.newest_ = null;\n }\n --this.count_;\n return entry.value_;\n }\n\n /**\n * @param {string} key Key.\n * @param {T} value Value.\n */\n replace(key, value) {\n this.get(key); // update `newest_`\n this.entries_[key].value_ = value;\n }\n\n /**\n * @param {string} key Key.\n * @param {T} value Value.\n */\n set(key, value) {\n assert(!(key in this.entries_), 16); // Tried to set a value for a key that is used already\n const entry = {\n key_: key,\n newer: null,\n older: this.newest_,\n value_: value,\n };\n if (!this.newest_) {\n this.oldest_ = entry;\n } else {\n this.newest_.newer = entry;\n }\n this.newest_ = entry;\n this.entries_[key] = entry;\n ++this.count_;\n }\n\n /**\n * Set a maximum number of entries for the cache.\n * @param {number} size Cache size.\n * @api\n */\n setSize(size) {\n this.highWaterMark = size;\n }\n}\n\nexport default LRUCache;\n","/**\n * @module ol/tilecoord\n */\n\n/**\n * An array of three numbers representing the location of a tile in a tile\n * grid. The order is `z` (zoom level), `x` (column), and `y` (row).\n * @typedef {Array} TileCoord\n * @api\n */\n\n/**\n * @param {number} z Z.\n * @param {number} x X.\n * @param {number} y Y.\n * @param {TileCoord} [tileCoord] Tile coordinate.\n * @return {TileCoord} Tile coordinate.\n */\nexport function createOrUpdate(z, x, y, tileCoord) {\n if (tileCoord !== undefined) {\n tileCoord[0] = z;\n tileCoord[1] = x;\n tileCoord[2] = y;\n return tileCoord;\n }\n return [z, x, y];\n}\n\n/**\n * @param {number} z Z.\n * @param {number} x X.\n * @param {number} y Y.\n * @return {string} Key.\n */\nexport function getKeyZXY(z, x, y) {\n return z + '/' + x + '/' + y;\n}\n\n/**\n * Get the key for a tile coord.\n * @param {TileCoord} tileCoord The tile coord.\n * @return {string} Key.\n */\nexport function getKey(tileCoord) {\n return getKeyZXY(tileCoord[0], tileCoord[1], tileCoord[2]);\n}\n\n/**\n * Get the tile cache key for a tile key obtained through `tile.getKey()`.\n * @param {string} tileKey The tile key.\n * @return {string} The cache key.\n */\nexport function getCacheKeyForTileKey(tileKey) {\n const [z, x, y] = tileKey\n .substring(tileKey.lastIndexOf('/') + 1, tileKey.length)\n .split(',')\n .map(Number);\n return getKeyZXY(z, x, y);\n}\n\n/**\n * Get a tile coord given a key.\n * @param {string} key The tile coord key.\n * @return {TileCoord} The tile coord.\n */\nexport function fromKey(key) {\n return key.split('/').map(Number);\n}\n\n/**\n * @param {TileCoord} tileCoord Tile coord.\n * @return {number} Hash.\n */\nexport function hash(tileCoord) {\n return (tileCoord[1] << tileCoord[0]) + tileCoord[2];\n}\n\n/**\n * @param {TileCoord} tileCoord Tile coordinate.\n * @param {!import(\"./tilegrid/TileGrid.js\").default} tileGrid Tile grid.\n * @return {boolean} Tile coordinate is within extent and zoom level range.\n */\nexport function withinExtentAndZ(tileCoord, tileGrid) {\n const z = tileCoord[0];\n const x = tileCoord[1];\n const y = tileCoord[2];\n\n if (tileGrid.getMinZoom() > z || z > tileGrid.getMaxZoom()) {\n return false;\n }\n const tileRange = tileGrid.getFullTileRange(z);\n if (!tileRange) {\n return true;\n }\n return tileRange.containsXY(x, y);\n}\n","/**\n * @module ol/TileCache\n */\nimport LRUCache from './structs/LRUCache.js';\nimport {fromKey, getKey} from './tilecoord.js';\n\nclass TileCache extends LRUCache {\n clear() {\n while (this.getCount() > 0) {\n this.pop().release();\n }\n super.clear();\n }\n\n /**\n * @param {!Object} usedTiles Used tiles.\n */\n expireCache(usedTiles) {\n while (this.canExpireCache()) {\n const tile = this.peekLast();\n if (tile.getKey() in usedTiles) {\n break;\n } else {\n this.pop().release();\n }\n }\n }\n\n /**\n * Prune all tiles from the cache that don't have the same z as the newest tile.\n */\n pruneExceptNewestZ() {\n if (this.getCount() === 0) {\n return;\n }\n const key = this.peekFirstKey();\n const tileCoord = fromKey(key);\n const z = tileCoord[0];\n this.forEach((tile) => {\n if (tile.tileCoord[0] !== z) {\n this.remove(getKey(tile.tileCoord));\n tile.release();\n }\n });\n }\n}\n\nexport default TileCache;\n","/**\n * @module ol/TileRange\n */\n\n/**\n * A representation of a contiguous block of tiles. A tile range is specified\n * by its min/max tile coordinates and is inclusive of coordinates.\n */\nclass TileRange {\n /**\n * @param {number} minX Minimum X.\n * @param {number} maxX Maximum X.\n * @param {number} minY Minimum Y.\n * @param {number} maxY Maximum Y.\n */\n constructor(minX, maxX, minY, maxY) {\n /**\n * @type {number}\n */\n this.minX = minX;\n\n /**\n * @type {number}\n */\n this.maxX = maxX;\n\n /**\n * @type {number}\n */\n this.minY = minY;\n\n /**\n * @type {number}\n */\n this.maxY = maxY;\n }\n\n /**\n * @param {import(\"./tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n * @return {boolean} Contains tile coordinate.\n */\n contains(tileCoord) {\n return this.containsXY(tileCoord[1], tileCoord[2]);\n }\n\n /**\n * @param {TileRange} tileRange Tile range.\n * @return {boolean} Contains.\n */\n containsTileRange(tileRange) {\n return (\n this.minX <= tileRange.minX &&\n tileRange.maxX <= this.maxX &&\n this.minY <= tileRange.minY &&\n tileRange.maxY <= this.maxY\n );\n }\n\n /**\n * @param {number} x Tile coordinate x.\n * @param {number} y Tile coordinate y.\n * @return {boolean} Contains coordinate.\n */\n containsXY(x, y) {\n return this.minX <= x && x <= this.maxX && this.minY <= y && y <= this.maxY;\n }\n\n /**\n * @param {TileRange} tileRange Tile range.\n * @return {boolean} Equals.\n */\n equals(tileRange) {\n return (\n this.minX == tileRange.minX &&\n this.minY == tileRange.minY &&\n this.maxX == tileRange.maxX &&\n this.maxY == tileRange.maxY\n );\n }\n\n /**\n * @param {TileRange} tileRange Tile range.\n */\n extend(tileRange) {\n if (tileRange.minX < this.minX) {\n this.minX = tileRange.minX;\n }\n if (tileRange.maxX > this.maxX) {\n this.maxX = tileRange.maxX;\n }\n if (tileRange.minY < this.minY) {\n this.minY = tileRange.minY;\n }\n if (tileRange.maxY > this.maxY) {\n this.maxY = tileRange.maxY;\n }\n }\n\n /**\n * @return {number} Height.\n */\n getHeight() {\n return this.maxY - this.minY + 1;\n }\n\n /**\n * @return {import(\"./size.js\").Size} Size.\n */\n getSize() {\n return [this.getWidth(), this.getHeight()];\n }\n\n /**\n * @return {number} Width.\n */\n getWidth() {\n return this.maxX - this.minX + 1;\n }\n\n /**\n * @param {TileRange} tileRange Tile range.\n * @return {boolean} Intersects.\n */\n intersects(tileRange) {\n return (\n this.minX <= tileRange.maxX &&\n this.maxX >= tileRange.minX &&\n this.minY <= tileRange.maxY &&\n this.maxY >= tileRange.minY\n );\n }\n}\n\n/**\n * @param {number} minX Minimum X.\n * @param {number} maxX Maximum X.\n * @param {number} minY Minimum Y.\n * @param {number} maxY Maximum Y.\n * @param {TileRange} [tileRange] TileRange.\n * @return {TileRange} Tile range.\n */\nexport function createOrUpdate(minX, maxX, minY, maxY, tileRange) {\n if (tileRange !== undefined) {\n tileRange.minX = minX;\n tileRange.maxX = maxX;\n tileRange.minY = minY;\n tileRange.maxY = maxY;\n return tileRange;\n }\n return new TileRange(minX, maxX, minY, maxY);\n}\n\nexport default TileRange;\n","/**\n * @module ol/VectorRenderTile\n */\nimport Tile from './Tile.js';\nimport {createCanvasContext2D, releaseCanvas} from './dom.js';\nimport {getUid} from './util.js';\n\n/**\n * @typedef {Object} ReplayState\n * @property {boolean} dirty Dirty.\n * @property {null|import(\"./render.js\").OrderFunction} renderedRenderOrder RenderedRenderOrder.\n * @property {number} renderedTileRevision RenderedTileRevision.\n * @property {number} renderedResolution RenderedResolution.\n * @property {number} renderedRevision RenderedRevision.\n * @property {number} renderedTileResolution RenderedTileResolution.\n * @property {number} renderedTileZ RenderedTileZ.\n */\n\n/**\n * @type {Array}\n */\nconst canvasPool = [];\n\nclass VectorRenderTile extends Tile {\n /**\n * @param {import(\"./tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n * @param {import(\"./TileState.js\").default} state State.\n * @param {import(\"./tilecoord.js\").TileCoord} urlTileCoord Wrapped tile coordinate for source urls.\n * @param {function(VectorRenderTile):Array} getSourceTiles Function\n * to get source tiles for this tile.\n */\n constructor(tileCoord, state, urlTileCoord, getSourceTiles) {\n super(tileCoord, state, {transition: 0});\n\n /**\n * @private\n * @type {!Object}\n */\n this.context_ = {};\n\n /**\n * Executor groups by layer uid. Entries are read/written by the renderer.\n * @type {Object>}\n */\n this.executorGroups = {};\n\n /**\n * Executor groups for decluttering, by layer uid. Entries are read/written by the renderer.\n * @type {Object>}\n */\n this.declutterExecutorGroups = {};\n\n /**\n * Number of loading source tiles. Read/written by the source.\n * @type {number}\n */\n this.loadingSourceTiles = 0;\n\n /**\n * @type {Object}\n */\n this.hitDetectionImageData = {};\n\n /**\n * @private\n * @type {!Object}\n */\n this.replayState_ = {};\n\n /**\n * @type {Array}\n */\n this.sourceTiles = [];\n\n /**\n * @type {Object}\n */\n this.errorTileKeys = {};\n\n /**\n * @type {number}\n */\n this.wantedResolution;\n\n /**\n * @type {!function():Array}\n */\n this.getSourceTiles = getSourceTiles.bind(undefined, this);\n\n /**\n * @type {import(\"./tilecoord.js\").TileCoord}\n */\n this.wrappedTileCoord = urlTileCoord;\n }\n\n /**\n * @param {import(\"./layer/Layer.js\").default} layer Layer.\n * @return {CanvasRenderingContext2D} The rendering context.\n */\n getContext(layer) {\n const key = getUid(layer);\n if (!(key in this.context_)) {\n this.context_[key] = createCanvasContext2D(1, 1, canvasPool);\n }\n return this.context_[key];\n }\n\n /**\n * @param {import(\"./layer/Layer.js\").default} layer Layer.\n * @return {boolean} Tile has a rendering context for the given layer.\n */\n hasContext(layer) {\n return getUid(layer) in this.context_;\n }\n\n /**\n * Get the Canvas for this tile.\n * @param {import(\"./layer/Layer.js\").default} layer Layer.\n * @return {HTMLCanvasElement} Canvas.\n */\n getImage(layer) {\n return this.hasContext(layer) ? this.getContext(layer).canvas : null;\n }\n\n /**\n * @param {import(\"./layer/Layer.js\").default} layer Layer.\n * @return {ReplayState} The replay state.\n */\n getReplayState(layer) {\n const key = getUid(layer);\n if (!(key in this.replayState_)) {\n this.replayState_[key] = {\n dirty: false,\n renderedRenderOrder: null,\n renderedResolution: NaN,\n renderedRevision: -1,\n renderedTileResolution: NaN,\n renderedTileRevision: -1,\n renderedTileZ: -1,\n };\n }\n return this.replayState_[key];\n }\n\n /**\n * Load the tile.\n */\n load() {\n this.getSourceTiles();\n }\n\n /**\n * Remove from the cache due to expiry\n */\n release() {\n for (const key in this.context_) {\n const context = this.context_[key];\n releaseCanvas(context);\n canvasPool.push(context.canvas);\n delete this.context_[key];\n }\n super.release();\n }\n}\n\nexport default VectorRenderTile;\n","/**\n * @module ol/VectorTile\n */\nimport Tile from './Tile.js';\nimport TileState from './TileState.js';\n\nclass VectorTile extends Tile {\n /**\n * @param {import(\"./tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n * @param {import(\"./TileState.js\").default} state State.\n * @param {string} src Data source url.\n * @param {import(\"./format/Feature.js\").default} format Feature format.\n * @param {import(\"./Tile.js\").LoadFunction} tileLoadFunction Tile load function.\n * @param {import(\"./Tile.js\").Options} [options] Tile options.\n */\n constructor(tileCoord, state, src, format, tileLoadFunction, options) {\n super(tileCoord, state, options);\n\n /**\n * Extent of this tile; set by the source.\n * @type {import(\"./extent.js\").Extent}\n */\n this.extent = null;\n\n /**\n * @private\n * @type {import(\"./format/Feature.js\").default}\n */\n this.format_ = format;\n\n /**\n * @private\n * @type {Array}\n */\n this.features_ = null;\n\n /**\n * @private\n * @type {import(\"./featureloader.js\").FeatureLoader}\n */\n this.loader_;\n\n /**\n * Feature projection of this tile; set by the source.\n * @type {import(\"./proj/Projection.js\").default}\n */\n this.projection = null;\n\n /**\n * Resolution of this tile; set by the source.\n * @type {number}\n */\n this.resolution;\n\n /**\n * @private\n * @type {import(\"./Tile.js\").LoadFunction}\n */\n this.tileLoadFunction_ = tileLoadFunction;\n\n /**\n * @private\n * @type {string}\n */\n this.url_ = src;\n\n this.key = src;\n }\n\n /**\n * Get the feature format assigned for reading this tile's features.\n * @return {import(\"./format/Feature.js\").default} Feature format.\n * @api\n */\n getFormat() {\n return this.format_;\n }\n\n /**\n * Get the features for this tile. Geometries will be in the view projection.\n * @return {Array} Features.\n * @api\n */\n getFeatures() {\n return this.features_;\n }\n\n /**\n * Load not yet loaded URI.\n */\n load() {\n if (this.state == TileState.IDLE) {\n this.setState(TileState.LOADING);\n this.tileLoadFunction_(this, this.url_);\n if (this.loader_) {\n this.loader_(this.extent, this.resolution, this.projection);\n }\n }\n }\n\n /**\n * Handler for successful tile load.\n * @param {Array} features The loaded features.\n * @param {import(\"./proj/Projection.js\").default} dataProjection Data projection.\n */\n onLoad(features, dataProjection) {\n this.setFeatures(features);\n }\n\n /**\n * Handler for tile load errors.\n */\n onError() {\n this.setState(TileState.ERROR);\n }\n\n /**\n * Function for use in an {@link module:ol/source/VectorTile~VectorTile}'s `tileLoadFunction`.\n * Sets the features for the tile.\n * @param {Array} features Features.\n * @api\n */\n setFeatures(features) {\n this.features_ = features;\n this.setState(TileState.LOADED);\n }\n\n /**\n * Set the feature loader for reading this tile's features.\n * @param {import(\"./featureloader.js\").FeatureLoader} loader Feature loader.\n * @api\n */\n setLoader(loader) {\n this.loader_ = loader;\n }\n}\n\nexport default VectorTile;\n","/**\n * @module ol/colorlike\n */\nimport {toString} from './color.js';\n\n/**\n * A type accepted by CanvasRenderingContext2D.fillStyle\n * or CanvasRenderingContext2D.strokeStyle.\n * Represents a color, pattern, or gradient. The origin for patterns and\n * gradients as fill style is an increment of 512 css pixels from map coordinate\n * `[0, 0]`. For seamless repeat patterns, width and height of the pattern image\n * must be a factor of two (2, 4, 8, ..., 512).\n *\n * @typedef {string|CanvasPattern|CanvasGradient} ColorLike\n * @api\n */\n\n/**\n * @param {import(\"./color.js\").Color|ColorLike} color Color.\n * @return {ColorLike} The color as an {@link ol/colorlike~ColorLike}.\n * @api\n */\nexport function asColorLike(color) {\n if (Array.isArray(color)) {\n return toString(color);\n }\n return color;\n}\n","/**\n * @module ol/featureloader\n */\nimport {VOID} from './functions.js';\n\n/**\n *\n * @type {boolean}\n * @private\n */\nlet withCredentials = false;\n\n/**\n * {@link module:ol/source/Vector~VectorSource} sources use a function of this type to\n * load features.\n *\n * This function takes up to 5 arguments. These are an {@link module:ol/extent~Extent} representing\n * the area to be loaded, a `{number}` representing the resolution (map units per pixel), an\n * {@link module:ol/proj/Projection~Projection} for the projection, an optional success callback that should get\n * the loaded features passed as an argument and an optional failure callback with no arguments. If\n * the callbacks are not used, the corresponding vector source will not fire `'featuresloadend'` and\n * `'featuresloaderror'` events. `this` within the function is bound to the\n * {@link module:ol/source/Vector~VectorSource} it's called from.\n *\n * The function is responsible for loading the features and adding them to the\n * source.\n * @typedef {function(this:(import(\"./source/Vector\").default|import(\"./VectorTile.js\").default),\n * import(\"./extent.js\").Extent,\n * number,\n * import(\"./proj/Projection.js\").default,\n * function(Array): void=,\n * function(): void=): void} FeatureLoader\n * @api\n */\n\n/**\n * {@link module:ol/source/Vector~VectorSource} sources use a function of this type to\n * get the url to load features from.\n *\n * This function takes an {@link module:ol/extent~Extent} representing the area\n * to be loaded, a `{number}` representing the resolution (map units per pixel)\n * and an {@link module:ol/proj/Projection~Projection} for the projection as\n * arguments and returns a `{string}` representing the URL.\n * @typedef {function(import(\"./extent.js\").Extent, number, import(\"./proj/Projection.js\").default): string} FeatureUrlFunction\n * @api\n */\n\n/**\n * @param {string|FeatureUrlFunction} url Feature URL service.\n * @param {import(\"./format/Feature.js\").default} format Feature format.\n * @param {import(\"./extent.js\").Extent} extent Extent.\n * @param {number} resolution Resolution.\n * @param {import(\"./proj/Projection.js\").default} projection Projection.\n * @param {function(Array, import(\"./proj/Projection.js\").default): void} success Success\n * Function called with the loaded features and optionally with the data projection.\n * @param {function(): void} failure Failure\n * Function called when loading failed.\n */\nexport function loadFeaturesXhr(\n url,\n format,\n extent,\n resolution,\n projection,\n success,\n failure\n) {\n const xhr = new XMLHttpRequest();\n xhr.open(\n 'GET',\n typeof url === 'function' ? url(extent, resolution, projection) : url,\n true\n );\n if (format.getType() == 'arraybuffer') {\n xhr.responseType = 'arraybuffer';\n }\n xhr.withCredentials = withCredentials;\n /**\n * @param {Event} event Event.\n * @private\n */\n xhr.onload = function (event) {\n // status will be 0 for file:// urls\n if (!xhr.status || (xhr.status >= 200 && xhr.status < 300)) {\n const type = format.getType();\n /** @type {Document|Node|Object|string|undefined} */\n let source;\n if (type == 'json' || type == 'text') {\n source = xhr.responseText;\n } else if (type == 'xml') {\n source = xhr.responseXML;\n if (!source) {\n source = new DOMParser().parseFromString(\n xhr.responseText,\n 'application/xml'\n );\n }\n } else if (type == 'arraybuffer') {\n source = /** @type {ArrayBuffer} */ (xhr.response);\n }\n if (source) {\n success(\n /** @type {Array} */\n (\n format.readFeatures(source, {\n extent: extent,\n featureProjection: projection,\n })\n ),\n format.readProjection(source)\n );\n } else {\n failure();\n }\n } else {\n failure();\n }\n };\n /**\n * @private\n */\n xhr.onerror = failure;\n xhr.send();\n}\n\n/**\n * Create an XHR feature loader for a `url` and `format`. The feature loader\n * loads features (with XHR), parses the features, and adds them to the\n * vector source.\n * @param {string|FeatureUrlFunction} url Feature URL service.\n * @param {import(\"./format/Feature.js\").default} format Feature format.\n * @return {FeatureLoader} The feature loader.\n * @api\n */\nexport function xhr(url, format) {\n /**\n * @param {import(\"./extent.js\").Extent} extent Extent.\n * @param {number} resolution Resolution.\n * @param {import(\"./proj/Projection.js\").default} projection Projection.\n * @param {function(Array): void} [success] Success\n * Function called when loading succeeded.\n * @param {function(): void} [failure] Failure\n * Function called when loading failed.\n */\n return function (extent, resolution, projection, success, failure) {\n const source = /** @type {import(\"./source/Vector\").default} */ (this);\n loadFeaturesXhr(\n url,\n format,\n extent,\n resolution,\n projection,\n /**\n * @param {Array} features The loaded features.\n * @param {import(\"./proj/Projection.js\").default} dataProjection Data\n * projection.\n */\n function (features, dataProjection) {\n source.addFeatures(features);\n if (success !== undefined) {\n success(features);\n }\n },\n /* FIXME handle error */ failure ? failure : VOID\n );\n };\n}\n\n/**\n * Setter for the withCredentials configuration for the XHR.\n *\n * @param {boolean} xhrWithCredentials The value of withCredentials to set.\n * Compare https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/\n * @api\n */\nexport function setWithCredentials(xhrWithCredentials) {\n withCredentials = xhrWithCredentials;\n}\n","/**\n * @module ol/net\n */\nimport {getUid} from './util.js';\n\n/**\n * Simple JSONP helper. Supports error callbacks and a custom callback param.\n * The error callback will be called when no JSONP is executed after 10 seconds.\n *\n * @param {string} url Request url. A 'callback' query parameter will be\n * appended.\n * @param {Function} callback Callback on success.\n * @param {Function} [errback] Callback on error.\n * @param {string} [callbackParam] Custom query parameter for the JSONP\n * callback. Default is 'callback'.\n */\nexport function jsonp(url, callback, errback, callbackParam) {\n const script = document.createElement('script');\n const key = 'olc_' + getUid(callback);\n function cleanup() {\n delete window[key];\n script.parentNode.removeChild(script);\n }\n script.async = true;\n script.src =\n url +\n (url.includes('?') ? '&' : '?') +\n (callbackParam || 'callback') +\n '=' +\n key;\n const timer = setTimeout(function () {\n cleanup();\n if (errback) {\n errback();\n }\n }, 10000);\n window[key] = function (data) {\n clearTimeout(timer);\n cleanup();\n callback(data);\n };\n document.head.appendChild(script);\n}\n\nexport class ResponseError extends Error {\n /**\n * @param {XMLHttpRequest} response The XHR object.\n */\n constructor(response) {\n const message = 'Unexpected response status: ' + response.status;\n super(message);\n\n /**\n * @type {string}\n */\n this.name = 'ResponseError';\n\n /**\n * @type {XMLHttpRequest}\n */\n this.response = response;\n }\n}\n\nexport class ClientError extends Error {\n /**\n * @param {XMLHttpRequest} client The XHR object.\n */\n constructor(client) {\n super('Failed to issue request');\n\n /**\n * @type {string}\n */\n this.name = 'ClientError';\n\n /**\n * @type {XMLHttpRequest}\n */\n this.client = client;\n }\n}\n\n/**\n * @param {string} url The URL.\n * @return {Promise} A promise that resolves to the JSON response.\n */\nexport function getJSON(url) {\n return new Promise(function (resolve, reject) {\n /**\n * @param {ProgressEvent} event The load event.\n */\n function onLoad(event) {\n const client = event.target;\n // status will be 0 for file:// urls\n if (!client.status || (client.status >= 200 && client.status < 300)) {\n let data;\n try {\n data = JSON.parse(client.responseText);\n } catch (err) {\n const message = 'Error parsing response text as JSON: ' + err.message;\n reject(new Error(message));\n return;\n }\n resolve(data);\n return;\n }\n\n reject(new ResponseError(client));\n }\n\n /**\n * @param {ProgressEvent} event The error event.\n */\n function onError(event) {\n reject(new ClientError(event.target));\n }\n\n const client = new XMLHttpRequest();\n client.addEventListener('load', onLoad);\n client.addEventListener('error', onError);\n client.open('GET', url);\n client.setRequestHeader('Accept', 'application/json');\n client.send();\n });\n}\n\n/**\n * @param {string} base The base URL.\n * @param {string} url The potentially relative URL.\n * @return {string} The full URL.\n */\nexport function resolveUrl(base, url) {\n if (url.includes('://')) {\n return url;\n }\n return new URL(url, base).href;\n}\n\nlet originalXHR;\nexport function overrideXHR(xhr) {\n if (typeof XMLHttpRequest !== 'undefined') {\n originalXHR = XMLHttpRequest;\n }\n global.XMLHttpRequest = xhr;\n}\n\nexport function restoreXHR() {\n global.XMLHttpRequest = originalXHR;\n}\n","/**\n * @module ol/loadingstrategy\n */\n\nimport {fromUserExtent, fromUserResolution, toUserExtent} from './proj.js';\n\n/**\n * Strategy function for loading all features with a single request.\n * @param {import(\"./extent.js\").Extent} extent Extent.\n * @param {number} resolution Resolution.\n * @return {Array} Extents.\n * @api\n */\nexport function all(extent, resolution) {\n return [[-Infinity, -Infinity, Infinity, Infinity]];\n}\n\n/**\n * Strategy function for loading features based on the view's extent and\n * resolution.\n * @param {import(\"./extent.js\").Extent} extent Extent.\n * @param {number} resolution Resolution.\n * @return {Array} Extents.\n * @api\n */\nexport function bbox(extent, resolution) {\n return [extent];\n}\n\n/**\n * Creates a strategy function for loading features based on a tile grid.\n * @param {import(\"./tilegrid/TileGrid.js\").default} tileGrid Tile grid.\n * @return {function(import(\"./extent.js\").Extent, number, import(\"./proj.js\").Projection): Array} Loading strategy.\n * @api\n */\nexport function tile(tileGrid) {\n return (\n /**\n * @param {import(\"./extent.js\").Extent} extent Extent.\n * @param {number} resolution Resolution.\n * @param {import(\"./proj.js\").Projection} projection Projection.\n * @return {Array} Extents.\n */\n function (extent, resolution, projection) {\n const z = tileGrid.getZForResolution(\n fromUserResolution(resolution, projection)\n );\n const tileRange = tileGrid.getTileRangeForExtentAndZ(\n fromUserExtent(extent, projection),\n z\n );\n /** @type {Array} */\n const extents = [];\n /** @type {import(\"./tilecoord.js\").TileCoord} */\n const tileCoord = [z, 0, 0];\n for (\n tileCoord[1] = tileRange.minX;\n tileCoord[1] <= tileRange.maxX;\n ++tileCoord[1]\n ) {\n for (\n tileCoord[2] = tileRange.minY;\n tileCoord[2] <= tileRange.maxY;\n ++tileCoord[2]\n ) {\n extents.push(\n toUserExtent(tileGrid.getTileCoordExtent(tileCoord), projection)\n );\n }\n }\n return extents;\n }\n );\n}\n","/**\n * @module ol/render/VectorContext\n */\n\n/**\n * @classdesc\n * Context for drawing geometries. A vector context is available on render\n * events and does not need to be constructed directly.\n * @api\n */\nclass VectorContext {\n /**\n * Render a geometry with a custom renderer.\n *\n * @param {import(\"../geom/SimpleGeometry.js\").default} geometry Geometry.\n * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n * @param {Function} renderer Renderer.\n * @param {Function} hitDetectionRenderer Renderer.\n */\n drawCustom(geometry, feature, renderer, hitDetectionRenderer) {}\n\n /**\n * Render a geometry.\n *\n * @param {import(\"../geom/Geometry.js\").default} geometry The geometry to render.\n */\n drawGeometry(geometry) {}\n\n /**\n * Set the rendering style.\n *\n * @param {import(\"../style/Style.js\").default} style The rendering style.\n */\n setStyle(style) {}\n\n /**\n * @param {import(\"../geom/Circle.js\").default} circleGeometry Circle geometry.\n * @param {import(\"../Feature.js\").default} feature Feature.\n */\n drawCircle(circleGeometry, feature) {}\n\n /**\n * @param {import(\"../Feature.js\").default} feature Feature.\n * @param {import(\"../style/Style.js\").default} style Style.\n */\n drawFeature(feature, style) {}\n\n /**\n * @param {import(\"../geom/GeometryCollection.js\").default} geometryCollectionGeometry Geometry collection.\n * @param {import(\"../Feature.js\").default} feature Feature.\n */\n drawGeometryCollection(geometryCollectionGeometry, feature) {}\n\n /**\n * @param {import(\"../geom/LineString.js\").default|import(\"./Feature.js\").default} lineStringGeometry Line string geometry.\n * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n */\n drawLineString(lineStringGeometry, feature) {}\n\n /**\n * @param {import(\"../geom/MultiLineString.js\").default|import(\"./Feature.js\").default} multiLineStringGeometry MultiLineString geometry.\n * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n */\n drawMultiLineString(multiLineStringGeometry, feature) {}\n\n /**\n * @param {import(\"../geom/MultiPoint.js\").default|import(\"./Feature.js\").default} multiPointGeometry MultiPoint geometry.\n * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n */\n drawMultiPoint(multiPointGeometry, feature) {}\n\n /**\n * @param {import(\"../geom/MultiPolygon.js\").default} multiPolygonGeometry MultiPolygon geometry.\n * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n */\n drawMultiPolygon(multiPolygonGeometry, feature) {}\n\n /**\n * @param {import(\"../geom/Point.js\").default|import(\"./Feature.js\").default} pointGeometry Point geometry.\n * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n */\n drawPoint(pointGeometry, feature) {}\n\n /**\n * @param {import(\"../geom/Polygon.js\").default|import(\"./Feature.js\").default} polygonGeometry Polygon geometry.\n * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n */\n drawPolygon(polygonGeometry, feature) {}\n\n /**\n * @param {import(\"../geom/SimpleGeometry.js\").default|import(\"./Feature.js\").default} geometry Geometry.\n * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n */\n drawText(geometry, feature) {}\n\n /**\n * @param {import(\"../style/Fill.js\").default} fillStyle Fill style.\n * @param {import(\"../style/Stroke.js\").default} strokeStyle Stroke style.\n */\n setFillStrokeStyle(fillStyle, strokeStyle) {}\n\n /**\n * @param {import(\"../style/Image.js\").default} imageStyle Image style.\n * @param {import(\"../render/canvas.js\").DeclutterImageWithText} [declutterImageWithText] Shared data for combined decluttering with a text style.\n */\n setImageStyle(imageStyle, declutterImageWithText) {}\n\n /**\n * @param {import(\"../style/Text.js\").default} textStyle Text style.\n * @param {import(\"../render/canvas.js\").DeclutterImageWithText} [declutterImageWithText] Shared data for combined decluttering with an image style.\n */\n setTextStyle(textStyle, declutterImageWithText) {}\n}\n\nexport default VectorContext;\n","/**\n * @module ol/render/canvas/Immediate\n */\n// FIXME test, especially polygons with holes and multipolygons\n// FIXME need to handle large thick features (where pixel size matters)\n// FIXME add offset and end to ol/geom/flat/transform~transform2D?\n\nimport VectorContext from '../VectorContext.js';\nimport {asColorLike} from '../../colorlike.js';\nimport {\n compose as composeTransform,\n create as createTransform,\n} from '../../transform.js';\nimport {\n defaultFillStyle,\n defaultFont,\n defaultLineCap,\n defaultLineDash,\n defaultLineDashOffset,\n defaultLineJoin,\n defaultLineWidth,\n defaultMiterLimit,\n defaultStrokeStyle,\n defaultTextAlign,\n defaultTextBaseline,\n} from '../canvas.js';\nimport {equals} from '../../array.js';\nimport {intersects} from '../../extent.js';\nimport {toFixed} from '../../math.js';\nimport {transform2D} from '../../geom/flat/transform.js';\nimport {transformGeom2D} from '../../geom/SimpleGeometry.js';\n\n/**\n * @classdesc\n * A concrete subclass of {@link module:ol/render/VectorContext~VectorContext} that implements\n * direct rendering of features and geometries to an HTML5 Canvas context.\n * Instances of this class are created internally by the library and\n * provided to application code as vectorContext member of the\n * {@link module:ol/render/Event~RenderEvent} object associated with postcompose, precompose and\n * render events emitted by layers and maps.\n */\nclass CanvasImmediateRenderer extends VectorContext {\n /**\n * @param {CanvasRenderingContext2D} context Context.\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"../../extent.js\").Extent} extent Extent.\n * @param {import(\"../../transform.js\").Transform} transform Transform.\n * @param {number} viewRotation View rotation.\n * @param {number} [squaredTolerance] Optional squared tolerance for simplification.\n * @param {import(\"../../proj.js\").TransformFunction} [userTransform] Transform from user to view projection.\n */\n constructor(\n context,\n pixelRatio,\n extent,\n transform,\n viewRotation,\n squaredTolerance,\n userTransform\n ) {\n super();\n\n /**\n * @private\n * @type {CanvasRenderingContext2D}\n */\n this.context_ = context;\n\n /**\n * @private\n * @type {number}\n */\n this.pixelRatio_ = pixelRatio;\n\n /**\n * @private\n * @type {import(\"../../extent.js\").Extent}\n */\n this.extent_ = extent;\n\n /**\n * @private\n * @type {import(\"../../transform.js\").Transform}\n */\n this.transform_ = transform;\n\n /**\n * @private\n * @type {number}\n */\n this.transformRotation_ = transform\n ? toFixed(Math.atan2(transform[1], transform[0]), 10)\n : 0;\n\n /**\n * @private\n * @type {number}\n */\n this.viewRotation_ = viewRotation;\n\n /**\n * @private\n * @type {number}\n */\n this.squaredTolerance_ = squaredTolerance;\n\n /**\n * @private\n * @type {import(\"../../proj.js\").TransformFunction}\n */\n this.userTransform_ = userTransform;\n\n /**\n * @private\n * @type {?import(\"../canvas.js\").FillState}\n */\n this.contextFillState_ = null;\n\n /**\n * @private\n * @type {?import(\"../canvas.js\").StrokeState}\n */\n this.contextStrokeState_ = null;\n\n /**\n * @private\n * @type {?import(\"../canvas.js\").TextState}\n */\n this.contextTextState_ = null;\n\n /**\n * @private\n * @type {?import(\"../canvas.js\").FillState}\n */\n this.fillState_ = null;\n\n /**\n * @private\n * @type {?import(\"../canvas.js\").StrokeState}\n */\n this.strokeState_ = null;\n\n /**\n * @private\n * @type {HTMLCanvasElement|HTMLVideoElement|HTMLImageElement}\n */\n this.image_ = null;\n\n /**\n * @private\n * @type {number}\n */\n this.imageAnchorX_ = 0;\n\n /**\n * @private\n * @type {number}\n */\n this.imageAnchorY_ = 0;\n\n /**\n * @private\n * @type {number}\n */\n this.imageHeight_ = 0;\n\n /**\n * @private\n * @type {number}\n */\n this.imageOpacity_ = 0;\n\n /**\n * @private\n * @type {number}\n */\n this.imageOriginX_ = 0;\n\n /**\n * @private\n * @type {number}\n */\n this.imageOriginY_ = 0;\n\n /**\n * @private\n * @type {boolean}\n */\n this.imageRotateWithView_ = false;\n\n /**\n * @private\n * @type {number}\n */\n this.imageRotation_ = 0;\n\n /**\n * @private\n * @type {import(\"../../size.js\").Size}\n */\n this.imageScale_ = [0, 0];\n\n /**\n * @private\n * @type {number}\n */\n this.imageWidth_ = 0;\n\n /**\n * @private\n * @type {string}\n */\n this.text_ = '';\n\n /**\n * @private\n * @type {number}\n */\n this.textOffsetX_ = 0;\n\n /**\n * @private\n * @type {number}\n */\n this.textOffsetY_ = 0;\n\n /**\n * @private\n * @type {boolean}\n */\n this.textRotateWithView_ = false;\n\n /**\n * @private\n * @type {number}\n */\n this.textRotation_ = 0;\n\n /**\n * @private\n * @type {import(\"../../size.js\").Size}\n */\n this.textScale_ = [0, 0];\n\n /**\n * @private\n * @type {?import(\"../canvas.js\").FillState}\n */\n this.textFillState_ = null;\n\n /**\n * @private\n * @type {?import(\"../canvas.js\").StrokeState}\n */\n this.textStrokeState_ = null;\n\n /**\n * @private\n * @type {?import(\"../canvas.js\").TextState}\n */\n this.textState_ = null;\n\n /**\n * @private\n * @type {Array}\n */\n this.pixelCoordinates_ = [];\n\n /**\n * @private\n * @type {import(\"../../transform.js\").Transform}\n */\n this.tmpLocalTransform_ = createTransform();\n }\n\n /**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @private\n */\n drawImages_(flatCoordinates, offset, end, stride) {\n if (!this.image_) {\n return;\n }\n const pixelCoordinates = transform2D(\n flatCoordinates,\n offset,\n end,\n stride,\n this.transform_,\n this.pixelCoordinates_\n );\n const context = this.context_;\n const localTransform = this.tmpLocalTransform_;\n const alpha = context.globalAlpha;\n if (this.imageOpacity_ != 1) {\n context.globalAlpha = alpha * this.imageOpacity_;\n }\n let rotation = this.imageRotation_;\n if (this.transformRotation_ === 0) {\n rotation -= this.viewRotation_;\n }\n if (this.imageRotateWithView_) {\n rotation += this.viewRotation_;\n }\n for (let i = 0, ii = pixelCoordinates.length; i < ii; i += 2) {\n const x = pixelCoordinates[i] - this.imageAnchorX_;\n const y = pixelCoordinates[i + 1] - this.imageAnchorY_;\n if (\n rotation !== 0 ||\n this.imageScale_[0] != 1 ||\n this.imageScale_[1] != 1\n ) {\n const centerX = x + this.imageAnchorX_;\n const centerY = y + this.imageAnchorY_;\n composeTransform(\n localTransform,\n centerX,\n centerY,\n 1,\n 1,\n rotation,\n -centerX,\n -centerY\n );\n context.setTransform.apply(context, localTransform);\n context.translate(centerX, centerY);\n context.scale(this.imageScale_[0], this.imageScale_[1]);\n context.drawImage(\n this.image_,\n this.imageOriginX_,\n this.imageOriginY_,\n this.imageWidth_,\n this.imageHeight_,\n -this.imageAnchorX_,\n -this.imageAnchorY_,\n this.imageWidth_,\n this.imageHeight_\n );\n context.setTransform(1, 0, 0, 1, 0, 0);\n } else {\n context.drawImage(\n this.image_,\n this.imageOriginX_,\n this.imageOriginY_,\n this.imageWidth_,\n this.imageHeight_,\n x,\n y,\n this.imageWidth_,\n this.imageHeight_\n );\n }\n }\n if (this.imageOpacity_ != 1) {\n context.globalAlpha = alpha;\n }\n }\n\n /**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @private\n */\n drawText_(flatCoordinates, offset, end, stride) {\n if (!this.textState_ || this.text_ === '') {\n return;\n }\n if (this.textFillState_) {\n this.setContextFillState_(this.textFillState_);\n }\n if (this.textStrokeState_) {\n this.setContextStrokeState_(this.textStrokeState_);\n }\n this.setContextTextState_(this.textState_);\n const pixelCoordinates = transform2D(\n flatCoordinates,\n offset,\n end,\n stride,\n this.transform_,\n this.pixelCoordinates_\n );\n const context = this.context_;\n let rotation = this.textRotation_;\n if (this.transformRotation_ === 0) {\n rotation -= this.viewRotation_;\n }\n if (this.textRotateWithView_) {\n rotation += this.viewRotation_;\n }\n for (; offset < end; offset += stride) {\n const x = pixelCoordinates[offset] + this.textOffsetX_;\n const y = pixelCoordinates[offset + 1] + this.textOffsetY_;\n if (\n rotation !== 0 ||\n this.textScale_[0] != 1 ||\n this.textScale_[1] != 1\n ) {\n context.translate(x - this.textOffsetX_, y - this.textOffsetY_);\n context.rotate(rotation);\n context.translate(this.textOffsetX_, this.textOffsetY_);\n context.scale(this.textScale_[0], this.textScale_[1]);\n if (this.textStrokeState_) {\n context.strokeText(this.text_, 0, 0);\n }\n if (this.textFillState_) {\n context.fillText(this.text_, 0, 0);\n }\n context.setTransform(1, 0, 0, 1, 0, 0);\n } else {\n if (this.textStrokeState_) {\n context.strokeText(this.text_, x, y);\n }\n if (this.textFillState_) {\n context.fillText(this.text_, x, y);\n }\n }\n }\n }\n\n /**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {number} end End.\n * @param {number} stride Stride.\n * @param {boolean} close Close.\n * @private\n * @return {number} end End.\n */\n moveToLineTo_(flatCoordinates, offset, end, stride, close) {\n const context = this.context_;\n const pixelCoordinates = transform2D(\n flatCoordinates,\n offset,\n end,\n stride,\n this.transform_,\n this.pixelCoordinates_\n );\n context.moveTo(pixelCoordinates[0], pixelCoordinates[1]);\n let length = pixelCoordinates.length;\n if (close) {\n length -= 2;\n }\n for (let i = 2; i < length; i += 2) {\n context.lineTo(pixelCoordinates[i], pixelCoordinates[i + 1]);\n }\n if (close) {\n context.closePath();\n }\n return end;\n }\n\n /**\n * @param {Array} flatCoordinates Flat coordinates.\n * @param {number} offset Offset.\n * @param {Array} ends Ends.\n * @param {number} stride Stride.\n * @private\n * @return {number} End.\n */\n drawRings_(flatCoordinates, offset, ends, stride) {\n for (let i = 0, ii = ends.length; i < ii; ++i) {\n offset = this.moveToLineTo_(\n flatCoordinates,\n offset,\n ends[i],\n stride,\n true\n );\n }\n return offset;\n }\n\n /**\n * Render a circle geometry into the canvas. Rendering is immediate and uses\n * the current fill and stroke styles.\n *\n * @param {import(\"../../geom/Circle.js\").default} geometry Circle geometry.\n * @api\n */\n drawCircle(geometry) {\n if (this.squaredTolerance_) {\n geometry = /** @type {import(\"../../geom/Circle.js\").default} */ (\n geometry.simplifyTransformed(\n this.squaredTolerance_,\n this.userTransform_\n )\n );\n }\n if (!intersects(this.extent_, geometry.getExtent())) {\n return;\n }\n if (this.fillState_ || this.strokeState_) {\n if (this.fillState_) {\n this.setContextFillState_(this.fillState_);\n }\n if (this.strokeState_) {\n this.setContextStrokeState_(this.strokeState_);\n }\n const pixelCoordinates = transformGeom2D(\n geometry,\n this.transform_,\n this.pixelCoordinates_\n );\n const dx = pixelCoordinates[2] - pixelCoordinates[0];\n const dy = pixelCoordinates[3] - pixelCoordinates[1];\n const radius = Math.sqrt(dx * dx + dy * dy);\n const context = this.context_;\n context.beginPath();\n context.arc(\n pixelCoordinates[0],\n pixelCoordinates[1],\n radius,\n 0,\n 2 * Math.PI\n );\n if (this.fillState_) {\n context.fill();\n }\n if (this.strokeState_) {\n context.stroke();\n }\n }\n if (this.text_ !== '') {\n this.drawText_(geometry.getCenter(), 0, 2, 2);\n }\n }\n\n /**\n * Set the rendering style. Note that since this is an immediate rendering API,\n * any `zIndex` on the provided style will be ignored.\n *\n * @param {import(\"../../style/Style.js\").default} style The rendering style.\n * @api\n */\n setStyle(style) {\n this.setFillStrokeStyle(style.getFill(), style.getStroke());\n this.setImageStyle(style.getImage());\n this.setTextStyle(style.getText());\n }\n\n /**\n * @param {import(\"../../transform.js\").Transform} transform Transform.\n */\n setTransform(transform) {\n this.transform_ = transform;\n }\n\n /**\n * Render a geometry into the canvas. Call\n * {@link module:ol/render/canvas/Immediate~CanvasImmediateRenderer#setStyle renderer.setStyle()} first to set the rendering style.\n *\n * @param {import(\"../../geom/Geometry.js\").default|import(\"../Feature.js\").default} geometry The geometry to render.\n * @api\n */\n drawGeometry(geometry) {\n const type = geometry.getType();\n switch (type) {\n case 'Point':\n this.drawPoint(\n /** @type {import(\"../../geom/Point.js\").default} */ (geometry)\n );\n break;\n case 'LineString':\n this.drawLineString(\n /** @type {import(\"../../geom/LineString.js\").default} */ (geometry)\n );\n break;\n case 'Polygon':\n this.drawPolygon(\n /** @type {import(\"../../geom/Polygon.js\").default} */ (geometry)\n );\n break;\n case 'MultiPoint':\n this.drawMultiPoint(\n /** @type {import(\"../../geom/MultiPoint.js\").default} */ (geometry)\n );\n break;\n case 'MultiLineString':\n this.drawMultiLineString(\n /** @type {import(\"../../geom/MultiLineString.js\").default} */ (\n geometry\n )\n );\n break;\n case 'MultiPolygon':\n this.drawMultiPolygon(\n /** @type {import(\"../../geom/MultiPolygon.js\").default} */ (geometry)\n );\n break;\n case 'GeometryCollection':\n this.drawGeometryCollection(\n /** @type {import(\"../../geom/GeometryCollection.js\").default} */ (\n geometry\n )\n );\n break;\n case 'Circle':\n this.drawCircle(\n /** @type {import(\"../../geom/Circle.js\").default} */ (geometry)\n );\n break;\n default:\n }\n }\n\n /**\n * Render a feature into the canvas. Note that any `zIndex` on the provided\n * style will be ignored - features are rendered immediately in the order that\n * this method is called. If you need `zIndex` support, you should be using an\n * {@link module:ol/layer/Vector~VectorLayer} instead.\n *\n * @param {import(\"../../Feature.js\").default} feature Feature.\n * @param {import(\"../../style/Style.js\").default} style Style.\n * @api\n */\n drawFeature(feature, style) {\n const geometry = style.getGeometryFunction()(feature);\n if (!geometry) {\n return;\n }\n this.setStyle(style);\n this.drawGeometry(geometry);\n }\n\n /**\n * Render a GeometryCollection to the canvas. Rendering is immediate and\n * uses the current styles appropriate for each geometry in the collection.\n *\n * @param {import(\"../../geom/GeometryCollection.js\").default} geometry Geometry collection.\n */\n drawGeometryCollection(geometry) {\n const geometries = geometry.getGeometriesArray();\n for (let i = 0, ii = geometries.length; i < ii; ++i) {\n this.drawGeometry(geometries[i]);\n }\n }\n\n /**\n * Render a Point geometry into the canvas. Rendering is immediate and uses\n * the current style.\n *\n * @param {import(\"../../geom/Point.js\").default|import(\"../Feature.js\").default} geometry Point geometry.\n */\n drawPoint(geometry) {\n if (this.squaredTolerance_) {\n geometry = /** @type {import(\"../../geom/Point.js\").default} */ (\n geometry.simplifyTransformed(\n this.squaredTolerance_,\n this.userTransform_\n )\n );\n }\n const flatCoordinates = geometry.getFlatCoordinates();\n const stride = geometry.getStride();\n if (this.image_) {\n this.drawImages_(flatCoordinates, 0, flatCoordinates.length, stride);\n }\n if (this.text_ !== '') {\n this.drawText_(flatCoordinates, 0, flatCoordinates.length, stride);\n }\n }\n\n /**\n * Render a MultiPoint geometry into the canvas. Rendering is immediate and\n * uses the current style.\n *\n * @param {import(\"../../geom/MultiPoint.js\").default|import(\"../Feature.js\").default} geometry MultiPoint geometry.\n */\n drawMultiPoint(geometry) {\n if (this.squaredTolerance_) {\n geometry = /** @type {import(\"../../geom/MultiPoint.js\").default} */ (\n geometry.simplifyTransformed(\n this.squaredTolerance_,\n this.userTransform_\n )\n );\n }\n const flatCoordinates = geometry.getFlatCoordinates();\n const stride = geometry.getStride();\n if (this.image_) {\n this.drawImages_(flatCoordinates, 0, flatCoordinates.length, stride);\n }\n if (this.text_ !== '') {\n this.drawText_(flatCoordinates, 0, flatCoordinates.length, stride);\n }\n }\n\n /**\n * Render a LineString into the canvas. Rendering is immediate and uses\n * the current style.\n *\n * @param {import(\"../../geom/LineString.js\").default|import(\"../Feature.js\").default} geometry LineString geometry.\n */\n drawLineString(geometry) {\n if (this.squaredTolerance_) {\n geometry = /** @type {import(\"../../geom/LineString.js\").default} */ (\n geometry.simplifyTransformed(\n this.squaredTolerance_,\n this.userTransform_\n )\n );\n }\n if (!intersects(this.extent_, geometry.getExtent())) {\n return;\n }\n if (this.strokeState_) {\n this.setContextStrokeState_(this.strokeState_);\n const context = this.context_;\n const flatCoordinates = geometry.getFlatCoordinates();\n context.beginPath();\n this.moveToLineTo_(\n flatCoordinates,\n 0,\n flatCoordinates.length,\n geometry.getStride(),\n false\n );\n context.stroke();\n }\n if (this.text_ !== '') {\n const flatMidpoint = geometry.getFlatMidpoint();\n this.drawText_(flatMidpoint, 0, 2, 2);\n }\n }\n\n /**\n * Render a MultiLineString geometry into the canvas. Rendering is immediate\n * and uses the current style.\n *\n * @param {import(\"../../geom/MultiLineString.js\").default|import(\"../Feature.js\").default} geometry MultiLineString geometry.\n */\n drawMultiLineString(geometry) {\n if (this.squaredTolerance_) {\n geometry =\n /** @type {import(\"../../geom/MultiLineString.js\").default} */ (\n geometry.simplifyTransformed(\n this.squaredTolerance_,\n this.userTransform_\n )\n );\n }\n const geometryExtent = geometry.getExtent();\n if (!intersects(this.extent_, geometryExtent)) {\n return;\n }\n if (this.strokeState_) {\n this.setContextStrokeState_(this.strokeState_);\n const context = this.context_;\n const flatCoordinates = geometry.getFlatCoordinates();\n let offset = 0;\n const ends = /** @type {Array} */ (geometry.getEnds());\n const stride = geometry.getStride();\n context.beginPath();\n for (let i = 0, ii = ends.length; i < ii; ++i) {\n offset = this.moveToLineTo_(\n flatCoordinates,\n offset,\n ends[i],\n stride,\n false\n );\n }\n context.stroke();\n }\n if (this.text_ !== '') {\n const flatMidpoints = geometry.getFlatMidpoints();\n this.drawText_(flatMidpoints, 0, flatMidpoints.length, 2);\n }\n }\n\n /**\n * Render a Polygon geometry into the canvas. Rendering is immediate and uses\n * the current style.\n *\n * @param {import(\"../../geom/Polygon.js\").default|import(\"../Feature.js\").default} geometry Polygon geometry.\n */\n drawPolygon(geometry) {\n if (this.squaredTolerance_) {\n geometry = /** @type {import(\"../../geom/Polygon.js\").default} */ (\n geometry.simplifyTransformed(\n this.squaredTolerance_,\n this.userTransform_\n )\n );\n }\n if (!intersects(this.extent_, geometry.getExtent())) {\n return;\n }\n if (this.strokeState_ || this.fillState_) {\n if (this.fillState_) {\n this.setContextFillState_(this.fillState_);\n }\n if (this.strokeState_) {\n this.setContextStrokeState_(this.strokeState_);\n }\n const context = this.context_;\n context.beginPath();\n this.drawRings_(\n geometry.getOrientedFlatCoordinates(),\n 0,\n /** @type {Array} */ (geometry.getEnds()),\n geometry.getStride()\n );\n if (this.fillState_) {\n context.fill();\n }\n if (this.strokeState_) {\n context.stroke();\n }\n }\n if (this.text_ !== '') {\n const flatInteriorPoint = geometry.getFlatInteriorPoint();\n this.drawText_(flatInteriorPoint, 0, 2, 2);\n }\n }\n\n /**\n * Render MultiPolygon geometry into the canvas. Rendering is immediate and\n * uses the current style.\n * @param {import(\"../../geom/MultiPolygon.js\").default} geometry MultiPolygon geometry.\n */\n drawMultiPolygon(geometry) {\n if (this.squaredTolerance_) {\n geometry = /** @type {import(\"../../geom/MultiPolygon.js\").default} */ (\n geometry.simplifyTransformed(\n this.squaredTolerance_,\n this.userTransform_\n )\n );\n }\n if (!intersects(this.extent_, geometry.getExtent())) {\n return;\n }\n if (this.strokeState_ || this.fillState_) {\n if (this.fillState_) {\n this.setContextFillState_(this.fillState_);\n }\n if (this.strokeState_) {\n this.setContextStrokeState_(this.strokeState_);\n }\n const context = this.context_;\n const flatCoordinates = geometry.getOrientedFlatCoordinates();\n let offset = 0;\n const endss = geometry.getEndss();\n const stride = geometry.getStride();\n context.beginPath();\n for (let i = 0, ii = endss.length; i < ii; ++i) {\n const ends = endss[i];\n offset = this.drawRings_(flatCoordinates, offset, ends, stride);\n }\n if (this.fillState_) {\n context.fill();\n }\n if (this.strokeState_) {\n context.stroke();\n }\n }\n if (this.text_ !== '') {\n const flatInteriorPoints = geometry.getFlatInteriorPoints();\n this.drawText_(flatInteriorPoints, 0, flatInteriorPoints.length, 2);\n }\n }\n\n /**\n * @param {import(\"../canvas.js\").FillState} fillState Fill state.\n * @private\n */\n setContextFillState_(fillState) {\n const context = this.context_;\n const contextFillState = this.contextFillState_;\n if (!contextFillState) {\n context.fillStyle = fillState.fillStyle;\n this.contextFillState_ = {\n fillStyle: fillState.fillStyle,\n };\n } else {\n if (contextFillState.fillStyle != fillState.fillStyle) {\n contextFillState.fillStyle = fillState.fillStyle;\n context.fillStyle = fillState.fillStyle;\n }\n }\n }\n\n /**\n * @param {import(\"../canvas.js\").StrokeState} strokeState Stroke state.\n * @private\n */\n setContextStrokeState_(strokeState) {\n const context = this.context_;\n const contextStrokeState = this.contextStrokeState_;\n if (!contextStrokeState) {\n context.lineCap = strokeState.lineCap;\n context.setLineDash(strokeState.lineDash);\n context.lineDashOffset = strokeState.lineDashOffset;\n context.lineJoin = strokeState.lineJoin;\n context.lineWidth = strokeState.lineWidth;\n context.miterLimit = strokeState.miterLimit;\n context.strokeStyle = strokeState.strokeStyle;\n this.contextStrokeState_ = {\n lineCap: strokeState.lineCap,\n lineDash: strokeState.lineDash,\n lineDashOffset: strokeState.lineDashOffset,\n lineJoin: strokeState.lineJoin,\n lineWidth: strokeState.lineWidth,\n miterLimit: strokeState.miterLimit,\n strokeStyle: strokeState.strokeStyle,\n };\n } else {\n if (contextStrokeState.lineCap != strokeState.lineCap) {\n contextStrokeState.lineCap = strokeState.lineCap;\n context.lineCap = strokeState.lineCap;\n }\n if (!equals(contextStrokeState.lineDash, strokeState.lineDash)) {\n context.setLineDash(\n (contextStrokeState.lineDash = strokeState.lineDash)\n );\n }\n if (contextStrokeState.lineDashOffset != strokeState.lineDashOffset) {\n contextStrokeState.lineDashOffset = strokeState.lineDashOffset;\n context.lineDashOffset = strokeState.lineDashOffset;\n }\n if (contextStrokeState.lineJoin != strokeState.lineJoin) {\n contextStrokeState.lineJoin = strokeState.lineJoin;\n context.lineJoin = strokeState.lineJoin;\n }\n if (contextStrokeState.lineWidth != strokeState.lineWidth) {\n contextStrokeState.lineWidth = strokeState.lineWidth;\n context.lineWidth = strokeState.lineWidth;\n }\n if (contextStrokeState.miterLimit != strokeState.miterLimit) {\n contextStrokeState.miterLimit = strokeState.miterLimit;\n context.miterLimit = strokeState.miterLimit;\n }\n if (contextStrokeState.strokeStyle != strokeState.strokeStyle) {\n contextStrokeState.strokeStyle = strokeState.strokeStyle;\n context.strokeStyle = strokeState.strokeStyle;\n }\n }\n }\n\n /**\n * @param {import(\"../canvas.js\").TextState} textState Text state.\n * @private\n */\n setContextTextState_(textState) {\n const context = this.context_;\n const contextTextState = this.contextTextState_;\n const textAlign = textState.textAlign\n ? textState.textAlign\n : defaultTextAlign;\n if (!contextTextState) {\n context.font = textState.font;\n context.textAlign = textAlign;\n context.textBaseline = textState.textBaseline;\n this.contextTextState_ = {\n font: textState.font,\n textAlign: textAlign,\n textBaseline: textState.textBaseline,\n };\n } else {\n if (contextTextState.font != textState.font) {\n contextTextState.font = textState.font;\n context.font = textState.font;\n }\n if (contextTextState.textAlign != textAlign) {\n contextTextState.textAlign = textAlign;\n context.textAlign = textAlign;\n }\n if (contextTextState.textBaseline != textState.textBaseline) {\n contextTextState.textBaseline = textState.textBaseline;\n context.textBaseline = textState.textBaseline;\n }\n }\n }\n\n /**\n * Set the fill and stroke style for subsequent draw operations. To clear\n * either fill or stroke styles, pass null for the appropriate parameter.\n *\n * @param {import(\"../../style/Fill.js\").default} fillStyle Fill style.\n * @param {import(\"../../style/Stroke.js\").default} strokeStyle Stroke style.\n */\n setFillStrokeStyle(fillStyle, strokeStyle) {\n if (!fillStyle) {\n this.fillState_ = null;\n } else {\n const fillStyleColor = fillStyle.getColor();\n this.fillState_ = {\n fillStyle: asColorLike(\n fillStyleColor ? fillStyleColor : defaultFillStyle\n ),\n };\n }\n if (!strokeStyle) {\n this.strokeState_ = null;\n } else {\n const strokeStyleColor = strokeStyle.getColor();\n const strokeStyleLineCap = strokeStyle.getLineCap();\n const strokeStyleLineDash = strokeStyle.getLineDash();\n const strokeStyleLineDashOffset = strokeStyle.getLineDashOffset();\n const strokeStyleLineJoin = strokeStyle.getLineJoin();\n const strokeStyleWidth = strokeStyle.getWidth();\n const strokeStyleMiterLimit = strokeStyle.getMiterLimit();\n const lineDash = strokeStyleLineDash\n ? strokeStyleLineDash\n : defaultLineDash;\n this.strokeState_ = {\n lineCap:\n strokeStyleLineCap !== undefined\n ? strokeStyleLineCap\n : defaultLineCap,\n lineDash:\n this.pixelRatio_ === 1\n ? lineDash\n : lineDash.map((n) => n * this.pixelRatio_),\n lineDashOffset:\n (strokeStyleLineDashOffset\n ? strokeStyleLineDashOffset\n : defaultLineDashOffset) * this.pixelRatio_,\n lineJoin:\n strokeStyleLineJoin !== undefined\n ? strokeStyleLineJoin\n : defaultLineJoin,\n lineWidth:\n (strokeStyleWidth !== undefined\n ? strokeStyleWidth\n : defaultLineWidth) * this.pixelRatio_,\n miterLimit:\n strokeStyleMiterLimit !== undefined\n ? strokeStyleMiterLimit\n : defaultMiterLimit,\n strokeStyle: asColorLike(\n strokeStyleColor ? strokeStyleColor : defaultStrokeStyle\n ),\n };\n }\n }\n\n /**\n * Set the image style for subsequent draw operations. Pass null to remove\n * the image style.\n *\n * @param {import(\"../../style/Image.js\").default} imageStyle Image style.\n */\n setImageStyle(imageStyle) {\n let imageSize;\n if (!imageStyle || !(imageSize = imageStyle.getSize())) {\n this.image_ = null;\n return;\n }\n const imagePixelRatio = imageStyle.getPixelRatio(this.pixelRatio_);\n const imageAnchor = imageStyle.getAnchor();\n const imageOrigin = imageStyle.getOrigin();\n this.image_ = imageStyle.getImage(this.pixelRatio_);\n this.imageAnchorX_ = imageAnchor[0] * imagePixelRatio;\n this.imageAnchorY_ = imageAnchor[1] * imagePixelRatio;\n this.imageHeight_ = imageSize[1] * imagePixelRatio;\n this.imageOpacity_ = imageStyle.getOpacity();\n this.imageOriginX_ = imageOrigin[0];\n this.imageOriginY_ = imageOrigin[1];\n this.imageRotateWithView_ = imageStyle.getRotateWithView();\n this.imageRotation_ = imageStyle.getRotation();\n const imageScale = imageStyle.getScaleArray();\n this.imageScale_ = [\n (imageScale[0] * this.pixelRatio_) / imagePixelRatio,\n (imageScale[1] * this.pixelRatio_) / imagePixelRatio,\n ];\n this.imageWidth_ = imageSize[0] * imagePixelRatio;\n }\n\n /**\n * Set the text style for subsequent draw operations. Pass null to\n * remove the text style.\n *\n * @param {import(\"../../style/Text.js\").default} textStyle Text style.\n */\n setTextStyle(textStyle) {\n if (!textStyle) {\n this.text_ = '';\n } else {\n const textFillStyle = textStyle.getFill();\n if (!textFillStyle) {\n this.textFillState_ = null;\n } else {\n const textFillStyleColor = textFillStyle.getColor();\n this.textFillState_ = {\n fillStyle: asColorLike(\n textFillStyleColor ? textFillStyleColor : defaultFillStyle\n ),\n };\n }\n const textStrokeStyle = textStyle.getStroke();\n if (!textStrokeStyle) {\n this.textStrokeState_ = null;\n } else {\n const textStrokeStyleColor = textStrokeStyle.getColor();\n const textStrokeStyleLineCap = textStrokeStyle.getLineCap();\n const textStrokeStyleLineDash = textStrokeStyle.getLineDash();\n const textStrokeStyleLineDashOffset =\n textStrokeStyle.getLineDashOffset();\n const textStrokeStyleLineJoin = textStrokeStyle.getLineJoin();\n const textStrokeStyleWidth = textStrokeStyle.getWidth();\n const textStrokeStyleMiterLimit = textStrokeStyle.getMiterLimit();\n this.textStrokeState_ = {\n lineCap:\n textStrokeStyleLineCap !== undefined\n ? textStrokeStyleLineCap\n : defaultLineCap,\n lineDash: textStrokeStyleLineDash\n ? textStrokeStyleLineDash\n : defaultLineDash,\n lineDashOffset: textStrokeStyleLineDashOffset\n ? textStrokeStyleLineDashOffset\n : defaultLineDashOffset,\n lineJoin:\n textStrokeStyleLineJoin !== undefined\n ? textStrokeStyleLineJoin\n : defaultLineJoin,\n lineWidth:\n textStrokeStyleWidth !== undefined\n ? textStrokeStyleWidth\n : defaultLineWidth,\n miterLimit:\n textStrokeStyleMiterLimit !== undefined\n ? textStrokeStyleMiterLimit\n : defaultMiterLimit,\n strokeStyle: asColorLike(\n textStrokeStyleColor ? textStrokeStyleColor : defaultStrokeStyle\n ),\n };\n }\n const textFont = textStyle.getFont();\n const textOffsetX = textStyle.getOffsetX();\n const textOffsetY = textStyle.getOffsetY();\n const textRotateWithView = textStyle.getRotateWithView();\n const textRotation = textStyle.getRotation();\n const textScale = textStyle.getScaleArray();\n const textText = textStyle.getText();\n const textTextAlign = textStyle.getTextAlign();\n const textTextBaseline = textStyle.getTextBaseline();\n this.textState_ = {\n font: textFont !== undefined ? textFont : defaultFont,\n textAlign:\n textTextAlign !== undefined ? textTextAlign : defaultTextAlign,\n textBaseline:\n textTextBaseline !== undefined\n ? textTextBaseline\n : defaultTextBaseline,\n };\n this.text_ =\n textText !== undefined\n ? Array.isArray(textText)\n ? textText.reduce((acc, t, i) => (acc += i % 2 ? ' ' : t), '')\n : textText\n : '';\n this.textOffsetX_ =\n textOffsetX !== undefined ? this.pixelRatio_ * textOffsetX : 0;\n this.textOffsetY_ =\n textOffsetY !== undefined ? this.pixelRatio_ * textOffsetY : 0;\n this.textRotateWithView_ =\n textRotateWithView !== undefined ? textRotateWithView : false;\n this.textRotation_ = textRotation !== undefined ? textRotation : 0;\n this.textScale_ = [\n this.pixelRatio_ * textScale[0],\n this.pixelRatio_ * textScale[1],\n ];\n }\n }\n}\n\nexport default CanvasImmediateRenderer;\n","/**\n * @module ol/renderer/vector\n */\nimport ImageState from '../ImageState.js';\nimport {getUid} from '../util.js';\n\n/**\n * Feature callback. The callback will be called with three arguments. The first\n * argument is one {@link module:ol/Feature~Feature feature} or {@link module:ol/render/Feature~RenderFeature render feature}\n * at the pixel, the second is the {@link module:ol/layer/Layer~Layer layer} of the feature and will be null for\n * unmanaged layers. The third is the {@link module:ol/geom/SimpleGeometry~SimpleGeometry} of the feature. For features\n * with a GeometryCollection geometry, it will be the first detected geometry from the collection.\n * @template T\n * @typedef {function(import(\"../Feature.js\").FeatureLike, import(\"../layer/Layer.js\").default, import(\"../geom/SimpleGeometry.js\").default): T} FeatureCallback\n */\n\n/**\n * Tolerance for geometry simplification in device pixels.\n * @type {number}\n */\nconst SIMPLIFY_TOLERANCE = 0.5;\n\n/**\n * @const\n * @type {Object}\n */\nconst GEOMETRY_RENDERERS = {\n 'Point': renderPointGeometry,\n 'LineString': renderLineStringGeometry,\n 'Polygon': renderPolygonGeometry,\n 'MultiPoint': renderMultiPointGeometry,\n 'MultiLineString': renderMultiLineStringGeometry,\n 'MultiPolygon': renderMultiPolygonGeometry,\n 'GeometryCollection': renderGeometryCollectionGeometry,\n 'Circle': renderCircleGeometry,\n};\n\n/**\n * @param {import(\"../Feature.js\").FeatureLike} feature1 Feature 1.\n * @param {import(\"../Feature.js\").FeatureLike} feature2 Feature 2.\n * @return {number} Order.\n */\nexport function defaultOrder(feature1, feature2) {\n return parseInt(getUid(feature1), 10) - parseInt(getUid(feature2), 10);\n}\n\n/**\n * @param {number} resolution Resolution.\n * @param {number} pixelRatio Pixel ratio.\n * @return {number} Squared pixel tolerance.\n */\nexport function getSquaredTolerance(resolution, pixelRatio) {\n const tolerance = getTolerance(resolution, pixelRatio);\n return tolerance * tolerance;\n}\n\n/**\n * @param {number} resolution Resolution.\n * @param {number} pixelRatio Pixel ratio.\n * @return {number} Pixel tolerance.\n */\nexport function getTolerance(resolution, pixelRatio) {\n return (SIMPLIFY_TOLERANCE * resolution) / pixelRatio;\n}\n\n/**\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} builderGroup Builder group.\n * @param {import(\"../geom/Circle.js\").default} geometry Geometry.\n * @param {import(\"../style/Style.js\").default} style Style.\n * @param {import(\"../Feature.js\").default} feature Feature.\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} [declutterBuilderGroup] Builder for decluttering.\n */\nfunction renderCircleGeometry(\n builderGroup,\n geometry,\n style,\n feature,\n declutterBuilderGroup\n) {\n const fillStyle = style.getFill();\n const strokeStyle = style.getStroke();\n if (fillStyle || strokeStyle) {\n const circleReplay = builderGroup.getBuilder(style.getZIndex(), 'Circle');\n circleReplay.setFillStrokeStyle(fillStyle, strokeStyle);\n circleReplay.drawCircle(geometry, feature);\n }\n const textStyle = style.getText();\n if (textStyle && textStyle.getText()) {\n const textReplay = (declutterBuilderGroup || builderGroup).getBuilder(\n style.getZIndex(),\n 'Text'\n );\n textReplay.setTextStyle(textStyle);\n textReplay.drawText(geometry, feature);\n }\n}\n\n/**\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} replayGroup Replay group.\n * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n * @param {import(\"../style/Style.js\").default} style Style.\n * @param {number} squaredTolerance Squared tolerance.\n * @param {function(import(\"../events/Event.js\").default): void} listener Listener function.\n * @param {import(\"../proj.js\").TransformFunction} [transform] Transform from user to view projection.\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} [declutterBuilderGroup] Builder for decluttering.\n * @return {boolean} `true` if style is loading.\n */\nexport function renderFeature(\n replayGroup,\n feature,\n style,\n squaredTolerance,\n listener,\n transform,\n declutterBuilderGroup\n) {\n let loading = false;\n const imageStyle = style.getImage();\n if (imageStyle) {\n const imageState = imageStyle.getImageState();\n if (imageState == ImageState.LOADED || imageState == ImageState.ERROR) {\n imageStyle.unlistenImageChange(listener);\n } else {\n if (imageState == ImageState.IDLE) {\n imageStyle.load();\n }\n imageStyle.listenImageChange(listener);\n loading = true;\n }\n }\n renderFeatureInternal(\n replayGroup,\n feature,\n style,\n squaredTolerance,\n transform,\n declutterBuilderGroup\n );\n\n return loading;\n}\n\n/**\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} replayGroup Replay group.\n * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n * @param {import(\"../style/Style.js\").default} style Style.\n * @param {number} squaredTolerance Squared tolerance.\n * @param {import(\"../proj.js\").TransformFunction} [transform] Optional transform function.\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} [declutterBuilderGroup] Builder for decluttering.\n */\nfunction renderFeatureInternal(\n replayGroup,\n feature,\n style,\n squaredTolerance,\n transform,\n declutterBuilderGroup\n) {\n const geometry = style.getGeometryFunction()(feature);\n if (!geometry) {\n return;\n }\n const simplifiedGeometry = geometry.simplifyTransformed(\n squaredTolerance,\n transform\n );\n const renderer = style.getRenderer();\n if (renderer) {\n renderGeometry(replayGroup, simplifiedGeometry, style, feature);\n } else {\n const geometryRenderer = GEOMETRY_RENDERERS[simplifiedGeometry.getType()];\n geometryRenderer(\n replayGroup,\n simplifiedGeometry,\n style,\n feature,\n declutterBuilderGroup\n );\n }\n}\n\n/**\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} replayGroup Replay group.\n * @param {import(\"../geom/Geometry.js\").default|import(\"../render/Feature.js\").default} geometry Geometry.\n * @param {import(\"../style/Style.js\").default} style Style.\n * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n */\nfunction renderGeometry(replayGroup, geometry, style, feature) {\n if (geometry.getType() == 'GeometryCollection') {\n const geometries =\n /** @type {import(\"../geom/GeometryCollection.js\").default} */ (\n geometry\n ).getGeometries();\n for (let i = 0, ii = geometries.length; i < ii; ++i) {\n renderGeometry(replayGroup, geometries[i], style, feature);\n }\n return;\n }\n const replay = replayGroup.getBuilder(style.getZIndex(), 'Default');\n replay.drawCustom(\n /** @type {import(\"../geom/SimpleGeometry.js\").default} */ (geometry),\n feature,\n style.getRenderer(),\n style.getHitDetectionRenderer()\n );\n}\n\n/**\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} replayGroup Replay group.\n * @param {import(\"../geom/GeometryCollection.js\").default} geometry Geometry.\n * @param {import(\"../style/Style.js\").default} style Style.\n * @param {import(\"../Feature.js\").default} feature Feature.\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} [declutterBuilderGroup] Builder for decluttering.\n */\nfunction renderGeometryCollectionGeometry(\n replayGroup,\n geometry,\n style,\n feature,\n declutterBuilderGroup\n) {\n const geometries = geometry.getGeometriesArray();\n let i, ii;\n for (i = 0, ii = geometries.length; i < ii; ++i) {\n const geometryRenderer = GEOMETRY_RENDERERS[geometries[i].getType()];\n geometryRenderer(\n replayGroup,\n geometries[i],\n style,\n feature,\n declutterBuilderGroup\n );\n }\n}\n\n/**\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} builderGroup Replay group.\n * @param {import(\"../geom/LineString.js\").default|import(\"../render/Feature.js\").default} geometry Geometry.\n * @param {import(\"../style/Style.js\").default} style Style.\n * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} [declutterBuilderGroup] Builder for decluttering.\n */\nfunction renderLineStringGeometry(\n builderGroup,\n geometry,\n style,\n feature,\n declutterBuilderGroup\n) {\n const strokeStyle = style.getStroke();\n if (strokeStyle) {\n const lineStringReplay = builderGroup.getBuilder(\n style.getZIndex(),\n 'LineString'\n );\n lineStringReplay.setFillStrokeStyle(null, strokeStyle);\n lineStringReplay.drawLineString(geometry, feature);\n }\n const textStyle = style.getText();\n if (textStyle && textStyle.getText()) {\n const textReplay = (declutterBuilderGroup || builderGroup).getBuilder(\n style.getZIndex(),\n 'Text'\n );\n textReplay.setTextStyle(textStyle);\n textReplay.drawText(geometry, feature);\n }\n}\n\n/**\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} builderGroup Replay group.\n * @param {import(\"../geom/MultiLineString.js\").default|import(\"../render/Feature.js\").default} geometry Geometry.\n * @param {import(\"../style/Style.js\").default} style Style.\n * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} [declutterBuilderGroup] Builder for decluttering.\n */\nfunction renderMultiLineStringGeometry(\n builderGroup,\n geometry,\n style,\n feature,\n declutterBuilderGroup\n) {\n const strokeStyle = style.getStroke();\n if (strokeStyle) {\n const lineStringReplay = builderGroup.getBuilder(\n style.getZIndex(),\n 'LineString'\n );\n lineStringReplay.setFillStrokeStyle(null, strokeStyle);\n lineStringReplay.drawMultiLineString(geometry, feature);\n }\n const textStyle = style.getText();\n if (textStyle && textStyle.getText()) {\n const textReplay = (declutterBuilderGroup || builderGroup).getBuilder(\n style.getZIndex(),\n 'Text'\n );\n textReplay.setTextStyle(textStyle);\n textReplay.drawText(geometry, feature);\n }\n}\n\n/**\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} builderGroup Replay group.\n * @param {import(\"../geom/MultiPolygon.js\").default} geometry Geometry.\n * @param {import(\"../style/Style.js\").default} style Style.\n * @param {import(\"../Feature.js\").default} feature Feature.\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} [declutterBuilderGroup] Builder for decluttering.\n */\nfunction renderMultiPolygonGeometry(\n builderGroup,\n geometry,\n style,\n feature,\n declutterBuilderGroup\n) {\n const fillStyle = style.getFill();\n const strokeStyle = style.getStroke();\n if (strokeStyle || fillStyle) {\n const polygonReplay = builderGroup.getBuilder(style.getZIndex(), 'Polygon');\n polygonReplay.setFillStrokeStyle(fillStyle, strokeStyle);\n polygonReplay.drawMultiPolygon(geometry, feature);\n }\n const textStyle = style.getText();\n if (textStyle && textStyle.getText()) {\n const textReplay = (declutterBuilderGroup || builderGroup).getBuilder(\n style.getZIndex(),\n 'Text'\n );\n textReplay.setTextStyle(textStyle);\n textReplay.drawText(geometry, feature);\n }\n}\n\n/**\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} builderGroup Replay group.\n * @param {import(\"../geom/Point.js\").default|import(\"../render/Feature.js\").default} geometry Geometry.\n * @param {import(\"../style/Style.js\").default} style Style.\n * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} [declutterBuilderGroup] Builder for decluttering.\n */\nfunction renderPointGeometry(\n builderGroup,\n geometry,\n style,\n feature,\n declutterBuilderGroup\n) {\n const imageStyle = style.getImage();\n const textStyle = style.getText();\n /** @type {import(\"../render/canvas.js\").DeclutterImageWithText} */\n let declutterImageWithText;\n if (imageStyle) {\n if (imageStyle.getImageState() != ImageState.LOADED) {\n return;\n }\n let imageBuilderGroup = builderGroup;\n if (declutterBuilderGroup) {\n const declutterMode = imageStyle.getDeclutterMode();\n if (declutterMode !== 'none') {\n imageBuilderGroup = declutterBuilderGroup;\n if (declutterMode === 'obstacle') {\n // draw in non-declutter group:\n const imageReplay = builderGroup.getBuilder(\n style.getZIndex(),\n 'Image'\n );\n imageReplay.setImageStyle(imageStyle, declutterImageWithText);\n imageReplay.drawPoint(geometry, feature);\n } else if (textStyle && textStyle.getText()) {\n declutterImageWithText = {};\n }\n }\n }\n const imageReplay = imageBuilderGroup.getBuilder(\n style.getZIndex(),\n 'Image'\n );\n imageReplay.setImageStyle(imageStyle, declutterImageWithText);\n imageReplay.drawPoint(geometry, feature);\n }\n if (textStyle && textStyle.getText()) {\n let textBuilderGroup = builderGroup;\n if (declutterBuilderGroup) {\n textBuilderGroup = declutterBuilderGroup;\n }\n const textReplay = textBuilderGroup.getBuilder(style.getZIndex(), 'Text');\n textReplay.setTextStyle(textStyle, declutterImageWithText);\n textReplay.drawText(geometry, feature);\n }\n}\n\n/**\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} builderGroup Replay group.\n * @param {import(\"../geom/MultiPoint.js\").default|import(\"../render/Feature.js\").default} geometry Geometry.\n * @param {import(\"../style/Style.js\").default} style Style.\n * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} [declutterBuilderGroup] Builder for decluttering.\n */\nfunction renderMultiPointGeometry(\n builderGroup,\n geometry,\n style,\n feature,\n declutterBuilderGroup\n) {\n const imageStyle = style.getImage();\n const textStyle = style.getText();\n /** @type {import(\"../render/canvas.js\").DeclutterImageWithText} */\n let declutterImageWithText;\n if (imageStyle) {\n if (imageStyle.getImageState() != ImageState.LOADED) {\n return;\n }\n let imageBuilderGroup = builderGroup;\n if (declutterBuilderGroup) {\n const declutterMode = imageStyle.getDeclutterMode();\n if (declutterMode !== 'none') {\n imageBuilderGroup = declutterBuilderGroup;\n if (declutterMode === 'obstacle') {\n // draw in non-declutter group:\n const imageReplay = builderGroup.getBuilder(\n style.getZIndex(),\n 'Image'\n );\n imageReplay.setImageStyle(imageStyle, declutterImageWithText);\n imageReplay.drawMultiPoint(geometry, feature);\n } else if (textStyle && textStyle.getText()) {\n declutterImageWithText = {};\n }\n }\n }\n const imageReplay = imageBuilderGroup.getBuilder(\n style.getZIndex(),\n 'Image'\n );\n imageReplay.setImageStyle(imageStyle, declutterImageWithText);\n imageReplay.drawMultiPoint(geometry, feature);\n }\n if (textStyle && textStyle.getText()) {\n let textBuilderGroup = builderGroup;\n if (declutterBuilderGroup) {\n textBuilderGroup = declutterBuilderGroup;\n }\n const textReplay = textBuilderGroup.getBuilder(style.getZIndex(), 'Text');\n textReplay.setTextStyle(textStyle, declutterImageWithText);\n textReplay.drawText(geometry, feature);\n }\n}\n\n/**\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} builderGroup Replay group.\n * @param {import(\"../geom/Polygon.js\").default|import(\"../render/Feature.js\").default} geometry Geometry.\n * @param {import(\"../style/Style.js\").default} style Style.\n * @param {import(\"../Feature.js\").FeatureLike} feature Feature.\n * @param {import(\"../render/canvas/BuilderGroup.js\").default} [declutterBuilderGroup] Builder for decluttering.\n */\nfunction renderPolygonGeometry(\n builderGroup,\n geometry,\n style,\n feature,\n declutterBuilderGroup\n) {\n const fillStyle = style.getFill();\n const strokeStyle = style.getStroke();\n if (fillStyle || strokeStyle) {\n const polygonReplay = builderGroup.getBuilder(style.getZIndex(), 'Polygon');\n polygonReplay.setFillStrokeStyle(fillStyle, strokeStyle);\n polygonReplay.drawPolygon(geometry, feature);\n }\n const textStyle = style.getText();\n if (textStyle && textStyle.getText()) {\n const textReplay = (declutterBuilderGroup || builderGroup).getBuilder(\n style.getZIndex(),\n 'Text'\n );\n textReplay.setTextStyle(textStyle);\n textReplay.drawText(geometry, feature);\n }\n}\n","/**\n * @module ol/render\n */\nimport CanvasImmediateRenderer from './render/canvas/Immediate.js';\nimport {DEVICE_PIXEL_RATIO} from './has.js';\nimport {\n apply as applyTransform,\n create as createTransform,\n multiply as multiplyTransform,\n scale as scaleTransform,\n} from './transform.js';\nimport {getSquaredTolerance} from './renderer/vector.js';\nimport {getTransformFromProjections, getUserProjection} from './proj.js';\n\n/**\n * @typedef {Object} State\n * @property {CanvasRenderingContext2D} context Canvas context that the layer is being rendered to.\n * @property {import(\"./Feature.js\").FeatureLike} feature Feature.\n * @property {import(\"./geom/SimpleGeometry.js\").default} geometry Geometry.\n * @property {number} pixelRatio Pixel ratio used by the layer renderer.\n * @property {number} resolution Resolution that the render batch was created and optimized for.\n * This is not the view's resolution that is being rendered.\n * @property {number} rotation Rotation of the rendered layer in radians.\n */\n\n/**\n * A function to be used when sorting features before rendering.\n * It takes two instances of {@link module:ol/Feature~Feature} or\n * {@link module:ol/render/Feature~RenderFeature} and returns a `{number}`.\n *\n * @typedef {function(import(\"./Feature.js\").FeatureLike, import(\"./Feature.js\").FeatureLike):number} OrderFunction\n */\n\n/**\n * @typedef {Object} ToContextOptions\n * @property {import(\"./size.js\").Size} [size] Desired size of the canvas in css\n * pixels. When provided, both canvas and css size will be set according to the\n * `pixelRatio`. If not provided, the current canvas and css sizes will not be\n * altered.\n * @property {number} [pixelRatio=window.devicePixelRatio] Pixel ratio (canvas\n * pixel to css pixel ratio) for the canvas.\n */\n\n/**\n * Binds a Canvas Immediate API to a canvas context, to allow drawing geometries\n * to the context's canvas.\n *\n * The units for geometry coordinates are css pixels relative to the top left\n * corner of the canvas element.\n * ```js\n * import {toContext} from 'ol/render.js';\n * import Fill from 'ol/style/Fill.js';\n * import Polygon from 'ol/geom/Polygon.js';\n *\n * const canvas = document.createElement('canvas');\n * const render = toContext(\n * canvas.getContext('2d'),\n * {size: [100, 100]}\n * );\n * render.setFillStrokeStyle(new Fill({ color: blue }));\n * render.drawPolygon(\n * new Polygon([[[0, 0], [100, 100], [100, 0], [0, 0]]])\n * );\n * ```\n *\n * @param {CanvasRenderingContext2D} context Canvas context.\n * @param {ToContextOptions} [options] Options.\n * @return {CanvasImmediateRenderer} Canvas Immediate.\n * @api\n */\nexport function toContext(context, options) {\n const canvas = context.canvas;\n options = options ? options : {};\n const pixelRatio = options.pixelRatio || DEVICE_PIXEL_RATIO;\n const size = options.size;\n if (size) {\n canvas.width = size[0] * pixelRatio;\n canvas.height = size[1] * pixelRatio;\n canvas.style.width = size[0] + 'px';\n canvas.style.height = size[1] + 'px';\n }\n const extent = [0, 0, canvas.width, canvas.height];\n const transform = scaleTransform(createTransform(), pixelRatio, pixelRatio);\n return new CanvasImmediateRenderer(context, pixelRatio, extent, transform, 0);\n}\n\n/**\n * Gets a vector context for drawing to the event's canvas.\n * @param {import(\"./render/Event.js\").default} event Render event.\n * @return {CanvasImmediateRenderer} Vector context.\n * @api\n */\nexport function getVectorContext(event) {\n if (!(event.context instanceof CanvasRenderingContext2D)) {\n throw new Error('Only works for render events from Canvas 2D layers');\n }\n\n // canvas may be at a different pixel ratio than frameState.pixelRatio\n const a = event.inversePixelTransform[0];\n const b = event.inversePixelTransform[1];\n const canvasPixelRatio = Math.sqrt(a * a + b * b);\n const frameState = event.frameState;\n const transform = multiplyTransform(\n event.inversePixelTransform.slice(),\n frameState.coordinateToPixelTransform\n );\n const squaredTolerance = getSquaredTolerance(\n frameState.viewState.resolution,\n canvasPixelRatio\n );\n let userTransform;\n const userProjection = getUserProjection();\n if (userProjection) {\n userTransform = getTransformFromProjections(\n userProjection,\n frameState.viewState.projection\n );\n }\n\n return new CanvasImmediateRenderer(\n event.context,\n canvasPixelRatio,\n frameState.extent,\n transform,\n frameState.viewState.rotation,\n squaredTolerance,\n userTransform\n );\n}\n\n/**\n * Gets the pixel of the event's canvas context from the map viewport's CSS pixel.\n * @param {import(\"./render/Event.js\").default} event Render event.\n * @param {import(\"./pixel.js\").Pixel} pixel CSS pixel relative to the top-left\n * corner of the map viewport.\n * @return {import(\"./pixel.js\").Pixel} Pixel on the event's canvas context.\n * @api\n */\nexport function getRenderPixel(event, pixel) {\n return applyTransform(event.inversePixelTransform, pixel.slice(0));\n}\n","/**\n * @module ol/reproj\n */\nimport {\n containsCoordinate,\n createEmpty,\n extend,\n forEachCorner,\n getCenter,\n getHeight,\n getTopLeft,\n getWidth,\n} from './extent.js';\nimport {createCanvasContext2D, releaseCanvas} from './dom.js';\nimport {getPointResolution, transform} from './proj.js';\nimport {solveLinearSystem} from './math.js';\n\nlet brokenDiagonalRendering_;\n\n/**\n * @type {Array}\n */\nexport const canvasPool = [];\n\n/**\n * This draws a small triangle into a canvas by setting the triangle as the clip region\n * and then drawing a (too large) rectangle\n *\n * @param {CanvasRenderingContext2D} ctx The context in which to draw the triangle\n * @param {number} u1 The x-coordinate of the second point. The first point is 0,0.\n * @param {number} v1 The y-coordinate of the second point.\n * @param {number} u2 The x-coordinate of the third point.\n * @param {number} v2 The y-coordinate of the third point.\n */\nfunction drawTestTriangle(ctx, u1, v1, u2, v2) {\n ctx.beginPath();\n ctx.moveTo(0, 0);\n ctx.lineTo(u1, v1);\n ctx.lineTo(u2, v2);\n ctx.closePath();\n ctx.save();\n ctx.clip();\n ctx.fillRect(0, 0, Math.max(u1, u2) + 1, Math.max(v1, v2));\n ctx.restore();\n}\n\n/**\n * Given the data from getImageData, see if the right values appear at the provided offset.\n * Returns true if either the color or transparency is off\n *\n * @param {Uint8ClampedArray} data The data returned from getImageData\n * @param {number} offset The pixel offset from the start of data.\n * @return {boolean} true if the diagonal rendering is broken\n */\nfunction verifyBrokenDiagonalRendering(data, offset) {\n // the values ought to be close to the rgba(210, 0, 0, 0.75)\n return (\n Math.abs(data[offset * 4] - 210) > 2 ||\n Math.abs(data[offset * 4 + 3] - 0.75 * 255) > 2\n );\n}\n\n/**\n * Determines if the current browser configuration can render triangular clip regions correctly.\n * This value is cached so the function is only expensive the first time called.\n * Firefox on Windows (as of now) does not if HWA is enabled. See https://bugzilla.mozilla.org/show_bug.cgi?id=1606976\n * Chrome works, and everything seems to work on OSX and Android. This function caches the\n * result. I suppose that it is conceivably possible that a browser might flip modes while the app is\n * running, but lets hope not.\n *\n * @return {boolean} true if the Diagonal Rendering is broken.\n */\nfunction isBrokenDiagonalRendering() {\n if (brokenDiagonalRendering_ === undefined) {\n const ctx = createCanvasContext2D(6, 6, canvasPool);\n ctx.globalCompositeOperation = 'lighter';\n ctx.fillStyle = 'rgba(210, 0, 0, 0.75)';\n drawTestTriangle(ctx, 4, 5, 4, 0);\n drawTestTriangle(ctx, 4, 5, 0, 5);\n const data = ctx.getImageData(0, 0, 3, 3).data;\n brokenDiagonalRendering_ =\n verifyBrokenDiagonalRendering(data, 0) ||\n verifyBrokenDiagonalRendering(data, 4) ||\n verifyBrokenDiagonalRendering(data, 8);\n releaseCanvas(ctx);\n canvasPool.push(ctx.canvas);\n }\n\n return brokenDiagonalRendering_;\n}\n\n/**\n * Calculates ideal resolution to use from the source in order to achieve\n * pixel mapping as close as possible to 1:1 during reprojection.\n * The resolution is calculated regardless of what resolutions\n * are actually available in the dataset (TileGrid, Image, ...).\n *\n * @param {import(\"./proj/Projection.js\").default} sourceProj Source projection.\n * @param {import(\"./proj/Projection.js\").default} targetProj Target projection.\n * @param {import(\"./coordinate.js\").Coordinate} targetCenter Target center.\n * @param {number} targetResolution Target resolution.\n * @return {number} The best resolution to use. Can be +-Infinity, NaN or 0.\n */\nexport function calculateSourceResolution(\n sourceProj,\n targetProj,\n targetCenter,\n targetResolution\n) {\n const sourceCenter = transform(targetCenter, targetProj, sourceProj);\n\n // calculate the ideal resolution of the source data\n let sourceResolution = getPointResolution(\n targetProj,\n targetResolution,\n targetCenter\n );\n\n const targetMetersPerUnit = targetProj.getMetersPerUnit();\n if (targetMetersPerUnit !== undefined) {\n sourceResolution *= targetMetersPerUnit;\n }\n const sourceMetersPerUnit = sourceProj.getMetersPerUnit();\n if (sourceMetersPerUnit !== undefined) {\n sourceResolution /= sourceMetersPerUnit;\n }\n\n // Based on the projection properties, the point resolution at the specified\n // coordinates may be slightly different. We need to reverse-compensate this\n // in order to achieve optimal results.\n\n const sourceExtent = sourceProj.getExtent();\n if (!sourceExtent || containsCoordinate(sourceExtent, sourceCenter)) {\n const compensationFactor =\n getPointResolution(sourceProj, sourceResolution, sourceCenter) /\n sourceResolution;\n if (isFinite(compensationFactor) && compensationFactor > 0) {\n sourceResolution /= compensationFactor;\n }\n }\n\n return sourceResolution;\n}\n\n/**\n * Calculates ideal resolution to use from the source in order to achieve\n * pixel mapping as close as possible to 1:1 during reprojection.\n * The resolution is calculated regardless of what resolutions\n * are actually available in the dataset (TileGrid, Image, ...).\n *\n * @param {import(\"./proj/Projection.js\").default} sourceProj Source projection.\n * @param {import(\"./proj/Projection.js\").default} targetProj Target projection.\n * @param {import(\"./extent.js\").Extent} targetExtent Target extent\n * @param {number} targetResolution Target resolution.\n * @return {number} The best resolution to use. Can be +-Infinity, NaN or 0.\n */\nexport function calculateSourceExtentResolution(\n sourceProj,\n targetProj,\n targetExtent,\n targetResolution\n) {\n const targetCenter = getCenter(targetExtent);\n let sourceResolution = calculateSourceResolution(\n sourceProj,\n targetProj,\n targetCenter,\n targetResolution\n );\n\n if (!isFinite(sourceResolution) || sourceResolution <= 0) {\n forEachCorner(targetExtent, function (corner) {\n sourceResolution = calculateSourceResolution(\n sourceProj,\n targetProj,\n corner,\n targetResolution\n );\n return isFinite(sourceResolution) && sourceResolution > 0;\n });\n }\n\n return sourceResolution;\n}\n\n/**\n * @typedef {Object} ImageExtent\n * @property {import(\"./extent.js\").Extent} extent Extent.\n * @property {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} image Image.\n */\n\n/**\n * Renders the source data into new canvas based on the triangulation.\n *\n * @param {number} width Width of the canvas.\n * @param {number} height Height of the canvas.\n * @param {number} pixelRatio Pixel ratio.\n * @param {number} sourceResolution Source resolution.\n * @param {import(\"./extent.js\").Extent} sourceExtent Extent of the data source.\n * @param {number} targetResolution Target resolution.\n * @param {import(\"./extent.js\").Extent} targetExtent Target extent.\n * @param {import(\"./reproj/Triangulation.js\").default} triangulation Calculated triangulation.\n * @param {Array} sources Array of sources.\n * @param {number} gutter Gutter of the sources.\n * @param {boolean} [renderEdges] Render reprojection edges.\n * @param {boolean} [interpolate] Use linear interpolation when resampling.\n * @return {HTMLCanvasElement} Canvas with reprojected data.\n */\nexport function render(\n width,\n height,\n pixelRatio,\n sourceResolution,\n sourceExtent,\n targetResolution,\n targetExtent,\n triangulation,\n sources,\n gutter,\n renderEdges,\n interpolate\n) {\n const context = createCanvasContext2D(\n Math.round(pixelRatio * width),\n Math.round(pixelRatio * height),\n canvasPool\n );\n\n if (!interpolate) {\n context.imageSmoothingEnabled = false;\n }\n\n if (sources.length === 0) {\n return context.canvas;\n }\n\n context.scale(pixelRatio, pixelRatio);\n\n function pixelRound(value) {\n return Math.round(value * pixelRatio) / pixelRatio;\n }\n\n context.globalCompositeOperation = 'lighter';\n\n const sourceDataExtent = createEmpty();\n sources.forEach(function (src, i, arr) {\n extend(sourceDataExtent, src.extent);\n });\n\n const canvasWidthInUnits = getWidth(sourceDataExtent);\n const canvasHeightInUnits = getHeight(sourceDataExtent);\n const stitchContext = createCanvasContext2D(\n Math.round((pixelRatio * canvasWidthInUnits) / sourceResolution),\n Math.round((pixelRatio * canvasHeightInUnits) / sourceResolution),\n canvasPool\n );\n\n if (!interpolate) {\n stitchContext.imageSmoothingEnabled = false;\n }\n\n const stitchScale = pixelRatio / sourceResolution;\n\n sources.forEach(function (src, i, arr) {\n const xPos = src.extent[0] - sourceDataExtent[0];\n const yPos = -(src.extent[3] - sourceDataExtent[3]);\n const srcWidth = getWidth(src.extent);\n const srcHeight = getHeight(src.extent);\n\n // This test should never fail -- but it does. Need to find a fix the upstream condition\n if (src.image.width > 0 && src.image.height > 0) {\n stitchContext.drawImage(\n src.image,\n gutter,\n gutter,\n src.image.width - 2 * gutter,\n src.image.height - 2 * gutter,\n xPos * stitchScale,\n yPos * stitchScale,\n srcWidth * stitchScale,\n srcHeight * stitchScale\n );\n }\n });\n\n const targetTopLeft = getTopLeft(targetExtent);\n\n triangulation.getTriangles().forEach(function (triangle, i, arr) {\n /* Calculate affine transform (src -> dst)\n * Resulting matrix can be used to transform coordinate\n * from `sourceProjection` to destination pixels.\n *\n * To optimize number of context calls and increase numerical stability,\n * we also do the following operations:\n * trans(-topLeftExtentCorner), scale(1 / targetResolution), scale(1, -1)\n * here before solving the linear system so [ui, vi] are pixel coordinates.\n *\n * Src points: xi, yi\n * Dst points: ui, vi\n * Affine coefficients: aij\n *\n * | x0 y0 1 0 0 0 | |a00| |u0|\n * | x1 y1 1 0 0 0 | |a01| |u1|\n * | x2 y2 1 0 0 0 | x |a02| = |u2|\n * | 0 0 0 x0 y0 1 | |a10| |v0|\n * | 0 0 0 x1 y1 1 | |a11| |v1|\n * | 0 0 0 x2 y2 1 | |a12| |v2|\n */\n const source = triangle.source;\n const target = triangle.target;\n let x0 = source[0][0],\n y0 = source[0][1];\n let x1 = source[1][0],\n y1 = source[1][1];\n let x2 = source[2][0],\n y2 = source[2][1];\n // Make sure that everything is on pixel boundaries\n const u0 = pixelRound((target[0][0] - targetTopLeft[0]) / targetResolution);\n const v0 = pixelRound(\n -(target[0][1] - targetTopLeft[1]) / targetResolution\n );\n const u1 = pixelRound((target[1][0] - targetTopLeft[0]) / targetResolution);\n const v1 = pixelRound(\n -(target[1][1] - targetTopLeft[1]) / targetResolution\n );\n const u2 = pixelRound((target[2][0] - targetTopLeft[0]) / targetResolution);\n const v2 = pixelRound(\n -(target[2][1] - targetTopLeft[1]) / targetResolution\n );\n\n // Shift all the source points to improve numerical stability\n // of all the subsequent calculations. The [x0, y0] is used here.\n // This is also used to simplify the linear system.\n const sourceNumericalShiftX = x0;\n const sourceNumericalShiftY = y0;\n x0 = 0;\n y0 = 0;\n x1 -= sourceNumericalShiftX;\n y1 -= sourceNumericalShiftY;\n x2 -= sourceNumericalShiftX;\n y2 -= sourceNumericalShiftY;\n\n const augmentedMatrix = [\n [x1, y1, 0, 0, u1 - u0],\n [x2, y2, 0, 0, u2 - u0],\n [0, 0, x1, y1, v1 - v0],\n [0, 0, x2, y2, v2 - v0],\n ];\n const affineCoefs = solveLinearSystem(augmentedMatrix);\n if (!affineCoefs) {\n return;\n }\n\n context.save();\n context.beginPath();\n\n if (isBrokenDiagonalRendering() || !interpolate) {\n // Make sure that all lines are horizontal or vertical\n context.moveTo(u1, v1);\n // This is the diagonal line. Do it in 4 steps\n const steps = 4;\n const ud = u0 - u1;\n const vd = v0 - v1;\n for (let step = 0; step < steps; step++) {\n // Go horizontally\n context.lineTo(\n u1 + pixelRound(((step + 1) * ud) / steps),\n v1 + pixelRound((step * vd) / (steps - 1))\n );\n // Go vertically\n if (step != steps - 1) {\n context.lineTo(\n u1 + pixelRound(((step + 1) * ud) / steps),\n v1 + pixelRound(((step + 1) * vd) / (steps - 1))\n );\n }\n }\n // We are almost at u0r, v0r\n context.lineTo(u2, v2);\n } else {\n context.moveTo(u1, v1);\n context.lineTo(u0, v0);\n context.lineTo(u2, v2);\n }\n\n context.clip();\n\n context.transform(\n affineCoefs[0],\n affineCoefs[2],\n affineCoefs[1],\n affineCoefs[3],\n u0,\n v0\n );\n\n context.translate(\n sourceDataExtent[0] - sourceNumericalShiftX,\n sourceDataExtent[3] - sourceNumericalShiftY\n );\n\n context.scale(\n sourceResolution / pixelRatio,\n -sourceResolution / pixelRatio\n );\n\n context.drawImage(stitchContext.canvas, 0, 0);\n context.restore();\n });\n\n releaseCanvas(stitchContext);\n canvasPool.push(stitchContext.canvas);\n\n if (renderEdges) {\n context.save();\n\n context.globalCompositeOperation = 'source-over';\n context.strokeStyle = 'black';\n context.lineWidth = 1;\n\n triangulation.getTriangles().forEach(function (triangle, i, arr) {\n const target = triangle.target;\n const u0 = (target[0][0] - targetTopLeft[0]) / targetResolution;\n const v0 = -(target[0][1] - targetTopLeft[1]) / targetResolution;\n const u1 = (target[1][0] - targetTopLeft[0]) / targetResolution;\n const v1 = -(target[1][1] - targetTopLeft[1]) / targetResolution;\n const u2 = (target[2][0] - targetTopLeft[0]) / targetResolution;\n const v2 = -(target[2][1] - targetTopLeft[1]) / targetResolution;\n\n context.beginPath();\n context.moveTo(u1, v1);\n context.lineTo(u0, v0);\n context.lineTo(u2, v2);\n context.closePath();\n context.stroke();\n });\n\n context.restore();\n }\n return context.canvas;\n}\n","/**\n * @module ol/reproj/common\n */\n\n/**\n * Default maximum allowed threshold (in pixels) for reprojection\n * triangulation.\n * @type {number}\n */\nexport const ERROR_THRESHOLD = 0.5;\n","/**\n * @module ol/reproj/Triangulation\n */\nimport {\n boundingExtent,\n createEmpty,\n extendCoordinate,\n getArea,\n getBottomLeft,\n getBottomRight,\n getTopLeft,\n getTopRight,\n getWidth,\n intersects,\n} from '../extent.js';\nimport {getTransform} from '../proj.js';\nimport {modulo} from '../math.js';\n\n/**\n * Single triangle; consists of 3 source points and 3 target points.\n * @typedef {Object} Triangle\n * @property {Array} source Source.\n * @property {Array} target Target.\n */\n\n/**\n * Maximum number of subdivision steps during raster reprojection triangulation.\n * Prevents high memory usage and large number of proj4 calls (for certain\n * transformations and areas). At most `2*(2^this)` triangles are created for\n * each triangulated extent (tile/image).\n * @type {number}\n */\nconst MAX_SUBDIVISION = 10;\n\n/**\n * Maximum allowed size of triangle relative to world width. When transforming\n * corners of world extent between certain projections, the resulting\n * triangulation seems to have zero error and no subdivision is performed. If\n * the triangle width is more than this (relative to world width; 0-1),\n * subdivison is forced (up to `MAX_SUBDIVISION`). Default is `0.25`.\n * @type {number}\n */\nconst MAX_TRIANGLE_WIDTH = 0.25;\n\n/**\n * @classdesc\n * Class containing triangulation of the given target extent.\n * Used for determining source data and the reprojection itself.\n */\nclass Triangulation {\n /**\n * @param {import(\"../proj/Projection.js\").default} sourceProj Source projection.\n * @param {import(\"../proj/Projection.js\").default} targetProj Target projection.\n * @param {import(\"../extent.js\").Extent} targetExtent Target extent to triangulate.\n * @param {import(\"../extent.js\").Extent} maxSourceExtent Maximal source extent that can be used.\n * @param {number} errorThreshold Acceptable error (in source units).\n * @param {?number} destinationResolution The (optional) resolution of the destination.\n */\n constructor(\n sourceProj,\n targetProj,\n targetExtent,\n maxSourceExtent,\n errorThreshold,\n destinationResolution\n ) {\n /**\n * @type {import(\"../proj/Projection.js\").default}\n * @private\n */\n this.sourceProj_ = sourceProj;\n\n /**\n * @type {import(\"../proj/Projection.js\").default}\n * @private\n */\n this.targetProj_ = targetProj;\n\n /** @type {!Object} */\n let transformInvCache = {};\n const transformInv = getTransform(this.targetProj_, this.sourceProj_);\n\n /**\n * @param {import(\"../coordinate.js\").Coordinate} c A coordinate.\n * @return {import(\"../coordinate.js\").Coordinate} Transformed coordinate.\n * @private\n */\n this.transformInv_ = function (c) {\n const key = c[0] + '/' + c[1];\n if (!transformInvCache[key]) {\n transformInvCache[key] = transformInv(c);\n }\n return transformInvCache[key];\n };\n\n /**\n * @type {import(\"../extent.js\").Extent}\n * @private\n */\n this.maxSourceExtent_ = maxSourceExtent;\n\n /**\n * @type {number}\n * @private\n */\n this.errorThresholdSquared_ = errorThreshold * errorThreshold;\n\n /**\n * @type {Array}\n * @private\n */\n this.triangles_ = [];\n\n /**\n * Indicates that the triangulation crosses edge of the source projection.\n * @type {boolean}\n * @private\n */\n this.wrapsXInSource_ = false;\n\n /**\n * @type {boolean}\n * @private\n */\n this.canWrapXInSource_ =\n this.sourceProj_.canWrapX() &&\n !!maxSourceExtent &&\n !!this.sourceProj_.getExtent() &&\n getWidth(maxSourceExtent) >= getWidth(this.sourceProj_.getExtent());\n\n /**\n * @type {?number}\n * @private\n */\n this.sourceWorldWidth_ = this.sourceProj_.getExtent()\n ? getWidth(this.sourceProj_.getExtent())\n : null;\n\n /**\n * @type {?number}\n * @private\n */\n this.targetWorldWidth_ = this.targetProj_.getExtent()\n ? getWidth(this.targetProj_.getExtent())\n : null;\n\n const destinationTopLeft = getTopLeft(targetExtent);\n const destinationTopRight = getTopRight(targetExtent);\n const destinationBottomRight = getBottomRight(targetExtent);\n const destinationBottomLeft = getBottomLeft(targetExtent);\n const sourceTopLeft = this.transformInv_(destinationTopLeft);\n const sourceTopRight = this.transformInv_(destinationTopRight);\n const sourceBottomRight = this.transformInv_(destinationBottomRight);\n const sourceBottomLeft = this.transformInv_(destinationBottomLeft);\n\n /*\n * The maxSubdivision controls how many splittings of the target area can\n * be done. The idea here is to do a linear mapping of the target areas\n * but the actual overall reprojection (can be) extremely non-linear. The\n * default value of MAX_SUBDIVISION was chosen based on mapping a 256x256\n * tile size. However this function is also called to remap canvas rendered\n * layers which can be much larger. This calculation increases the maxSubdivision\n * value by the right factor so that each 256x256 pixel area has\n * MAX_SUBDIVISION divisions.\n */\n const maxSubdivision =\n MAX_SUBDIVISION +\n (destinationResolution\n ? Math.max(\n 0,\n Math.ceil(\n Math.log2(\n getArea(targetExtent) /\n (destinationResolution * destinationResolution * 256 * 256)\n )\n )\n )\n : 0);\n\n this.addQuad_(\n destinationTopLeft,\n destinationTopRight,\n destinationBottomRight,\n destinationBottomLeft,\n sourceTopLeft,\n sourceTopRight,\n sourceBottomRight,\n sourceBottomLeft,\n maxSubdivision\n );\n\n if (this.wrapsXInSource_) {\n let leftBound = Infinity;\n this.triangles_.forEach(function (triangle, i, arr) {\n leftBound = Math.min(\n leftBound,\n triangle.source[0][0],\n triangle.source[1][0],\n triangle.source[2][0]\n );\n });\n\n // Shift triangles to be as close to `leftBound` as possible\n // (if the distance is more than `worldWidth / 2` it can be closer.\n this.triangles_.forEach((triangle) => {\n if (\n Math.max(\n triangle.source[0][0],\n triangle.source[1][0],\n triangle.source[2][0]\n ) -\n leftBound >\n this.sourceWorldWidth_ / 2\n ) {\n const newTriangle = [\n [triangle.source[0][0], triangle.source[0][1]],\n [triangle.source[1][0], triangle.source[1][1]],\n [triangle.source[2][0], triangle.source[2][1]],\n ];\n if (newTriangle[0][0] - leftBound > this.sourceWorldWidth_ / 2) {\n newTriangle[0][0] -= this.sourceWorldWidth_;\n }\n if (newTriangle[1][0] - leftBound > this.sourceWorldWidth_ / 2) {\n newTriangle[1][0] -= this.sourceWorldWidth_;\n }\n if (newTriangle[2][0] - leftBound > this.sourceWorldWidth_ / 2) {\n newTriangle[2][0] -= this.sourceWorldWidth_;\n }\n\n // Rarely (if the extent contains both the dateline and prime meridian)\n // the shift can in turn break some triangles.\n // Detect this here and don't shift in such cases.\n const minX = Math.min(\n newTriangle[0][0],\n newTriangle[1][0],\n newTriangle[2][0]\n );\n const maxX = Math.max(\n newTriangle[0][0],\n newTriangle[1][0],\n newTriangle[2][0]\n );\n if (maxX - minX < this.sourceWorldWidth_ / 2) {\n triangle.source = newTriangle;\n }\n }\n });\n }\n\n transformInvCache = {};\n }\n\n /**\n * Adds triangle to the triangulation.\n * @param {import(\"../coordinate.js\").Coordinate} a The target a coordinate.\n * @param {import(\"../coordinate.js\").Coordinate} b The target b coordinate.\n * @param {import(\"../coordinate.js\").Coordinate} c The target c coordinate.\n * @param {import(\"../coordinate.js\").Coordinate} aSrc The source a coordinate.\n * @param {import(\"../coordinate.js\").Coordinate} bSrc The source b coordinate.\n * @param {import(\"../coordinate.js\").Coordinate} cSrc The source c coordinate.\n * @private\n */\n addTriangle_(a, b, c, aSrc, bSrc, cSrc) {\n this.triangles_.push({\n source: [aSrc, bSrc, cSrc],\n target: [a, b, c],\n });\n }\n\n /**\n * Adds quad (points in clock-wise order) to the triangulation\n * (and reprojects the vertices) if valid.\n * Performs quad subdivision if needed to increase precision.\n *\n * @param {import(\"../coordinate.js\").Coordinate} a The target a coordinate.\n * @param {import(\"../coordinate.js\").Coordinate} b The target b coordinate.\n * @param {import(\"../coordinate.js\").Coordinate} c The target c coordinate.\n * @param {import(\"../coordinate.js\").Coordinate} d The target d coordinate.\n * @param {import(\"../coordinate.js\").Coordinate} aSrc The source a coordinate.\n * @param {import(\"../coordinate.js\").Coordinate} bSrc The source b coordinate.\n * @param {import(\"../coordinate.js\").Coordinate} cSrc The source c coordinate.\n * @param {import(\"../coordinate.js\").Coordinate} dSrc The source d coordinate.\n * @param {number} maxSubdivision Maximal allowed subdivision of the quad.\n * @private\n */\n addQuad_(a, b, c, d, aSrc, bSrc, cSrc, dSrc, maxSubdivision) {\n const sourceQuadExtent = boundingExtent([aSrc, bSrc, cSrc, dSrc]);\n const sourceCoverageX = this.sourceWorldWidth_\n ? getWidth(sourceQuadExtent) / this.sourceWorldWidth_\n : null;\n const sourceWorldWidth = /** @type {number} */ (this.sourceWorldWidth_);\n\n // when the quad is wrapped in the source projection\n // it covers most of the projection extent, but not fully\n const wrapsX =\n this.sourceProj_.canWrapX() &&\n sourceCoverageX > 0.5 &&\n sourceCoverageX < 1;\n\n let needsSubdivision = false;\n\n if (maxSubdivision > 0) {\n if (this.targetProj_.isGlobal() && this.targetWorldWidth_) {\n const targetQuadExtent = boundingExtent([a, b, c, d]);\n const targetCoverageX =\n getWidth(targetQuadExtent) / this.targetWorldWidth_;\n needsSubdivision =\n targetCoverageX > MAX_TRIANGLE_WIDTH || needsSubdivision;\n }\n if (!wrapsX && this.sourceProj_.isGlobal() && sourceCoverageX) {\n needsSubdivision =\n sourceCoverageX > MAX_TRIANGLE_WIDTH || needsSubdivision;\n }\n }\n\n if (!needsSubdivision && this.maxSourceExtent_) {\n if (\n isFinite(sourceQuadExtent[0]) &&\n isFinite(sourceQuadExtent[1]) &&\n isFinite(sourceQuadExtent[2]) &&\n isFinite(sourceQuadExtent[3])\n ) {\n if (!intersects(sourceQuadExtent, this.maxSourceExtent_)) {\n // whole quad outside source projection extent -> ignore\n return;\n }\n }\n }\n\n let isNotFinite = 0;\n\n if (!needsSubdivision) {\n if (\n !isFinite(aSrc[0]) ||\n !isFinite(aSrc[1]) ||\n !isFinite(bSrc[0]) ||\n !isFinite(bSrc[1]) ||\n !isFinite(cSrc[0]) ||\n !isFinite(cSrc[1]) ||\n !isFinite(dSrc[0]) ||\n !isFinite(dSrc[1])\n ) {\n if (maxSubdivision > 0) {\n needsSubdivision = true;\n } else {\n // It might be the case that only 1 of the points is infinite. In this case\n // we can draw a single triangle with the other three points\n isNotFinite =\n (!isFinite(aSrc[0]) || !isFinite(aSrc[1]) ? 8 : 0) +\n (!isFinite(bSrc[0]) || !isFinite(bSrc[1]) ? 4 : 0) +\n (!isFinite(cSrc[0]) || !isFinite(cSrc[1]) ? 2 : 0) +\n (!isFinite(dSrc[0]) || !isFinite(dSrc[1]) ? 1 : 0);\n if (\n isNotFinite != 1 &&\n isNotFinite != 2 &&\n isNotFinite != 4 &&\n isNotFinite != 8\n ) {\n return;\n }\n }\n }\n }\n\n if (maxSubdivision > 0) {\n if (!needsSubdivision) {\n const center = [(a[0] + c[0]) / 2, (a[1] + c[1]) / 2];\n const centerSrc = this.transformInv_(center);\n\n let dx;\n if (wrapsX) {\n const centerSrcEstimX =\n (modulo(aSrc[0], sourceWorldWidth) +\n modulo(cSrc[0], sourceWorldWidth)) /\n 2;\n dx = centerSrcEstimX - modulo(centerSrc[0], sourceWorldWidth);\n } else {\n dx = (aSrc[0] + cSrc[0]) / 2 - centerSrc[0];\n }\n const dy = (aSrc[1] + cSrc[1]) / 2 - centerSrc[1];\n const centerSrcErrorSquared = dx * dx + dy * dy;\n needsSubdivision = centerSrcErrorSquared > this.errorThresholdSquared_;\n }\n if (needsSubdivision) {\n if (Math.abs(a[0] - c[0]) <= Math.abs(a[1] - c[1])) {\n // split horizontally (top & bottom)\n const bc = [(b[0] + c[0]) / 2, (b[1] + c[1]) / 2];\n const bcSrc = this.transformInv_(bc);\n const da = [(d[0] + a[0]) / 2, (d[1] + a[1]) / 2];\n const daSrc = this.transformInv_(da);\n\n this.addQuad_(\n a,\n b,\n bc,\n da,\n aSrc,\n bSrc,\n bcSrc,\n daSrc,\n maxSubdivision - 1\n );\n this.addQuad_(\n da,\n bc,\n c,\n d,\n daSrc,\n bcSrc,\n cSrc,\n dSrc,\n maxSubdivision - 1\n );\n } else {\n // split vertically (left & right)\n const ab = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];\n const abSrc = this.transformInv_(ab);\n const cd = [(c[0] + d[0]) / 2, (c[1] + d[1]) / 2];\n const cdSrc = this.transformInv_(cd);\n\n this.addQuad_(\n a,\n ab,\n cd,\n d,\n aSrc,\n abSrc,\n cdSrc,\n dSrc,\n maxSubdivision - 1\n );\n this.addQuad_(\n ab,\n b,\n c,\n cd,\n abSrc,\n bSrc,\n cSrc,\n cdSrc,\n maxSubdivision - 1\n );\n }\n return;\n }\n }\n\n if (wrapsX) {\n if (!this.canWrapXInSource_) {\n return;\n }\n this.wrapsXInSource_ = true;\n }\n\n // Exactly zero or one of *Src is not finite\n // The triangles must have the diagonal line as the first side\n // This is to allow easy code in reproj.s to make it straight for broken\n // browsers that can't handle diagonal clipping\n if ((isNotFinite & 0xb) == 0) {\n this.addTriangle_(a, c, d, aSrc, cSrc, dSrc);\n }\n if ((isNotFinite & 0xe) == 0) {\n this.addTriangle_(a, c, b, aSrc, cSrc, bSrc);\n }\n if (isNotFinite) {\n // Try the other two triangles\n if ((isNotFinite & 0xd) == 0) {\n this.addTriangle_(b, d, a, bSrc, dSrc, aSrc);\n }\n if ((isNotFinite & 0x7) == 0) {\n this.addTriangle_(b, d, c, bSrc, dSrc, cSrc);\n }\n }\n }\n\n /**\n * Calculates extent of the `source` coordinates from all the triangles.\n *\n * @return {import(\"../extent.js\").Extent} Calculated extent.\n */\n calculateSourceExtent() {\n const extent = createEmpty();\n\n this.triangles_.forEach(function (triangle, i, arr) {\n const src = triangle.source;\n extendCoordinate(extent, src[0]);\n extendCoordinate(extent, src[1]);\n extendCoordinate(extent, src[2]);\n });\n\n return extent;\n }\n\n /**\n * @return {Array} Array of the calculated triangles.\n */\n getTriangles() {\n return this.triangles_;\n }\n}\n\nexport default Triangulation;\n","/**\n * @module ol/reproj/Tile\n */\nimport {ERROR_THRESHOLD} from './common.js';\n\nimport EventType from '../events/EventType.js';\nimport Tile from '../Tile.js';\nimport TileState from '../TileState.js';\nimport Triangulation from './Triangulation.js';\nimport {\n calculateSourceExtentResolution,\n canvasPool,\n render as renderReprojected,\n} from '../reproj.js';\nimport {clamp} from '../math.js';\nimport {getArea, getIntersection} from '../extent.js';\nimport {listen, unlistenByKey} from '../events.js';\nimport {releaseCanvas} from '../dom.js';\n\n/**\n * @typedef {function(number, number, number, number) : (import(\"../ImageTile.js\").default)} FunctionType\n */\n\n/**\n * @classdesc\n * Class encapsulating single reprojected tile.\n * See {@link module:ol/source/TileImage~TileImage}.\n *\n */\nclass ReprojTile extends Tile {\n /**\n * @param {import(\"../proj/Projection.js\").default} sourceProj Source projection.\n * @param {import(\"../tilegrid/TileGrid.js\").default} sourceTileGrid Source tile grid.\n * @param {import(\"../proj/Projection.js\").default} targetProj Target projection.\n * @param {import(\"../tilegrid/TileGrid.js\").default} targetTileGrid Target tile grid.\n * @param {import(\"../tilecoord.js\").TileCoord} tileCoord Coordinate of the tile.\n * @param {import(\"../tilecoord.js\").TileCoord} wrappedTileCoord Coordinate of the tile wrapped in X.\n * @param {number} pixelRatio Pixel ratio.\n * @param {number} gutter Gutter of the source tiles.\n * @param {FunctionType} getTileFunction\n * Function returning source tiles (z, x, y, pixelRatio).\n * @param {number} [errorThreshold] Acceptable reprojection error (in px).\n * @param {boolean} [renderEdges] Render reprojection edges.\n * @param {boolean} [interpolate] Use linear interpolation when resampling.\n */\n constructor(\n sourceProj,\n sourceTileGrid,\n targetProj,\n targetTileGrid,\n tileCoord,\n wrappedTileCoord,\n pixelRatio,\n gutter,\n getTileFunction,\n errorThreshold,\n renderEdges,\n interpolate\n ) {\n super(tileCoord, TileState.IDLE, {interpolate: !!interpolate});\n\n /**\n * @private\n * @type {boolean}\n */\n this.renderEdges_ = renderEdges !== undefined ? renderEdges : false;\n\n /**\n * @private\n * @type {number}\n */\n this.pixelRatio_ = pixelRatio;\n\n /**\n * @private\n * @type {number}\n */\n this.gutter_ = gutter;\n\n /**\n * @private\n * @type {HTMLCanvasElement}\n */\n this.canvas_ = null;\n\n /**\n * @private\n * @type {import(\"../tilegrid/TileGrid.js\").default}\n */\n this.sourceTileGrid_ = sourceTileGrid;\n\n /**\n * @private\n * @type {import(\"../tilegrid/TileGrid.js\").default}\n */\n this.targetTileGrid_ = targetTileGrid;\n\n /**\n * @private\n * @type {import(\"../tilecoord.js\").TileCoord}\n */\n this.wrappedTileCoord_ = wrappedTileCoord ? wrappedTileCoord : tileCoord;\n\n /**\n * @private\n * @type {!Array}\n */\n this.sourceTiles_ = [];\n\n /**\n * @private\n * @type {?Array}\n */\n this.sourcesListenerKeys_ = null;\n\n /**\n * @private\n * @type {number}\n */\n this.sourceZ_ = 0;\n\n const targetExtent = targetTileGrid.getTileCoordExtent(\n this.wrappedTileCoord_\n );\n const maxTargetExtent = this.targetTileGrid_.getExtent();\n let maxSourceExtent = this.sourceTileGrid_.getExtent();\n\n const limitedTargetExtent = maxTargetExtent\n ? getIntersection(targetExtent, maxTargetExtent)\n : targetExtent;\n\n if (getArea(limitedTargetExtent) === 0) {\n // Tile is completely outside range -> EMPTY\n // TODO: is it actually correct that the source even creates the tile ?\n this.state = TileState.EMPTY;\n return;\n }\n\n const sourceProjExtent = sourceProj.getExtent();\n if (sourceProjExtent) {\n if (!maxSourceExtent) {\n maxSourceExtent = sourceProjExtent;\n } else {\n maxSourceExtent = getIntersection(maxSourceExtent, sourceProjExtent);\n }\n }\n\n const targetResolution = targetTileGrid.getResolution(\n this.wrappedTileCoord_[0]\n );\n\n const sourceResolution = calculateSourceExtentResolution(\n sourceProj,\n targetProj,\n limitedTargetExtent,\n targetResolution\n );\n\n if (!isFinite(sourceResolution) || sourceResolution <= 0) {\n // invalid sourceResolution -> EMPTY\n // probably edges of the projections when no extent is defined\n this.state = TileState.EMPTY;\n return;\n }\n\n const errorThresholdInPixels =\n errorThreshold !== undefined ? errorThreshold : ERROR_THRESHOLD;\n\n /**\n * @private\n * @type {!import(\"./Triangulation.js\").default}\n */\n this.triangulation_ = new Triangulation(\n sourceProj,\n targetProj,\n limitedTargetExtent,\n maxSourceExtent,\n sourceResolution * errorThresholdInPixels,\n targetResolution\n );\n\n if (this.triangulation_.getTriangles().length === 0) {\n // no valid triangles -> EMPTY\n this.state = TileState.EMPTY;\n return;\n }\n\n this.sourceZ_ = sourceTileGrid.getZForResolution(sourceResolution);\n let sourceExtent = this.triangulation_.calculateSourceExtent();\n\n if (maxSourceExtent) {\n if (sourceProj.canWrapX()) {\n sourceExtent[1] = clamp(\n sourceExtent[1],\n maxSourceExtent[1],\n maxSourceExtent[3]\n );\n sourceExtent[3] = clamp(\n sourceExtent[3],\n maxSourceExtent[1],\n maxSourceExtent[3]\n );\n } else {\n sourceExtent = getIntersection(sourceExtent, maxSourceExtent);\n }\n }\n\n if (!getArea(sourceExtent)) {\n this.state = TileState.EMPTY;\n } else {\n const sourceRange = sourceTileGrid.getTileRangeForExtentAndZ(\n sourceExtent,\n this.sourceZ_\n );\n\n for (let srcX = sourceRange.minX; srcX <= sourceRange.maxX; srcX++) {\n for (let srcY = sourceRange.minY; srcY <= sourceRange.maxY; srcY++) {\n const tile = getTileFunction(this.sourceZ_, srcX, srcY, pixelRatio);\n if (tile) {\n this.sourceTiles_.push(tile);\n }\n }\n }\n\n if (this.sourceTiles_.length === 0) {\n this.state = TileState.EMPTY;\n }\n }\n }\n\n /**\n * Get the HTML Canvas element for this tile.\n * @return {HTMLCanvasElement} Canvas.\n */\n getImage() {\n return this.canvas_;\n }\n\n /**\n * @private\n */\n reproject_() {\n const sources = [];\n this.sourceTiles_.forEach((tile) => {\n if (tile && tile.getState() == TileState.LOADED) {\n sources.push({\n extent: this.sourceTileGrid_.getTileCoordExtent(tile.tileCoord),\n image: tile.getImage(),\n });\n }\n });\n this.sourceTiles_.length = 0;\n\n if (sources.length === 0) {\n this.state = TileState.ERROR;\n } else {\n const z = this.wrappedTileCoord_[0];\n const size = this.targetTileGrid_.getTileSize(z);\n const width = typeof size === 'number' ? size : size[0];\n const height = typeof size === 'number' ? size : size[1];\n const targetResolution = this.targetTileGrid_.getResolution(z);\n const sourceResolution = this.sourceTileGrid_.getResolution(\n this.sourceZ_\n );\n\n const targetExtent = this.targetTileGrid_.getTileCoordExtent(\n this.wrappedTileCoord_\n );\n\n this.canvas_ = renderReprojected(\n width,\n height,\n this.pixelRatio_,\n sourceResolution,\n this.sourceTileGrid_.getExtent(),\n targetResolution,\n targetExtent,\n this.triangulation_,\n sources,\n this.gutter_,\n this.renderEdges_,\n this.interpolate\n );\n\n this.state = TileState.LOADED;\n }\n this.changed();\n }\n\n /**\n * Load not yet loaded URI.\n */\n load() {\n if (this.state == TileState.IDLE) {\n this.state = TileState.LOADING;\n this.changed();\n\n let leftToLoad = 0;\n\n this.sourcesListenerKeys_ = [];\n this.sourceTiles_.forEach((tile) => {\n const state = tile.getState();\n if (state == TileState.IDLE || state == TileState.LOADING) {\n leftToLoad++;\n\n const sourceListenKey = listen(\n tile,\n EventType.CHANGE,\n function (e) {\n const state = tile.getState();\n if (\n state == TileState.LOADED ||\n state == TileState.ERROR ||\n state == TileState.EMPTY\n ) {\n unlistenByKey(sourceListenKey);\n leftToLoad--;\n if (leftToLoad === 0) {\n this.unlistenSources_();\n this.reproject_();\n }\n }\n },\n this\n );\n this.sourcesListenerKeys_.push(sourceListenKey);\n }\n });\n\n if (leftToLoad === 0) {\n setTimeout(this.reproject_.bind(this), 0);\n } else {\n this.sourceTiles_.forEach(function (tile, i, arr) {\n const state = tile.getState();\n if (state == TileState.IDLE) {\n tile.load();\n }\n });\n }\n }\n }\n\n /**\n * @private\n */\n unlistenSources_() {\n this.sourcesListenerKeys_.forEach(unlistenByKey);\n this.sourcesListenerKeys_ = null;\n }\n\n /**\n * Remove from the cache due to expiry\n */\n release() {\n if (this.canvas_) {\n releaseCanvas(this.canvas_.getContext('2d'));\n canvasPool.push(this.canvas_);\n this.canvas_ = null;\n }\n super.release();\n }\n}\n\nexport default ReprojTile;\n","/**\n * @module ol/source/TileEventType\n */\n\n/**\n * @enum {string}\n */\nexport default {\n /**\n * Triggered when a tile starts loading.\n * @event module:ol/source/Tile.TileSourceEvent#tileloadstart\n * @api\n */\n TILELOADSTART: 'tileloadstart',\n\n /**\n * Triggered when a tile finishes loading, either when its data is loaded,\n * or when loading was aborted because the tile is no longer needed.\n * @event module:ol/source/Tile.TileSourceEvent#tileloadend\n * @api\n */\n TILELOADEND: 'tileloadend',\n\n /**\n * Triggered if tile loading results in an error. Note that this is not the\n * right place to re-fetch tiles. See {@link module:ol/ImageTile~ImageTile#load}\n * for details.\n * @event module:ol/source/Tile.TileSourceEvent#tileloaderror\n * @api\n */\n TILELOADERROR: 'tileloaderror',\n};\n\n/**\n * @typedef {'tileloadstart'|'tileloadend'|'tileloaderror'} TileSourceEventTypes\n */\n","/**\n * @module ol/source/Source\n */\nimport BaseObject from '../Object.js';\nimport {get as getProjection} from '../proj.js';\n\n/**\n * @typedef {'undefined' | 'loading' | 'ready' | 'error'} State\n * State of the source, one of 'undefined', 'loading', 'ready' or 'error'.\n */\n\n/**\n * A function that takes a {@link import(\"../View.js\").ViewStateLayerStateExtent} and returns a string or\n * an array of strings representing source attributions.\n *\n * @typedef {function(import(\"../View.js\").ViewStateLayerStateExtent): (string|Array)} Attribution\n */\n\n/**\n * A type that can be used to provide attribution information for data sources.\n *\n * It represents either\n * * a simple string (e.g. `'© Acme Inc.'`)\n * * an array of simple strings (e.g. `['© Acme Inc.', '© Bacme Inc.']`)\n * * a function that returns a string or array of strings ({@link module:ol/source/Source~Attribution})\n *\n * @typedef {string|Array|Attribution} AttributionLike\n */\n\n/**\n * @typedef {Object} Options\n * @property {AttributionLike} [attributions] Attributions.\n * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.\n * @property {import(\"../proj.js\").ProjectionLike} [projection] Projection. Default is the view projection.\n * @property {import(\"./Source.js\").State} [state='ready'] State.\n * @property {boolean} [wrapX=false] WrapX.\n * @property {boolean} [interpolate=false] Use interpolated values when resampling. By default,\n * the nearest neighbor is used when resampling.\n */\n\n/**\n * @classdesc\n * Abstract base class; normally only used for creating subclasses and not\n * instantiated in apps.\n * Base class for {@link module:ol/layer/Layer~Layer} sources.\n *\n * A generic `change` event is triggered when the state of the source changes.\n * @abstract\n * @api\n */\nclass Source extends BaseObject {\n /**\n * @param {Options} options Source options.\n */\n constructor(options) {\n super();\n\n /**\n * @protected\n * @type {import(\"../proj/Projection.js\").default|null}\n */\n this.projection = getProjection(options.projection);\n\n /**\n * @private\n * @type {?Attribution}\n */\n this.attributions_ = adaptAttributions(options.attributions);\n\n /**\n * @private\n * @type {boolean}\n */\n this.attributionsCollapsible_ =\n options.attributionsCollapsible !== undefined\n ? options.attributionsCollapsible\n : true;\n\n /**\n * This source is currently loading data. Sources that defer loading to the\n * map's tile queue never set this to `true`.\n * @type {boolean}\n */\n this.loading = false;\n\n /**\n * @private\n * @type {import(\"./Source.js\").State}\n */\n this.state_ = options.state !== undefined ? options.state : 'ready';\n\n /**\n * @private\n * @type {boolean}\n */\n this.wrapX_ = options.wrapX !== undefined ? options.wrapX : false;\n\n /**\n * @private\n * @type {boolean}\n */\n this.interpolate_ = !!options.interpolate;\n\n /**\n * @protected\n * @type {function(import(\"../View.js\").ViewOptions):void}\n */\n this.viewResolver = null;\n\n /**\n * @protected\n * @type {function(Error):void}\n */\n this.viewRejector = null;\n\n const self = this;\n /**\n * @private\n * @type {Promise}\n */\n this.viewPromise_ = new Promise(function (resolve, reject) {\n self.viewResolver = resolve;\n self.viewRejector = reject;\n });\n }\n\n /**\n * Get the attribution function for the source.\n * @return {?Attribution} Attribution function.\n * @api\n */\n getAttributions() {\n return this.attributions_;\n }\n\n /**\n * @return {boolean} Attributions are collapsible.\n * @api\n */\n getAttributionsCollapsible() {\n return this.attributionsCollapsible_;\n }\n\n /**\n * Get the projection of the source.\n * @return {import(\"../proj/Projection.js\").default|null} Projection.\n * @api\n */\n getProjection() {\n return this.projection;\n }\n\n /**\n * @param {import(\"../proj/Projection\").default} [projection] Projection.\n * @return {Array|null} Resolutions.\n */\n getResolutions(projection) {\n return null;\n }\n\n /**\n * @return {Promise} A promise for view-related properties.\n */\n getView() {\n return this.viewPromise_;\n }\n\n /**\n * Get the state of the source, see {@link import(\"./Source.js\").State} for possible states.\n * @return {import(\"./Source.js\").State} State.\n * @api\n */\n getState() {\n return this.state_;\n }\n\n /**\n * @return {boolean|undefined} Wrap X.\n */\n getWrapX() {\n return this.wrapX_;\n }\n\n /**\n * @return {boolean} Use linear interpolation when resampling.\n */\n getInterpolate() {\n return this.interpolate_;\n }\n\n /**\n * Refreshes the source. The source will be cleared, and data from the server will be reloaded.\n * @api\n */\n refresh() {\n this.changed();\n }\n\n /**\n * Set the attributions of the source.\n * @param {AttributionLike|undefined} attributions Attributions.\n * Can be passed as `string`, `Array`, {@link module:ol/source/Source~Attribution},\n * or `undefined`.\n * @api\n */\n setAttributions(attributions) {\n this.attributions_ = adaptAttributions(attributions);\n this.changed();\n }\n\n /**\n * Set the state of the source.\n * @param {import(\"./Source.js\").State} state State.\n */\n setState(state) {\n this.state_ = state;\n this.changed();\n }\n}\n\n/**\n * Turns the attributions option into an attributions function.\n * @param {AttributionLike|undefined} attributionLike The attribution option.\n * @return {Attribution|null} An attribution function (or null).\n */\nfunction adaptAttributions(attributionLike) {\n if (!attributionLike) {\n return null;\n }\n if (Array.isArray(attributionLike)) {\n return function (frameState) {\n return attributionLike;\n };\n }\n\n if (typeof attributionLike === 'function') {\n return attributionLike;\n }\n\n return function (frameState) {\n return [attributionLike];\n };\n}\n\nexport default Source;\n","/**\n * @module ol/tilegrid/TileGrid\n */\nimport TileRange, {\n createOrUpdate as createOrUpdateTileRange,\n} from '../TileRange.js';\nimport {DEFAULT_TILE_SIZE} from './common.js';\nimport {assert} from '../asserts.js';\nimport {ceil, clamp, floor} from '../math.js';\nimport {createOrUpdate, getTopLeft} from '../extent.js';\nimport {createOrUpdate as createOrUpdateTileCoord} from '../tilecoord.js';\nimport {intersectsLinearRing} from '../geom/flat/intersectsextent.js';\nimport {isSorted, linearFindNearest} from '../array.js';\nimport {toSize} from '../size.js';\n\n/**\n * @private\n * @type {import(\"../tilecoord.js\").TileCoord}\n */\nconst tmpTileCoord = [0, 0, 0];\n\n/**\n * Number of decimal digits to consider in integer values when rounding.\n * @type {number}\n */\nconst DECIMALS = 5;\n\n/**\n * @typedef {Object} Options\n * @property {import(\"../extent.js\").Extent} [extent] Extent for the tile grid. No tiles outside this\n * extent will be requested by {@link module:ol/source/Tile~TileSource} sources. When no `origin` or\n * `origins` are configured, the `origin` will be set to the top-left corner of the extent.\n * @property {number} [minZoom=0] Minimum zoom.\n * @property {import(\"../coordinate.js\").Coordinate} [origin] The tile grid origin, i.e. where the `x`\n * and `y` axes meet (`[z, 0, 0]`). Tile coordinates increase left to right and downwards. If not\n * specified, `extent` or `origins` must be provided.\n * @property {Array} [origins] Tile grid origins, i.e. where\n * the `x` and `y` axes meet (`[z, 0, 0]`), for each zoom level. If given, the array length\n * should match the length of the `resolutions` array, i.e. each resolution can have a different\n * origin. Tile coordinates increase left to right and downwards. If not specified, `extent` or\n * `origin` must be provided.\n * @property {!Array} resolutions Resolutions. The array index of each resolution needs\n * to match the zoom level. This means that even if a `minZoom` is configured, the resolutions\n * array will have a length of `maxZoom + 1`.\n * @property {Array} [sizes] Number of tile rows and columns\n * of the grid for each zoom level. If specified the values\n * define each zoom level's extent together with the `origin` or `origins`.\n * A grid `extent` can be configured in addition, and will further limit the extent\n * for which tile requests are made by sources. If the bottom-left corner of\n * an extent is used as `origin` or `origins`, then the `y` value must be\n * negative because OpenLayers tile coordinates use the top left as the origin.\n * @property {number|import(\"../size.js\").Size} [tileSize] Tile size.\n * Default is `[256, 256]`.\n * @property {Array} [tileSizes] Tile sizes. If given, the array length\n * should match the length of the `resolutions` array, i.e. each resolution can have a different\n * tile size.\n */\n\n/**\n * @classdesc\n * Base class for setting the grid pattern for sources accessing tiled-image\n * servers.\n * @api\n */\nclass TileGrid {\n /**\n * @param {Options} options Tile grid options.\n */\n constructor(options) {\n /**\n * @protected\n * @type {number}\n */\n this.minZoom = options.minZoom !== undefined ? options.minZoom : 0;\n\n /**\n * @private\n * @type {!Array}\n */\n this.resolutions_ = options.resolutions;\n assert(\n isSorted(\n this.resolutions_,\n function (a, b) {\n return b - a;\n },\n true\n ),\n 17\n ); // `resolutions` must be sorted in descending order\n\n // check if we've got a consistent zoom factor and origin\n let zoomFactor;\n if (!options.origins) {\n for (let i = 0, ii = this.resolutions_.length - 1; i < ii; ++i) {\n if (!zoomFactor) {\n zoomFactor = this.resolutions_[i] / this.resolutions_[i + 1];\n } else {\n if (this.resolutions_[i] / this.resolutions_[i + 1] !== zoomFactor) {\n zoomFactor = undefined;\n break;\n }\n }\n }\n }\n\n /**\n * @private\n * @type {number|undefined}\n */\n this.zoomFactor_ = zoomFactor;\n\n /**\n * @protected\n * @type {number}\n */\n this.maxZoom = this.resolutions_.length - 1;\n\n /**\n * @private\n * @type {import(\"../coordinate.js\").Coordinate|null}\n */\n this.origin_ = options.origin !== undefined ? options.origin : null;\n\n /**\n * @private\n * @type {Array}\n */\n this.origins_ = null;\n if (options.origins !== undefined) {\n this.origins_ = options.origins;\n assert(this.origins_.length == this.resolutions_.length, 20); // Number of `origins` and `resolutions` must be equal\n }\n\n const extent = options.extent;\n\n if (extent !== undefined && !this.origin_ && !this.origins_) {\n this.origin_ = getTopLeft(extent);\n }\n\n assert(\n (!this.origin_ && this.origins_) || (this.origin_ && !this.origins_),\n 18\n ); // Either `origin` or `origins` must be configured, never both\n\n /**\n * @private\n * @type {Array}\n */\n this.tileSizes_ = null;\n if (options.tileSizes !== undefined) {\n this.tileSizes_ = options.tileSizes;\n assert(this.tileSizes_.length == this.resolutions_.length, 19); // Number of `tileSizes` and `resolutions` must be equal\n }\n\n /**\n * @private\n * @type {number|import(\"../size.js\").Size}\n */\n this.tileSize_ =\n options.tileSize !== undefined\n ? options.tileSize\n : !this.tileSizes_\n ? DEFAULT_TILE_SIZE\n : null;\n assert(\n (!this.tileSize_ && this.tileSizes_) ||\n (this.tileSize_ && !this.tileSizes_),\n 22\n ); // Either `tileSize` or `tileSizes` must be configured, never both\n\n /**\n * @private\n * @type {import(\"../extent.js\").Extent}\n */\n this.extent_ = extent !== undefined ? extent : null;\n\n /**\n * @private\n * @type {Array}\n */\n this.fullTileRanges_ = null;\n\n /**\n * @private\n * @type {import(\"../size.js\").Size}\n */\n this.tmpSize_ = [0, 0];\n\n /**\n * @private\n * @type {import(\"../extent.js\").Extent}\n */\n this.tmpExtent_ = [0, 0, 0, 0];\n\n if (options.sizes !== undefined) {\n this.fullTileRanges_ = options.sizes.map(function (size, z) {\n const tileRange = new TileRange(\n Math.min(0, size[0]),\n Math.max(size[0] - 1, -1),\n Math.min(0, size[1]),\n Math.max(size[1] - 1, -1)\n );\n if (extent) {\n const restrictedTileRange = this.getTileRangeForExtentAndZ(extent, z);\n tileRange.minX = Math.max(restrictedTileRange.minX, tileRange.minX);\n tileRange.maxX = Math.min(restrictedTileRange.maxX, tileRange.maxX);\n tileRange.minY = Math.max(restrictedTileRange.minY, tileRange.minY);\n tileRange.maxY = Math.min(restrictedTileRange.maxY, tileRange.maxY);\n }\n return tileRange;\n }, this);\n } else if (extent) {\n this.calculateTileRanges_(extent);\n }\n }\n\n /**\n * Call a function with each tile coordinate for a given extent and zoom level.\n *\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @param {number} zoom Integer zoom level.\n * @param {function(import(\"../tilecoord.js\").TileCoord): void} callback Function called with each tile coordinate.\n * @api\n */\n forEachTileCoord(extent, zoom, callback) {\n const tileRange = this.getTileRangeForExtentAndZ(extent, zoom);\n for (let i = tileRange.minX, ii = tileRange.maxX; i <= ii; ++i) {\n for (let j = tileRange.minY, jj = tileRange.maxY; j <= jj; ++j) {\n callback([zoom, i, j]);\n }\n }\n }\n\n /**\n * @param {import(\"../tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n * @param {function(number, import(\"../TileRange.js\").default): boolean} callback Callback.\n * @param {import(\"../TileRange.js\").default} [tempTileRange] Temporary import(\"../TileRange.js\").default object.\n * @param {import(\"../extent.js\").Extent} [tempExtent] Temporary import(\"../extent.js\").Extent object.\n * @return {boolean} Callback succeeded.\n */\n forEachTileCoordParentTileRange(\n tileCoord,\n callback,\n tempTileRange,\n tempExtent\n ) {\n let tileRange, x, y;\n let tileCoordExtent = null;\n let z = tileCoord[0] - 1;\n if (this.zoomFactor_ === 2) {\n x = tileCoord[1];\n y = tileCoord[2];\n } else {\n tileCoordExtent = this.getTileCoordExtent(tileCoord, tempExtent);\n }\n while (z >= this.minZoom) {\n if (this.zoomFactor_ === 2) {\n x = Math.floor(x / 2);\n y = Math.floor(y / 2);\n tileRange = createOrUpdateTileRange(x, x, y, y, tempTileRange);\n } else {\n tileRange = this.getTileRangeForExtentAndZ(\n tileCoordExtent,\n z,\n tempTileRange\n );\n }\n if (callback(z, tileRange)) {\n return true;\n }\n --z;\n }\n return false;\n }\n\n /**\n * Get the extent for this tile grid, if it was configured.\n * @return {import(\"../extent.js\").Extent} Extent.\n * @api\n */\n getExtent() {\n return this.extent_;\n }\n\n /**\n * Get the maximum zoom level for the grid.\n * @return {number} Max zoom.\n * @api\n */\n getMaxZoom() {\n return this.maxZoom;\n }\n\n /**\n * Get the minimum zoom level for the grid.\n * @return {number} Min zoom.\n * @api\n */\n getMinZoom() {\n return this.minZoom;\n }\n\n /**\n * Get the origin for the grid at the given zoom level.\n * @param {number} z Integer zoom level.\n * @return {import(\"../coordinate.js\").Coordinate} Origin.\n * @api\n */\n getOrigin(z) {\n if (this.origin_) {\n return this.origin_;\n }\n return this.origins_[z];\n }\n\n /**\n * Get the resolution for the given zoom level.\n * @param {number} z Integer zoom level.\n * @return {number} Resolution.\n * @api\n */\n getResolution(z) {\n return this.resolutions_[z];\n }\n\n /**\n * Get the list of resolutions for the tile grid.\n * @return {Array} Resolutions.\n * @api\n */\n getResolutions() {\n return this.resolutions_;\n }\n\n /**\n * @param {import(\"../tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n * @param {import(\"../TileRange.js\").default} [tempTileRange] Temporary import(\"../TileRange.js\").default object.\n * @param {import(\"../extent.js\").Extent} [tempExtent] Temporary import(\"../extent.js\").Extent object.\n * @return {import(\"../TileRange.js\").default|null} Tile range.\n */\n getTileCoordChildTileRange(tileCoord, tempTileRange, tempExtent) {\n if (tileCoord[0] < this.maxZoom) {\n if (this.zoomFactor_ === 2) {\n const minX = tileCoord[1] * 2;\n const minY = tileCoord[2] * 2;\n return createOrUpdateTileRange(\n minX,\n minX + 1,\n minY,\n minY + 1,\n tempTileRange\n );\n }\n const tileCoordExtent = this.getTileCoordExtent(\n tileCoord,\n tempExtent || this.tmpExtent_\n );\n return this.getTileRangeForExtentAndZ(\n tileCoordExtent,\n tileCoord[0] + 1,\n tempTileRange\n );\n }\n return null;\n }\n\n /**\n * @param {import(\"../tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n * @param {number} z Integer zoom level.\n * @param {import(\"../TileRange.js\").default} [tempTileRange] Temporary import(\"../TileRange.js\").default object.\n * @return {import(\"../TileRange.js\").default|null} Tile range.\n */\n getTileRangeForTileCoordAndZ(tileCoord, z, tempTileRange) {\n if (z > this.maxZoom || z < this.minZoom) {\n return null;\n }\n\n const tileCoordZ = tileCoord[0];\n const tileCoordX = tileCoord[1];\n const tileCoordY = tileCoord[2];\n\n if (z === tileCoordZ) {\n return createOrUpdateTileRange(\n tileCoordX,\n tileCoordY,\n tileCoordX,\n tileCoordY,\n tempTileRange\n );\n }\n\n if (this.zoomFactor_) {\n const factor = Math.pow(this.zoomFactor_, z - tileCoordZ);\n const minX = Math.floor(tileCoordX * factor);\n const minY = Math.floor(tileCoordY * factor);\n if (z < tileCoordZ) {\n return createOrUpdateTileRange(minX, minX, minY, minY, tempTileRange);\n }\n\n const maxX = Math.floor(factor * (tileCoordX + 1)) - 1;\n const maxY = Math.floor(factor * (tileCoordY + 1)) - 1;\n return createOrUpdateTileRange(minX, maxX, minY, maxY, tempTileRange);\n }\n\n const tileCoordExtent = this.getTileCoordExtent(tileCoord, this.tmpExtent_);\n return this.getTileRangeForExtentAndZ(tileCoordExtent, z, tempTileRange);\n }\n\n /**\n * Get a tile range for the given extent and integer zoom level.\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @param {number} z Integer zoom level.\n * @param {import(\"../TileRange.js\").default} [tempTileRange] Temporary tile range object.\n * @return {import(\"../TileRange.js\").default} Tile range.\n */\n getTileRangeForExtentAndZ(extent, z, tempTileRange) {\n this.getTileCoordForXYAndZ_(extent[0], extent[3], z, false, tmpTileCoord);\n const minX = tmpTileCoord[1];\n const minY = tmpTileCoord[2];\n this.getTileCoordForXYAndZ_(extent[2], extent[1], z, true, tmpTileCoord);\n const maxX = tmpTileCoord[1];\n const maxY = tmpTileCoord[2];\n return createOrUpdateTileRange(minX, maxX, minY, maxY, tempTileRange);\n }\n\n /**\n * @param {import(\"../tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n * @return {import(\"../coordinate.js\").Coordinate} Tile center.\n */\n getTileCoordCenter(tileCoord) {\n const origin = this.getOrigin(tileCoord[0]);\n const resolution = this.getResolution(tileCoord[0]);\n const tileSize = toSize(this.getTileSize(tileCoord[0]), this.tmpSize_);\n return [\n origin[0] + (tileCoord[1] + 0.5) * tileSize[0] * resolution,\n origin[1] - (tileCoord[2] + 0.5) * tileSize[1] * resolution,\n ];\n }\n\n /**\n * Get the extent of a tile coordinate.\n *\n * @param {import(\"../tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n * @param {import(\"../extent.js\").Extent} [tempExtent] Temporary extent object.\n * @return {import(\"../extent.js\").Extent} Extent.\n * @api\n */\n getTileCoordExtent(tileCoord, tempExtent) {\n const origin = this.getOrigin(tileCoord[0]);\n const resolution = this.getResolution(tileCoord[0]);\n const tileSize = toSize(this.getTileSize(tileCoord[0]), this.tmpSize_);\n const minX = origin[0] + tileCoord[1] * tileSize[0] * resolution;\n const minY = origin[1] - (tileCoord[2] + 1) * tileSize[1] * resolution;\n const maxX = minX + tileSize[0] * resolution;\n const maxY = minY + tileSize[1] * resolution;\n return createOrUpdate(minX, minY, maxX, maxY, tempExtent);\n }\n\n /**\n * Get the tile coordinate for the given map coordinate and resolution. This\n * method considers that coordinates that intersect tile boundaries should be\n * assigned the higher tile coordinate.\n *\n * @param {import(\"../coordinate.js\").Coordinate} coordinate Coordinate.\n * @param {number} resolution Resolution.\n * @param {import(\"../tilecoord.js\").TileCoord} [opt_tileCoord] Destination import(\"../tilecoord.js\").TileCoord object.\n * @return {import(\"../tilecoord.js\").TileCoord} Tile coordinate.\n * @api\n */\n getTileCoordForCoordAndResolution(coordinate, resolution, opt_tileCoord) {\n return this.getTileCoordForXYAndResolution_(\n coordinate[0],\n coordinate[1],\n resolution,\n false,\n opt_tileCoord\n );\n }\n\n /**\n * Note that this method should not be called for resolutions that correspond\n * to an integer zoom level. Instead call the `getTileCoordForXYAndZ_` method.\n * @param {number} x X.\n * @param {number} y Y.\n * @param {number} resolution Resolution (for a non-integer zoom level).\n * @param {boolean} reverseIntersectionPolicy Instead of letting edge\n * intersections go to the higher tile coordinate, let edge intersections\n * go to the lower tile coordinate.\n * @param {import(\"../tilecoord.js\").TileCoord} [opt_tileCoord] Temporary import(\"../tilecoord.js\").TileCoord object.\n * @return {import(\"../tilecoord.js\").TileCoord} Tile coordinate.\n * @private\n */\n getTileCoordForXYAndResolution_(\n x,\n y,\n resolution,\n reverseIntersectionPolicy,\n opt_tileCoord\n ) {\n const z = this.getZForResolution(resolution);\n const scale = resolution / this.getResolution(z);\n const origin = this.getOrigin(z);\n const tileSize = toSize(this.getTileSize(z), this.tmpSize_);\n\n let tileCoordX = (scale * (x - origin[0])) / resolution / tileSize[0];\n let tileCoordY = (scale * (origin[1] - y)) / resolution / tileSize[1];\n\n if (reverseIntersectionPolicy) {\n tileCoordX = ceil(tileCoordX, DECIMALS) - 1;\n tileCoordY = ceil(tileCoordY, DECIMALS) - 1;\n } else {\n tileCoordX = floor(tileCoordX, DECIMALS);\n tileCoordY = floor(tileCoordY, DECIMALS);\n }\n\n return createOrUpdateTileCoord(z, tileCoordX, tileCoordY, opt_tileCoord);\n }\n\n /**\n * Although there is repetition between this method and `getTileCoordForXYAndResolution_`,\n * they should have separate implementations. This method is for integer zoom\n * levels. The other method should only be called for resolutions corresponding\n * to non-integer zoom levels.\n * @param {number} x Map x coordinate.\n * @param {number} y Map y coordinate.\n * @param {number} z Integer zoom level.\n * @param {boolean} reverseIntersectionPolicy Instead of letting edge\n * intersections go to the higher tile coordinate, let edge intersections\n * go to the lower tile coordinate.\n * @param {import(\"../tilecoord.js\").TileCoord} [opt_tileCoord] Temporary import(\"../tilecoord.js\").TileCoord object.\n * @return {import(\"../tilecoord.js\").TileCoord} Tile coordinate.\n * @private\n */\n getTileCoordForXYAndZ_(x, y, z, reverseIntersectionPolicy, opt_tileCoord) {\n const origin = this.getOrigin(z);\n const resolution = this.getResolution(z);\n const tileSize = toSize(this.getTileSize(z), this.tmpSize_);\n\n let tileCoordX = (x - origin[0]) / resolution / tileSize[0];\n let tileCoordY = (origin[1] - y) / resolution / tileSize[1];\n\n if (reverseIntersectionPolicy) {\n tileCoordX = ceil(tileCoordX, DECIMALS) - 1;\n tileCoordY = ceil(tileCoordY, DECIMALS) - 1;\n } else {\n tileCoordX = floor(tileCoordX, DECIMALS);\n tileCoordY = floor(tileCoordY, DECIMALS);\n }\n\n return createOrUpdateTileCoord(z, tileCoordX, tileCoordY, opt_tileCoord);\n }\n\n /**\n * Get a tile coordinate given a map coordinate and zoom level.\n * @param {import(\"../coordinate.js\").Coordinate} coordinate Coordinate.\n * @param {number} z Zoom level.\n * @param {import(\"../tilecoord.js\").TileCoord} [opt_tileCoord] Destination import(\"../tilecoord.js\").TileCoord object.\n * @return {import(\"../tilecoord.js\").TileCoord} Tile coordinate.\n * @api\n */\n getTileCoordForCoordAndZ(coordinate, z, opt_tileCoord) {\n return this.getTileCoordForXYAndZ_(\n coordinate[0],\n coordinate[1],\n z,\n false,\n opt_tileCoord\n );\n }\n\n /**\n * @param {import(\"../tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n * @return {number} Tile resolution.\n */\n getTileCoordResolution(tileCoord) {\n return this.resolutions_[tileCoord[0]];\n }\n\n /**\n * Get the tile size for a zoom level. The type of the return value matches the\n * `tileSize` or `tileSizes` that the tile grid was configured with. To always\n * get an {@link import(\"../size.js\").Size}, run the result through {@link module:ol/size.toSize}.\n * @param {number} z Z.\n * @return {number|import(\"../size.js\").Size} Tile size.\n * @api\n */\n getTileSize(z) {\n if (this.tileSize_) {\n return this.tileSize_;\n }\n return this.tileSizes_[z];\n }\n\n /**\n * @param {number} z Zoom level.\n * @return {import(\"../TileRange.js\").default} Extent tile range for the specified zoom level.\n */\n getFullTileRange(z) {\n if (!this.fullTileRanges_) {\n return this.extent_\n ? this.getTileRangeForExtentAndZ(this.extent_, z)\n : null;\n }\n return this.fullTileRanges_[z];\n }\n\n /**\n * @param {number} resolution Resolution.\n * @param {number|import(\"../array.js\").NearestDirectionFunction} [opt_direction]\n * If 0, the nearest resolution will be used.\n * If 1, the nearest higher resolution (lower Z) will be used. If -1, the\n * nearest lower resolution (higher Z) will be used. Default is 0.\n * Use a {@link module:ol/array~NearestDirectionFunction} for more precise control.\n *\n * For example to change tile Z at the midpoint of zoom levels\n * ```js\n * function(value, high, low) {\n * return value - low * Math.sqrt(high / low);\n * }\n * ```\n * @return {number} Z.\n * @api\n */\n getZForResolution(resolution, opt_direction) {\n const z = linearFindNearest(\n this.resolutions_,\n resolution,\n opt_direction || 0\n );\n return clamp(z, this.minZoom, this.maxZoom);\n }\n\n /**\n * The tile with the provided tile coordinate intersects the given viewport.\n * @param {import('../tilecoord.js').TileCoord} tileCoord Tile coordinate.\n * @param {Array} viewport Viewport as returned from {@link module:ol/extent.getRotatedViewport}.\n * @return {boolean} The tile with the provided tile coordinate intersects the given viewport.\n */\n tileCoordIntersectsViewport(tileCoord, viewport) {\n return intersectsLinearRing(\n viewport,\n 0,\n viewport.length,\n 2,\n this.getTileCoordExtent(tileCoord)\n );\n }\n\n /**\n * @param {!import(\"../extent.js\").Extent} extent Extent for this tile grid.\n * @private\n */\n calculateTileRanges_(extent) {\n const length = this.resolutions_.length;\n const fullTileRanges = new Array(length);\n for (let z = this.minZoom; z < length; ++z) {\n fullTileRanges[z] = this.getTileRangeForExtentAndZ(extent, z);\n }\n this.fullTileRanges_ = fullTileRanges;\n }\n}\n\nexport default TileGrid;\n","/**\n * @module ol/tilegrid\n */\nimport TileGrid from './tilegrid/TileGrid.js';\nimport {DEFAULT_MAX_ZOOM, DEFAULT_TILE_SIZE} from './tilegrid/common.js';\nimport {METERS_PER_UNIT, get as getProjection} from './proj.js';\nimport {\n containsCoordinate,\n createOrUpdate,\n getCorner,\n getHeight,\n getWidth,\n} from './extent.js';\nimport {toSize} from './size.js';\n\n/**\n * @param {import(\"./proj/Projection.js\").default} projection Projection.\n * @return {!TileGrid} Default tile grid for the\n * passed projection.\n */\nexport function getForProjection(projection) {\n let tileGrid = projection.getDefaultTileGrid();\n if (!tileGrid) {\n tileGrid = createForProjection(projection);\n projection.setDefaultTileGrid(tileGrid);\n }\n return tileGrid;\n}\n\n/**\n * @param {TileGrid} tileGrid Tile grid.\n * @param {import(\"./tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n * @param {import(\"./proj/Projection.js\").default} projection Projection.\n * @return {import(\"./tilecoord.js\").TileCoord} Tile coordinate.\n */\nexport function wrapX(tileGrid, tileCoord, projection) {\n const z = tileCoord[0];\n const center = tileGrid.getTileCoordCenter(tileCoord);\n const projectionExtent = extentFromProjection(projection);\n if (!containsCoordinate(projectionExtent, center)) {\n const worldWidth = getWidth(projectionExtent);\n const worldsAway = Math.ceil(\n (projectionExtent[0] - center[0]) / worldWidth\n );\n center[0] += worldWidth * worldsAway;\n return tileGrid.getTileCoordForCoordAndZ(center, z);\n }\n return tileCoord;\n}\n\n/**\n * @param {import(\"./extent.js\").Extent} extent Extent.\n * @param {number} [maxZoom] Maximum zoom level (default is\n * DEFAULT_MAX_ZOOM).\n * @param {number|import(\"./size.js\").Size} [tileSize] Tile size (default uses\n * DEFAULT_TILE_SIZE).\n * @param {import(\"./extent.js\").Corner} [corner] Extent corner (default is `'top-left'`).\n * @return {!TileGrid} TileGrid instance.\n */\nexport function createForExtent(extent, maxZoom, tileSize, corner) {\n corner = corner !== undefined ? corner : 'top-left';\n\n const resolutions = resolutionsFromExtent(extent, maxZoom, tileSize);\n\n return new TileGrid({\n extent: extent,\n origin: getCorner(extent, corner),\n resolutions: resolutions,\n tileSize: tileSize,\n });\n}\n\n/**\n * @typedef {Object} XYZOptions\n * @property {import(\"./extent.js\").Extent} [extent] Extent for the tile grid. The origin for an XYZ tile grid is the\n * top-left corner of the extent. If `maxResolution` is not provided the zero level of the grid is defined by the resolution\n * at which one tile fits in the provided extent. If not provided, the extent of the EPSG:3857 projection is used.\n * @property {number} [maxResolution] Resolution at level zero.\n * @property {number} [maxZoom] Maximum zoom. The default is `42`. This determines the number of levels\n * in the grid set. For example, a `maxZoom` of 21 means there are 22 levels in the grid set.\n * @property {number} [minZoom=0] Minimum zoom.\n * @property {number|import(\"./size.js\").Size} [tileSize=[256, 256]] Tile size in pixels.\n */\n\n/**\n * Creates a tile grid with a standard XYZ tiling scheme.\n * @param {XYZOptions} [options] Tile grid options.\n * @return {!TileGrid} Tile grid instance.\n * @api\n */\nexport function createXYZ(options) {\n const xyzOptions = options || {};\n\n const extent = xyzOptions.extent || getProjection('EPSG:3857').getExtent();\n\n const gridOptions = {\n extent: extent,\n minZoom: xyzOptions.minZoom,\n tileSize: xyzOptions.tileSize,\n resolutions: resolutionsFromExtent(\n extent,\n xyzOptions.maxZoom,\n xyzOptions.tileSize,\n xyzOptions.maxResolution\n ),\n };\n return new TileGrid(gridOptions);\n}\n\n/**\n * Create a resolutions array from an extent. A zoom factor of 2 is assumed.\n * @param {import(\"./extent.js\").Extent} extent Extent.\n * @param {number} [maxZoom] Maximum zoom level (default is\n * DEFAULT_MAX_ZOOM).\n * @param {number|import(\"./size.js\").Size} [tileSize] Tile size (default uses\n * DEFAULT_TILE_SIZE).\n * @param {number} [maxResolution] Resolution at level zero.\n * @return {!Array} Resolutions array.\n */\nfunction resolutionsFromExtent(extent, maxZoom, tileSize, maxResolution) {\n maxZoom = maxZoom !== undefined ? maxZoom : DEFAULT_MAX_ZOOM;\n tileSize = toSize(tileSize !== undefined ? tileSize : DEFAULT_TILE_SIZE);\n\n const height = getHeight(extent);\n const width = getWidth(extent);\n\n maxResolution =\n maxResolution > 0\n ? maxResolution\n : Math.max(width / tileSize[0], height / tileSize[1]);\n\n const length = maxZoom + 1;\n const resolutions = new Array(length);\n for (let z = 0; z < length; ++z) {\n resolutions[z] = maxResolution / Math.pow(2, z);\n }\n return resolutions;\n}\n\n/**\n * @param {import(\"./proj.js\").ProjectionLike} projection Projection.\n * @param {number} [maxZoom] Maximum zoom level (default is\n * DEFAULT_MAX_ZOOM).\n * @param {number|import(\"./size.js\").Size} [tileSize] Tile size (default uses\n * DEFAULT_TILE_SIZE).\n * @param {import(\"./extent.js\").Corner} [corner] Extent corner (default is `'top-left'`).\n * @return {!TileGrid} TileGrid instance.\n */\nexport function createForProjection(projection, maxZoom, tileSize, corner) {\n const extent = extentFromProjection(projection);\n return createForExtent(extent, maxZoom, tileSize, corner);\n}\n\n/**\n * Generate a tile grid extent from a projection. If the projection has an\n * extent, it is used. If not, a global extent is assumed.\n * @param {import(\"./proj.js\").ProjectionLike} projection Projection.\n * @return {import(\"./extent.js\").Extent} Extent.\n */\nexport function extentFromProjection(projection) {\n projection = getProjection(projection);\n let extent = projection.getExtent();\n if (!extent) {\n const half =\n (180 * METERS_PER_UNIT.degrees) / projection.getMetersPerUnit();\n extent = createOrUpdate(-half, -half, half, half);\n }\n return extent;\n}\n","/**\n * @module ol/source/Tile\n */\nimport Event from '../events/Event.js';\nimport Source from './Source.js';\nimport TileCache from '../TileCache.js';\nimport TileState from '../TileState.js';\nimport {abstract} from '../util.js';\nimport {assert} from '../asserts.js';\nimport {equivalent} from '../proj.js';\nimport {getKeyZXY, withinExtentAndZ} from '../tilecoord.js';\nimport {\n getForProjection as getTileGridForProjection,\n wrapX,\n} from '../tilegrid.js';\nimport {scale as scaleSize, toSize} from '../size.js';\n\n/***\n * @template Return\n * @typedef {import(\"../Observable\").OnSignature &\n * import(\"../Observable\").OnSignature &\n * import(\"../Observable\").OnSignature &\n * import(\"../Observable\").CombinedOnSignature} TileSourceOnSignature\n */\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.\n * @property {number} [cacheSize] CacheSize.\n * @property {boolean} [opaque=false] Whether the layer is opaque.\n * @property {number} [tilePixelRatio] TilePixelRatio.\n * @property {import(\"../proj.js\").ProjectionLike} [projection] Projection.\n * @property {import(\"./Source.js\").State} [state] State.\n * @property {import(\"../tilegrid/TileGrid.js\").default} [tileGrid] TileGrid.\n * @property {boolean} [wrapX=false] WrapX.\n * @property {number} [transition] Transition.\n * @property {string} [key] Key.\n * @property {number|import(\"../array.js\").NearestDirectionFunction} [zDirection=0] ZDirection.\n * @property {boolean} [interpolate=false] Use interpolated values when resampling. By default,\n * the nearest neighbor is used when resampling.\n */\n\n/**\n * @classdesc\n * Abstract base class; normally only used for creating subclasses and not\n * instantiated in apps.\n * Base class for sources providing images divided into a tile grid.\n * @abstract\n * @api\n */\nclass TileSource extends Source {\n /**\n * @param {Options} options SourceTile source options.\n */\n constructor(options) {\n super({\n attributions: options.attributions,\n attributionsCollapsible: options.attributionsCollapsible,\n projection: options.projection,\n state: options.state,\n wrapX: options.wrapX,\n interpolate: options.interpolate,\n });\n\n /***\n * @type {TileSourceOnSignature}\n */\n this.on;\n\n /***\n * @type {TileSourceOnSignature}\n */\n this.once;\n\n /***\n * @type {TileSourceOnSignature}\n */\n this.un;\n\n /**\n * @private\n * @type {boolean}\n */\n this.opaque_ = options.opaque !== undefined ? options.opaque : false;\n\n /**\n * @private\n * @type {number}\n */\n this.tilePixelRatio_ =\n options.tilePixelRatio !== undefined ? options.tilePixelRatio : 1;\n\n /**\n * @type {import(\"../tilegrid/TileGrid.js\").default|null}\n */\n this.tileGrid = options.tileGrid !== undefined ? options.tileGrid : null;\n\n const tileSize = [256, 256];\n if (this.tileGrid) {\n toSize(this.tileGrid.getTileSize(this.tileGrid.getMinZoom()), tileSize);\n }\n\n /**\n * @protected\n * @type {import(\"../TileCache.js\").default}\n */\n this.tileCache = new TileCache(options.cacheSize || 0);\n\n /**\n * @protected\n * @type {import(\"../size.js\").Size}\n */\n this.tmpSize = [0, 0];\n\n /**\n * @private\n * @type {string}\n */\n this.key_ = options.key || '';\n\n /**\n * @protected\n * @type {import(\"../Tile.js\").Options}\n */\n this.tileOptions = {\n transition: options.transition,\n interpolate: options.interpolate,\n };\n\n /**\n * zDirection hint, read by the renderer. Indicates which resolution should be used\n * by a renderer if the views resolution does not match any resolution of the tile source.\n * If 0, the nearest resolution will be used. If 1, the nearest lower resolution\n * will be used. If -1, the nearest higher resolution will be used.\n * @type {number|import(\"../array.js\").NearestDirectionFunction}\n */\n this.zDirection = options.zDirection ? options.zDirection : 0;\n }\n\n /**\n * @return {boolean} Can expire cache.\n */\n canExpireCache() {\n return this.tileCache.canExpireCache();\n }\n\n /**\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @param {!Object} usedTiles Used tiles.\n */\n expireCache(projection, usedTiles) {\n const tileCache = this.getTileCacheForProjection(projection);\n if (tileCache) {\n tileCache.expireCache(usedTiles);\n }\n }\n\n /**\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @param {number} z Zoom level.\n * @param {import(\"../TileRange.js\").default} tileRange Tile range.\n * @param {function(import(\"../Tile.js\").default):(boolean|void)} callback Called with each\n * loaded tile. If the callback returns `false`, the tile will not be\n * considered loaded.\n * @return {boolean} The tile range is fully covered with loaded tiles.\n */\n forEachLoadedTile(projection, z, tileRange, callback) {\n const tileCache = this.getTileCacheForProjection(projection);\n if (!tileCache) {\n return false;\n }\n\n let covered = true;\n let tile, tileCoordKey, loaded;\n for (let x = tileRange.minX; x <= tileRange.maxX; ++x) {\n for (let y = tileRange.minY; y <= tileRange.maxY; ++y) {\n tileCoordKey = getKeyZXY(z, x, y);\n loaded = false;\n if (tileCache.containsKey(tileCoordKey)) {\n tile = /** @type {!import(\"../Tile.js\").default} */ (\n tileCache.get(tileCoordKey)\n );\n loaded = tile.getState() === TileState.LOADED;\n if (loaded) {\n loaded = callback(tile) !== false;\n }\n }\n if (!loaded) {\n covered = false;\n }\n }\n }\n return covered;\n }\n\n /**\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {number} Gutter.\n */\n getGutterForProjection(projection) {\n return 0;\n }\n\n /**\n * Return the key to be used for all tiles in the source.\n * @return {string} The key for all tiles.\n */\n getKey() {\n return this.key_;\n }\n\n /**\n * Set the value to be used as the key for all tiles in the source.\n * @param {string} key The key for tiles.\n * @protected\n */\n setKey(key) {\n if (this.key_ !== key) {\n this.key_ = key;\n this.changed();\n }\n }\n\n /**\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {boolean} Opaque.\n */\n getOpaque(projection) {\n return this.opaque_;\n }\n\n /**\n * @param {import(\"../proj/Projection\").default} [projection] Projection.\n * @return {Array|null} Resolutions.\n */\n getResolutions(projection) {\n const tileGrid = projection\n ? this.getTileGridForProjection(projection)\n : this.tileGrid;\n if (!tileGrid) {\n return null;\n }\n return tileGrid.getResolutions();\n }\n\n /**\n * @abstract\n * @param {number} z Tile coordinate z.\n * @param {number} x Tile coordinate x.\n * @param {number} y Tile coordinate y.\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {!import(\"../Tile.js\").default} Tile.\n */\n getTile(z, x, y, pixelRatio, projection) {\n return abstract();\n }\n\n /**\n * Return the tile grid of the tile source.\n * @return {import(\"../tilegrid/TileGrid.js\").default|null} Tile grid.\n * @api\n */\n getTileGrid() {\n return this.tileGrid;\n }\n\n /**\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {!import(\"../tilegrid/TileGrid.js\").default} Tile grid.\n */\n getTileGridForProjection(projection) {\n if (!this.tileGrid) {\n return getTileGridForProjection(projection);\n }\n return this.tileGrid;\n }\n\n /**\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {import(\"../TileCache.js\").default} Tile cache.\n * @protected\n */\n getTileCacheForProjection(projection) {\n const sourceProjection = this.getProjection();\n assert(\n sourceProjection === null || equivalent(sourceProjection, projection),\n 68 // A VectorTile source can only be rendered if it has a projection compatible with the view projection.\n );\n return this.tileCache;\n }\n\n /**\n * Get the tile pixel ratio for this source. Subclasses may override this\n * method, which is meant to return a supported pixel ratio that matches the\n * provided `pixelRatio` as close as possible.\n * @param {number} pixelRatio Pixel ratio.\n * @return {number} Tile pixel ratio.\n */\n getTilePixelRatio(pixelRatio) {\n return this.tilePixelRatio_;\n }\n\n /**\n * @param {number} z Z.\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {import(\"../size.js\").Size} Tile size.\n */\n getTilePixelSize(z, pixelRatio, projection) {\n const tileGrid = this.getTileGridForProjection(projection);\n const tilePixelRatio = this.getTilePixelRatio(pixelRatio);\n const tileSize = toSize(tileGrid.getTileSize(z), this.tmpSize);\n if (tilePixelRatio == 1) {\n return tileSize;\n }\n return scaleSize(tileSize, tilePixelRatio, this.tmpSize);\n }\n\n /**\n * Returns a tile coordinate wrapped around the x-axis. When the tile coordinate\n * is outside the resolution and extent range of the tile grid, `null` will be\n * returned.\n * @param {import(\"../tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n * @param {import(\"../proj/Projection.js\").default} [projection] Projection.\n * @return {import(\"../tilecoord.js\").TileCoord} Tile coordinate to be passed to the tileUrlFunction or\n * null if no tile URL should be created for the passed `tileCoord`.\n */\n getTileCoordForTileUrlFunction(tileCoord, projection) {\n projection = projection !== undefined ? projection : this.getProjection();\n const tileGrid = this.getTileGridForProjection(projection);\n if (this.getWrapX() && projection.isGlobal()) {\n tileCoord = wrapX(tileGrid, tileCoord, projection);\n }\n return withinExtentAndZ(tileCoord, tileGrid) ? tileCoord : null;\n }\n\n /**\n * Remove all cached tiles from the source. The next render cycle will fetch new tiles.\n * @api\n */\n clear() {\n this.tileCache.clear();\n }\n\n refresh() {\n this.clear();\n super.refresh();\n }\n\n /**\n * Increases the cache size if needed\n * @param {number} tileCount Minimum number of tiles needed.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n */\n updateCacheSize(tileCount, projection) {\n const tileCache = this.getTileCacheForProjection(projection);\n if (tileCount > tileCache.highWaterMark) {\n tileCache.highWaterMark = tileCount;\n }\n }\n\n /**\n * Marks a tile coord as being used, without triggering a load.\n * @abstract\n * @param {number} z Tile coordinate z.\n * @param {number} x Tile coordinate x.\n * @param {number} y Tile coordinate y.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n */\n useTile(z, x, y, projection) {}\n}\n\n/**\n * @classdesc\n * Events emitted by {@link module:ol/source/Tile~TileSource} instances are instances of this\n * type.\n */\nexport class TileSourceEvent extends Event {\n /**\n * @param {string} type Type.\n * @param {import(\"../Tile.js\").default} tile The tile.\n */\n constructor(type, tile) {\n super(type);\n\n /**\n * The tile related to the event.\n * @type {import(\"../Tile.js\").default}\n * @api\n */\n this.tile = tile;\n }\n}\n\nexport default TileSource;\n","/**\n * @module ol/tileurlfunction\n */\nimport {assert} from './asserts.js';\nimport {modulo} from './math.js';\nimport {hash as tileCoordHash} from './tilecoord.js';\n\n/**\n * @param {string} template Template.\n * @param {import(\"./tilegrid/TileGrid.js\").default} tileGrid Tile grid.\n * @return {import(\"./Tile.js\").UrlFunction} Tile URL function.\n */\nexport function createFromTemplate(template, tileGrid) {\n const zRegEx = /\\{z\\}/g;\n const xRegEx = /\\{x\\}/g;\n const yRegEx = /\\{y\\}/g;\n const dashYRegEx = /\\{-y\\}/g;\n return (\n /**\n * @param {import(\"./tilecoord.js\").TileCoord} tileCoord Tile Coordinate.\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"./proj/Projection.js\").default} projection Projection.\n * @return {string|undefined} Tile URL.\n */\n function (tileCoord, pixelRatio, projection) {\n if (!tileCoord) {\n return undefined;\n }\n return template\n .replace(zRegEx, tileCoord[0].toString())\n .replace(xRegEx, tileCoord[1].toString())\n .replace(yRegEx, tileCoord[2].toString())\n .replace(dashYRegEx, function () {\n const z = tileCoord[0];\n const range = tileGrid.getFullTileRange(z);\n assert(range, 55); // The {-y} placeholder requires a tile grid with extent\n const y = range.getHeight() - tileCoord[2] - 1;\n return y.toString();\n });\n }\n );\n}\n\n/**\n * @param {Array} templates Templates.\n * @param {import(\"./tilegrid/TileGrid.js\").default} tileGrid Tile grid.\n * @return {import(\"./Tile.js\").UrlFunction} Tile URL function.\n */\nexport function createFromTemplates(templates, tileGrid) {\n const len = templates.length;\n const tileUrlFunctions = new Array(len);\n for (let i = 0; i < len; ++i) {\n tileUrlFunctions[i] = createFromTemplate(templates[i], tileGrid);\n }\n return createFromTileUrlFunctions(tileUrlFunctions);\n}\n\n/**\n * @param {Array} tileUrlFunctions Tile URL Functions.\n * @return {import(\"./Tile.js\").UrlFunction} Tile URL function.\n */\nexport function createFromTileUrlFunctions(tileUrlFunctions) {\n if (tileUrlFunctions.length === 1) {\n return tileUrlFunctions[0];\n }\n return (\n /**\n * @param {import(\"./tilecoord.js\").TileCoord} tileCoord Tile Coordinate.\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"./proj/Projection.js\").default} projection Projection.\n * @return {string|undefined} Tile URL.\n */\n function (tileCoord, pixelRatio, projection) {\n if (!tileCoord) {\n return undefined;\n }\n const h = tileCoordHash(tileCoord);\n const index = modulo(h, tileUrlFunctions.length);\n return tileUrlFunctions[index](tileCoord, pixelRatio, projection);\n }\n );\n}\n\n/**\n * @param {import(\"./tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"./proj/Projection.js\").default} projection Projection.\n * @return {string|undefined} Tile URL.\n */\nexport function nullTileUrlFunction(tileCoord, pixelRatio, projection) {\n return undefined;\n}\n\n/**\n * @param {string} url URL.\n * @return {Array} Array of urls.\n */\nexport function expandUrl(url) {\n const urls = [];\n let match = /\\{([a-z])-([a-z])\\}/.exec(url);\n if (match) {\n // char range\n const startCharCode = match[1].charCodeAt(0);\n const stopCharCode = match[2].charCodeAt(0);\n let charCode;\n for (charCode = startCharCode; charCode <= stopCharCode; ++charCode) {\n urls.push(url.replace(match[0], String.fromCharCode(charCode)));\n }\n return urls;\n }\n match = /\\{(\\d+)-(\\d+)\\}/.exec(url);\n if (match) {\n // number range\n const stop = parseInt(match[2], 10);\n for (let i = parseInt(match[1], 10); i <= stop; i++) {\n urls.push(url.replace(match[0], i.toString()));\n }\n return urls;\n }\n urls.push(url);\n return urls;\n}\n","/**\n * @module ol/source/UrlTile\n */\nimport TileEventType from './TileEventType.js';\nimport TileSource, {TileSourceEvent} from './Tile.js';\nimport TileState from '../TileState.js';\nimport {createFromTemplates, expandUrl} from '../tileurlfunction.js';\nimport {getKeyZXY} from '../tilecoord.js';\nimport {getUid} from '../util.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.\n * @property {number} [cacheSize] Cache size.\n * @property {boolean} [opaque=false] Whether the layer is opaque.\n * @property {import(\"../proj.js\").ProjectionLike} [projection] Projection.\n * @property {import(\"./Source.js\").State} [state] State.\n * @property {import(\"../tilegrid/TileGrid.js\").default} [tileGrid] TileGrid.\n * @property {import(\"../Tile.js\").LoadFunction} tileLoadFunction TileLoadFunction.\n * @property {number} [tilePixelRatio] TilePixelRatio.\n * @property {import(\"../Tile.js\").UrlFunction} [tileUrlFunction] TileUrlFunction.\n * @property {string} [url] Url.\n * @property {Array} [urls] Urls.\n * @property {boolean} [wrapX=true] WrapX.\n * @property {number} [transition] Transition.\n * @property {string} [key] Key.\n * @property {number|import(\"../array.js\").NearestDirectionFunction} [zDirection=0] ZDirection.\n * @property {boolean} [interpolate=false] Use interpolated values when resampling. By default,\n * the nearest neighbor is used when resampling.\n */\n\n/**\n * @classdesc\n * Base class for sources providing tiles divided into a tile grid over http.\n *\n * @fires import(\"./Tile.js\").TileSourceEvent\n */\nclass UrlTile extends TileSource {\n /**\n * @param {Options} options Image tile options.\n */\n constructor(options) {\n super({\n attributions: options.attributions,\n cacheSize: options.cacheSize,\n opaque: options.opaque,\n projection: options.projection,\n state: options.state,\n tileGrid: options.tileGrid,\n tilePixelRatio: options.tilePixelRatio,\n wrapX: options.wrapX,\n transition: options.transition,\n interpolate: options.interpolate,\n key: options.key,\n attributionsCollapsible: options.attributionsCollapsible,\n zDirection: options.zDirection,\n });\n\n /**\n * @private\n * @type {boolean}\n */\n this.generateTileUrlFunction_ =\n this.tileUrlFunction === UrlTile.prototype.tileUrlFunction;\n\n /**\n * @protected\n * @type {import(\"../Tile.js\").LoadFunction}\n */\n this.tileLoadFunction = options.tileLoadFunction;\n\n if (options.tileUrlFunction) {\n this.tileUrlFunction = options.tileUrlFunction;\n }\n\n /**\n * @protected\n * @type {!Array|null}\n */\n this.urls = null;\n\n if (options.urls) {\n this.setUrls(options.urls);\n } else if (options.url) {\n this.setUrl(options.url);\n }\n\n /**\n * @private\n * @type {!Object}\n */\n this.tileLoadingKeys_ = {};\n }\n\n /**\n * Return the tile load function of the source.\n * @return {import(\"../Tile.js\").LoadFunction} TileLoadFunction\n * @api\n */\n getTileLoadFunction() {\n return this.tileLoadFunction;\n }\n\n /**\n * Return the tile URL function of the source.\n * @return {import(\"../Tile.js\").UrlFunction} TileUrlFunction\n * @api\n */\n getTileUrlFunction() {\n return Object.getPrototypeOf(this).tileUrlFunction === this.tileUrlFunction\n ? this.tileUrlFunction.bind(this)\n : this.tileUrlFunction;\n }\n\n /**\n * Return the URLs used for this source.\n * When a tileUrlFunction is used instead of url or urls,\n * null will be returned.\n * @return {!Array|null} URLs.\n * @api\n */\n getUrls() {\n return this.urls;\n }\n\n /**\n * Handle tile change events.\n * @param {import(\"../events/Event.js\").default} event Event.\n * @protected\n */\n handleTileChange(event) {\n const tile = /** @type {import(\"../Tile.js\").default} */ (event.target);\n const uid = getUid(tile);\n const tileState = tile.getState();\n let type;\n if (tileState == TileState.LOADING) {\n this.tileLoadingKeys_[uid] = true;\n type = TileEventType.TILELOADSTART;\n } else if (uid in this.tileLoadingKeys_) {\n delete this.tileLoadingKeys_[uid];\n type =\n tileState == TileState.ERROR\n ? TileEventType.TILELOADERROR\n : tileState == TileState.LOADED\n ? TileEventType.TILELOADEND\n : undefined;\n }\n if (type != undefined) {\n this.dispatchEvent(new TileSourceEvent(type, tile));\n }\n }\n\n /**\n * Set the tile load function of the source.\n * @param {import(\"../Tile.js\").LoadFunction} tileLoadFunction Tile load function.\n * @api\n */\n setTileLoadFunction(tileLoadFunction) {\n this.tileCache.clear();\n this.tileLoadFunction = tileLoadFunction;\n this.changed();\n }\n\n /**\n * Set the tile URL function of the source.\n * @param {import(\"../Tile.js\").UrlFunction} tileUrlFunction Tile URL function.\n * @param {string} [key] Optional new tile key for the source.\n * @api\n */\n setTileUrlFunction(tileUrlFunction, key) {\n this.tileUrlFunction = tileUrlFunction;\n this.tileCache.pruneExceptNewestZ();\n if (typeof key !== 'undefined') {\n this.setKey(key);\n } else {\n this.changed();\n }\n }\n\n /**\n * Set the URL to use for requests.\n * @param {string} url URL.\n * @api\n */\n setUrl(url) {\n const urls = expandUrl(url);\n this.urls = urls;\n this.setUrls(urls);\n }\n\n /**\n * Set the URLs to use for requests.\n * @param {Array} urls URLs.\n * @api\n */\n setUrls(urls) {\n this.urls = urls;\n const key = urls.join('\\n');\n if (this.generateTileUrlFunction_) {\n this.setTileUrlFunction(createFromTemplates(urls, this.tileGrid), key);\n } else {\n this.setKey(key);\n }\n }\n\n /**\n * @param {import(\"../tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {string|undefined} Tile URL.\n */\n tileUrlFunction(tileCoord, pixelRatio, projection) {\n return undefined;\n }\n\n /**\n * Marks a tile coord as being used, without triggering a load.\n * @param {number} z Tile coordinate z.\n * @param {number} x Tile coordinate x.\n * @param {number} y Tile coordinate y.\n */\n useTile(z, x, y) {\n const tileCoordKey = getKeyZXY(z, x, y);\n if (this.tileCache.containsKey(tileCoordKey)) {\n this.tileCache.get(tileCoordKey);\n }\n }\n}\n\nexport default UrlTile;\n","/**\n * @module ol/source/TileImage\n */\nimport EventType from '../events/EventType.js';\nimport ImageTile from '../ImageTile.js';\nimport ReprojTile from '../reproj/Tile.js';\nimport TileCache from '../TileCache.js';\nimport TileState from '../TileState.js';\nimport UrlTile from './UrlTile.js';\nimport {equivalent, get as getProjection} from '../proj.js';\nimport {getKey, getKeyZXY} from '../tilecoord.js';\nimport {getForProjection as getTileGridForProjection} from '../tilegrid.js';\nimport {getUid} from '../util.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.\n * @property {number} [cacheSize] Initial tile cache size. Will auto-grow to hold at least the number of tiles in the viewport.\n * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images. Note that\n * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.\n * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.\n * @property {boolean} [interpolate=true] Use interpolated values when resampling. By default,\n * linear interpolation is used when resampling. Set to false to use the nearest neighbor instead.\n * @property {boolean} [opaque=false] Whether the layer is opaque.\n * @property {import(\"../proj.js\").ProjectionLike} [projection] Projection. Default is the view projection.\n * @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).\n * Higher values can increase reprojection performance, but decrease precision.\n * @property {import(\"./Source.js\").State} [state] Source state.\n * @property {typeof import(\"../ImageTile.js\").default} [tileClass] Class used to instantiate image tiles.\n * Default is {@link module:ol/ImageTile~ImageTile}.\n * @property {import(\"../tilegrid/TileGrid.js\").default} [tileGrid] Tile grid.\n * @property {import(\"../Tile.js\").LoadFunction} [tileLoadFunction] Optional function to load a tile given a URL. The default is\n * ```js\n * function(imageTile, src) {\n * imageTile.getImage().src = src;\n * };\n * ```\n * @property {number} [tilePixelRatio=1] The pixel ratio used by the tile service. For example, if the tile\n * service advertizes 256px by 256px tiles but actually sends 512px\n * by 512px images (for retina/hidpi devices) then `tilePixelRatio`\n * should be set to `2`.\n * @property {import(\"../Tile.js\").UrlFunction} [tileUrlFunction] Optional function to get tile URL given a tile coordinate and the projection.\n * @property {string} [url] URL template. Must include `{x}`, `{y}` or `{-y}`, and `{z}` placeholders.\n * A `{?-?}` template pattern, for example `subdomain{a-f}.domain.com`, may be\n * used instead of defining each one separately in the `urls` option.\n * @property {Array} [urls] An array of URL templates.\n * @property {boolean} [wrapX] Whether to wrap the world horizontally. The default, is to\n * request out-of-bounds tiles from the server. When set to `false`, only one\n * world will be rendered. When set to `true`, tiles will be requested for one\n * world only, but they will be wrapped horizontally to render multiple worlds.\n * @property {number} [transition] Duration of the opacity transition for rendering.\n * To disable the opacity transition, pass `transition: 0`.\n * @property {string} [key] Optional tile key for proper cache fetching\n * @property {number|import(\"../array.js\").NearestDirectionFunction} [zDirection=0]\n * Choose whether to use tiles with a higher or lower zoom level when between integer\n * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.\n */\n\n/**\n * @classdesc\n * Base class for sources providing images divided into a tile grid.\n *\n * @fires import(\"./Tile.js\").TileSourceEvent\n * @api\n */\nclass TileImage extends UrlTile {\n /**\n * @param {!Options} options Image tile options.\n */\n constructor(options) {\n super({\n attributions: options.attributions,\n cacheSize: options.cacheSize,\n opaque: options.opaque,\n projection: options.projection,\n state: options.state,\n tileGrid: options.tileGrid,\n tileLoadFunction: options.tileLoadFunction\n ? options.tileLoadFunction\n : defaultTileLoadFunction,\n tilePixelRatio: options.tilePixelRatio,\n tileUrlFunction: options.tileUrlFunction,\n url: options.url,\n urls: options.urls,\n wrapX: options.wrapX,\n transition: options.transition,\n interpolate:\n options.interpolate !== undefined ? options.interpolate : true,\n key: options.key,\n attributionsCollapsible: options.attributionsCollapsible,\n zDirection: options.zDirection,\n });\n\n /**\n * @protected\n * @type {?string}\n */\n this.crossOrigin =\n options.crossOrigin !== undefined ? options.crossOrigin : null;\n\n /**\n * @protected\n * @type {typeof ImageTile}\n */\n this.tileClass =\n options.tileClass !== undefined ? options.tileClass : ImageTile;\n\n /**\n * @protected\n * @type {!Object}\n */\n this.tileCacheForProjection = {};\n\n /**\n * @protected\n * @type {!Object}\n */\n this.tileGridForProjection = {};\n\n /**\n * @private\n * @type {number|undefined}\n */\n this.reprojectionErrorThreshold_ = options.reprojectionErrorThreshold;\n\n /**\n * @private\n * @type {boolean}\n */\n this.renderReprojectionEdges_ = false;\n }\n\n /**\n * @return {boolean} Can expire cache.\n */\n canExpireCache() {\n if (this.tileCache.canExpireCache()) {\n return true;\n }\n for (const key in this.tileCacheForProjection) {\n if (this.tileCacheForProjection[key].canExpireCache()) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @param {!Object} usedTiles Used tiles.\n */\n expireCache(projection, usedTiles) {\n const usedTileCache = this.getTileCacheForProjection(projection);\n\n this.tileCache.expireCache(\n this.tileCache == usedTileCache ? usedTiles : {}\n );\n for (const id in this.tileCacheForProjection) {\n const tileCache = this.tileCacheForProjection[id];\n tileCache.expireCache(tileCache == usedTileCache ? usedTiles : {});\n }\n }\n\n /**\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {number} Gutter.\n */\n getGutterForProjection(projection) {\n if (\n this.getProjection() &&\n projection &&\n !equivalent(this.getProjection(), projection)\n ) {\n return 0;\n }\n return this.getGutter();\n }\n\n /**\n * @return {number} Gutter.\n */\n getGutter() {\n return 0;\n }\n\n /**\n * Return the key to be used for all tiles in the source.\n * @return {string} The key for all tiles.\n */\n getKey() {\n let key = super.getKey();\n if (!this.getInterpolate()) {\n key += ':disable-interpolation';\n }\n return key;\n }\n\n /**\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {boolean} Opaque.\n */\n getOpaque(projection) {\n if (\n this.getProjection() &&\n projection &&\n !equivalent(this.getProjection(), projection)\n ) {\n return false;\n }\n return super.getOpaque(projection);\n }\n\n /**\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {!import(\"../tilegrid/TileGrid.js\").default} Tile grid.\n */\n getTileGridForProjection(projection) {\n const thisProj = this.getProjection();\n if (this.tileGrid && (!thisProj || equivalent(thisProj, projection))) {\n return this.tileGrid;\n }\n const projKey = getUid(projection);\n if (!(projKey in this.tileGridForProjection)) {\n this.tileGridForProjection[projKey] =\n getTileGridForProjection(projection);\n }\n return this.tileGridForProjection[projKey];\n }\n\n /**\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {import(\"../TileCache.js\").default} Tile cache.\n */\n getTileCacheForProjection(projection) {\n const thisProj = this.getProjection();\n if (!thisProj || equivalent(thisProj, projection)) {\n return this.tileCache;\n }\n const projKey = getUid(projection);\n if (!(projKey in this.tileCacheForProjection)) {\n this.tileCacheForProjection[projKey] = new TileCache(\n this.tileCache.highWaterMark\n );\n }\n return this.tileCacheForProjection[projKey];\n }\n\n /**\n * @param {number} z Tile coordinate z.\n * @param {number} x Tile coordinate x.\n * @param {number} y Tile coordinate y.\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @param {string} key The key set on the tile.\n * @return {!ImageTile} Tile.\n * @private\n */\n createTile_(z, x, y, pixelRatio, projection, key) {\n const tileCoord = [z, x, y];\n const urlTileCoord = this.getTileCoordForTileUrlFunction(\n tileCoord,\n projection\n );\n const tileUrl = urlTileCoord\n ? this.tileUrlFunction(urlTileCoord, pixelRatio, projection)\n : undefined;\n const tile = new this.tileClass(\n tileCoord,\n tileUrl !== undefined ? TileState.IDLE : TileState.EMPTY,\n tileUrl !== undefined ? tileUrl : '',\n this.crossOrigin,\n this.tileLoadFunction,\n this.tileOptions\n );\n tile.key = key;\n tile.addEventListener(EventType.CHANGE, this.handleTileChange.bind(this));\n return tile;\n }\n\n /**\n * @param {number} z Tile coordinate z.\n * @param {number} x Tile coordinate x.\n * @param {number} y Tile coordinate y.\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {!(ImageTile|ReprojTile)} Tile.\n */\n getTile(z, x, y, pixelRatio, projection) {\n const sourceProjection = this.getProjection();\n if (\n !sourceProjection ||\n !projection ||\n equivalent(sourceProjection, projection)\n ) {\n return this.getTileInternal(\n z,\n x,\n y,\n pixelRatio,\n sourceProjection || projection\n );\n }\n const cache = this.getTileCacheForProjection(projection);\n const tileCoord = [z, x, y];\n let tile;\n const tileCoordKey = getKey(tileCoord);\n if (cache.containsKey(tileCoordKey)) {\n tile = cache.get(tileCoordKey);\n }\n const key = this.getKey();\n if (tile && tile.key == key) {\n return tile;\n }\n const sourceTileGrid = this.getTileGridForProjection(sourceProjection);\n const targetTileGrid = this.getTileGridForProjection(projection);\n const wrappedTileCoord = this.getTileCoordForTileUrlFunction(\n tileCoord,\n projection\n );\n const newTile = new ReprojTile(\n sourceProjection,\n sourceTileGrid,\n projection,\n targetTileGrid,\n tileCoord,\n wrappedTileCoord,\n this.getTilePixelRatio(pixelRatio),\n this.getGutter(),\n (z, x, y, pixelRatio) =>\n this.getTileInternal(z, x, y, pixelRatio, sourceProjection),\n this.reprojectionErrorThreshold_,\n this.renderReprojectionEdges_,\n this.getInterpolate()\n );\n newTile.key = key;\n\n if (tile) {\n newTile.interimTile = tile;\n newTile.refreshInterimChain();\n cache.replace(tileCoordKey, newTile);\n } else {\n cache.set(tileCoordKey, newTile);\n }\n return newTile;\n }\n\n /**\n * @param {number} z Tile coordinate z.\n * @param {number} x Tile coordinate x.\n * @param {number} y Tile coordinate y.\n * @param {number} pixelRatio Pixel ratio.\n * @param {!import(\"../proj/Projection.js\").default} projection Projection.\n * @return {!ImageTile} Tile.\n * @protected\n */\n getTileInternal(z, x, y, pixelRatio, projection) {\n let tile = null;\n const tileCoordKey = getKeyZXY(z, x, y);\n const key = this.getKey();\n if (!this.tileCache.containsKey(tileCoordKey)) {\n tile = this.createTile_(z, x, y, pixelRatio, projection, key);\n this.tileCache.set(tileCoordKey, tile);\n } else {\n tile = this.tileCache.get(tileCoordKey);\n if (tile.key != key) {\n // The source's params changed. If the tile has an interim tile and if we\n // can use it then we use it. Otherwise we create a new tile. In both\n // cases we attempt to assign an interim tile to the new tile.\n const interimTile = tile;\n tile = this.createTile_(z, x, y, pixelRatio, projection, key);\n\n //make the new tile the head of the list,\n if (interimTile.getState() == TileState.IDLE) {\n //the old tile hasn't begun loading yet, and is now outdated, so we can simply discard it\n tile.interimTile = interimTile.interimTile;\n } else {\n tile.interimTile = interimTile;\n }\n tile.refreshInterimChain();\n this.tileCache.replace(tileCoordKey, tile);\n }\n }\n return tile;\n }\n\n /**\n * Sets whether to render reprojection edges or not (usually for debugging).\n * @param {boolean} render Render the edges.\n * @api\n */\n setRenderReprojectionEdges(render) {\n if (this.renderReprojectionEdges_ == render) {\n return;\n }\n this.renderReprojectionEdges_ = render;\n for (const id in this.tileCacheForProjection) {\n this.tileCacheForProjection[id].clear();\n }\n this.changed();\n }\n\n /**\n * Sets the tile grid to use when reprojecting the tiles to the given\n * projection instead of the default tile grid for the projection.\n *\n * This can be useful when the default tile grid cannot be created\n * (e.g. projection has no extent defined) or\n * for optimization reasons (custom tile size, resolutions, ...).\n *\n * @param {import(\"../proj.js\").ProjectionLike} projection Projection.\n * @param {import(\"../tilegrid/TileGrid.js\").default} tilegrid Tile grid to use for the projection.\n * @api\n */\n setTileGridForProjection(projection, tilegrid) {\n const proj = getProjection(projection);\n if (proj) {\n const projKey = getUid(proj);\n if (!(projKey in this.tileGridForProjection)) {\n this.tileGridForProjection[projKey] = tilegrid;\n }\n }\n }\n\n clear() {\n super.clear();\n for (const id in this.tileCacheForProjection) {\n this.tileCacheForProjection[id].clear();\n }\n }\n}\n\n/**\n * @param {ImageTile} imageTile Image tile.\n * @param {string} src Source.\n */\nfunction defaultTileLoadFunction(imageTile, src) {\n /** @type {HTMLImageElement|HTMLVideoElement} */ (imageTile.getImage()).src =\n src;\n}\n\nexport default TileImage;\n","/**\n * @module ol/source/BingMaps\n */\n\nimport TileImage from './TileImage.js';\nimport {applyTransform, intersects} from '../extent.js';\nimport {createFromTileUrlFunctions} from '../tileurlfunction.js';\nimport {createOrUpdate} from '../tilecoord.js';\nimport {createXYZ, extentFromProjection} from '../tilegrid.js';\nimport {get as getProjection, getTransformFromProjections} from '../proj.js';\n\n/**\n * @param {import('../tilecoord.js').TileCoord} tileCoord Tile coord.\n * @return {string} Quad key.\n */\nexport function quadKey(tileCoord) {\n const z = tileCoord[0];\n const digits = new Array(z);\n let mask = 1 << (z - 1);\n let i, charCode;\n for (i = 0; i < z; ++i) {\n // 48 is charCode for 0 - '0'.charCodeAt(0)\n charCode = 48;\n if (tileCoord[1] & mask) {\n charCode += 1;\n }\n if (tileCoord[2] & mask) {\n charCode += 2;\n }\n digits[i] = String.fromCharCode(charCode);\n mask >>= 1;\n }\n return digits.join('');\n}\n\n/**\n * The attribution containing a link to the Microsoft® Bing™ Maps Platform APIs’\n * Terms Of Use.\n * @const\n * @type {string}\n */\nconst TOS_ATTRIBUTION =\n '' +\n 'Terms of Use';\n\n/**\n * @typedef {Object} Options\n * @property {number} [cacheSize] Initial tile cache size. Will auto-grow to hold at least the number of tiles in the viewport.\n * @property {boolean} [hidpi=false] If `true` hidpi tiles will be requested.\n * @property {string} [culture='en-us'] Culture code.\n * @property {string} key Bing Maps API key. Get yours at https://www.bingmapsportal.com/.\n * @property {string} imagerySet Type of imagery.\n * @property {boolean} [interpolate=true] Use interpolated values when resampling. By default,\n * linear interpolation is used when resampling. Set to false to use the nearest neighbor instead.\n * @property {number} [maxZoom=21] Max zoom. Default is what's advertized by the BingMaps service.\n * @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).\n * Higher values can increase reprojection performance, but decrease precision.\n * @property {import(\"../Tile.js\").LoadFunction} [tileLoadFunction] Optional function to load a tile given a URL. The default is\n * ```js\n * function(imageTile, src) {\n * imageTile.getImage().src = src;\n * };\n * ```\n * @property {boolean} [wrapX=true] Whether to wrap the world horizontally.\n * @property {number} [transition] Duration of the opacity transition for rendering.\n * To disable the opacity transition, pass `transition: 0`.\n * @property {number|import(\"../array.js\").NearestDirectionFunction} [zDirection=0]\n * Choose whether to use tiles with a higher or lower zoom level when between integer\n * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.\n * @property {boolean} placeholderTiles Whether to show BingMaps placeholder tiles when zoomed past the maximum level provided in an area. When `false`, requests beyond\n * the maximum zoom level will return no tile. When `true`, the placeholder tile will be returned.\n */\n\n/**\n * @typedef {Object} BingMapsImageryMetadataResponse\n * @property {number} statusCode The response status code\n * @property {string} statusDescription The response status description\n * @property {string} authenticationResultCode The authentication result code\n * @property {Array} resourceSets The array of resource sets\n */\n\n/**\n * @typedef {Object} ResourceSet\n * @property {Array} resources Resources.\n */\n\n/**\n * @typedef {Object} Resource\n * @property {number} imageHeight The image height\n * @property {number} imageWidth The image width\n * @property {number} zoomMin The minimum zoom level\n * @property {number} zoomMax The maximum zoom level\n * @property {string} imageUrl The image URL\n * @property {Array} imageUrlSubdomains The image URL subdomains for rotation\n * @property {Array} [imageryProviders] The array of ImageryProviders\n */\n\n/**\n * @typedef {Object} ImageryProvider\n * @property {Array} coverageAreas The coverage areas\n * @property {string} [attribution] The attribution\n */\n\n/**\n * @typedef {Object} CoverageArea\n * @property {number} zoomMin The minimum zoom\n * @property {number} zoomMax The maximum zoom\n * @property {Array} bbox The coverage bounding box\n */\n\n/**\n * @classdesc\n * Layer source for Bing Maps tile data.\n * @api\n */\nclass BingMaps extends TileImage {\n /**\n * @param {Options} options Bing Maps options.\n */\n constructor(options) {\n const hidpi = options.hidpi !== undefined ? options.hidpi : false;\n\n super({\n cacheSize: options.cacheSize,\n crossOrigin: 'anonymous',\n interpolate: options.interpolate,\n opaque: true,\n projection: getProjection('EPSG:3857'),\n reprojectionErrorThreshold: options.reprojectionErrorThreshold,\n state: 'loading',\n tileLoadFunction: options.tileLoadFunction,\n tilePixelRatio: hidpi ? 2 : 1,\n wrapX: options.wrapX !== undefined ? options.wrapX : true,\n transition: options.transition,\n zDirection: options.zDirection,\n });\n\n /**\n * @private\n * @type {boolean}\n */\n this.hidpi_ = hidpi;\n\n /**\n * @private\n * @type {string}\n */\n this.culture_ = options.culture !== undefined ? options.culture : 'en-us';\n\n /**\n * @private\n * @type {number}\n */\n this.maxZoom_ = options.maxZoom !== undefined ? options.maxZoom : -1;\n\n /**\n * @private\n * @type {string}\n */\n this.apiKey_ = options.key;\n\n /**\n * @private\n * @type {string}\n */\n this.imagerySet_ = options.imagerySet;\n\n /**\n * @private\n * @type {boolean}\n */\n this.placeholderTiles_ = options.placeholderTiles;\n\n const url =\n 'https://dev.virtualearth.net/REST/v1/Imagery/Metadata/' +\n this.imagerySet_ +\n '?uriScheme=https&include=ImageryProviders&key=' +\n this.apiKey_ +\n '&c=' +\n this.culture_;\n\n fetch(url)\n .then((response) => response.json())\n .then((json) => this.handleImageryMetadataResponse(json));\n }\n\n /**\n * Get the api key used for this source.\n *\n * @return {string} The api key.\n * @api\n */\n getApiKey() {\n return this.apiKey_;\n }\n\n /**\n * Get the imagery set associated with this source.\n *\n * @return {string} The imagery set.\n * @api\n */\n getImagerySet() {\n return this.imagerySet_;\n }\n\n /**\n * @param {BingMapsImageryMetadataResponse} response Response.\n */\n handleImageryMetadataResponse(response) {\n if (\n response.statusCode != 200 ||\n response.statusDescription != 'OK' ||\n response.authenticationResultCode != 'ValidCredentials' ||\n response.resourceSets.length != 1 ||\n response.resourceSets[0].resources.length != 1\n ) {\n this.setState('error');\n return;\n }\n\n const resource = response.resourceSets[0].resources[0];\n const maxZoom = this.maxZoom_ == -1 ? resource.zoomMax : this.maxZoom_;\n\n const sourceProjection = this.getProjection();\n const extent = extentFromProjection(sourceProjection);\n const scale = this.hidpi_ ? 2 : 1;\n const tileSize =\n resource.imageWidth == resource.imageHeight\n ? resource.imageWidth / scale\n : [resource.imageWidth / scale, resource.imageHeight / scale];\n\n const tileGrid = createXYZ({\n extent: extent,\n minZoom: resource.zoomMin,\n maxZoom: maxZoom,\n tileSize: tileSize,\n });\n this.tileGrid = tileGrid;\n\n const culture = this.culture_;\n const hidpi = this.hidpi_;\n const placeholderTiles = this.placeholderTiles_;\n this.tileUrlFunction = createFromTileUrlFunctions(\n resource.imageUrlSubdomains.map(function (subdomain) {\n /** @type {import('../tilecoord.js').TileCoord} */\n const quadKeyTileCoord = [0, 0, 0];\n const imageUrl = resource.imageUrl\n .replace('{subdomain}', subdomain)\n .replace('{culture}', culture);\n return (\n /**\n * @param {import(\"../tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {string|undefined} Tile URL.\n */\n function (tileCoord, pixelRatio, projection) {\n if (!tileCoord) {\n return undefined;\n }\n createOrUpdate(\n tileCoord[0],\n tileCoord[1],\n tileCoord[2],\n quadKeyTileCoord\n );\n const url = new URL(\n imageUrl.replace('{quadkey}', quadKey(quadKeyTileCoord))\n );\n const params = url.searchParams;\n if (hidpi) {\n params.set('dpi', 'd1');\n params.set('device', 'mobile');\n }\n if (placeholderTiles === true) {\n params.delete('n');\n } else if (placeholderTiles === false) {\n params.set('n', 'z');\n }\n return url.toString();\n }\n );\n })\n );\n\n if (resource.imageryProviders) {\n const transform = getTransformFromProjections(\n getProjection('EPSG:4326'),\n this.getProjection()\n );\n\n this.setAttributions((frameState) => {\n const attributions = [];\n const viewState = frameState.viewState;\n const tileGrid = this.getTileGrid();\n const z = tileGrid.getZForResolution(\n viewState.resolution,\n this.zDirection\n );\n const tileCoord = tileGrid.getTileCoordForCoordAndZ(\n viewState.center,\n z\n );\n const zoom = tileCoord[0];\n resource.imageryProviders.map(function (imageryProvider) {\n let intersecting = false;\n const coverageAreas = imageryProvider.coverageAreas;\n for (let i = 0, ii = coverageAreas.length; i < ii; ++i) {\n const coverageArea = coverageAreas[i];\n if (zoom >= coverageArea.zoomMin && zoom <= coverageArea.zoomMax) {\n const bbox = coverageArea.bbox;\n const epsg4326Extent = [bbox[1], bbox[0], bbox[3], bbox[2]];\n const extent = applyTransform(epsg4326Extent, transform);\n if (intersects(extent, frameState.extent)) {\n intersecting = true;\n break;\n }\n }\n }\n if (intersecting) {\n attributions.push(imageryProvider.attribution);\n }\n });\n\n attributions.push(TOS_ATTRIBUTION);\n return attributions;\n });\n }\n\n this.setState('ready');\n }\n}\n\nexport default BingMaps;\n","/**\n * @module ol/source/XYZ\n */\n\nimport TileImage from './TileImage.js';\nimport {createXYZ, extentFromProjection} from '../tilegrid.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.\n * @property {number} [cacheSize] Initial tile cache size. Will auto-grow to hold at least the number of tiles in the viewport.\n * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images. Note that\n * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.\n * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.\n * @property {boolean} [interpolate=true] Use interpolated values when resampling. By default,\n * linear interpolation is used when resampling. Set to false to use the nearest neighbor instead.\n * @property {boolean} [opaque=false] Whether the layer is opaque.\n * @property {import(\"../proj.js\").ProjectionLike} [projection='EPSG:3857'] Projection.\n * @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).\n * Higher values can increase reprojection performance, but decrease precision.\n * @property {number} [maxZoom=42] Optional max zoom level. Not used if `tileGrid` is provided.\n * @property {number} [minZoom=0] Optional min zoom level. Not used if `tileGrid` is provided.\n * @property {number} [maxResolution] Optional tile grid resolution at level zero. Not used if `tileGrid` is provided.\n * @property {import(\"../tilegrid/TileGrid.js\").default} [tileGrid] Tile grid.\n * @property {import(\"../Tile.js\").LoadFunction} [tileLoadFunction] Optional function to load a tile given a URL. The default is\n * ```js\n * function(imageTile, src) {\n * imageTile.getImage().src = src;\n * };\n * ```\n * @property {number} [tilePixelRatio=1] The pixel ratio used by the tile service.\n * For example, if the tile service advertizes 256px by 256px tiles but actually sends 512px\n * by 512px images (for retina/hidpi devices) then `tilePixelRatio`\n * should be set to `2`.\n * @property {number|import(\"../size.js\").Size} [tileSize=[256, 256]] The tile size used by the tile service.\n * Not used if `tileGrid` is provided.\n * @property {number} [gutter=0] The size in pixels of the gutter around image tiles to ignore.\n * This allows artifacts of rendering at tile edges to be ignored.\n * Supported images should be wider and taller than the tile size by a value of `2 x gutter`.\n * @property {import(\"../Tile.js\").UrlFunction} [tileUrlFunction] Optional function to get\n * tile URL given a tile coordinate and the projection.\n * Required if `url` or `urls` are not provided.\n * @property {string} [url] URL template. Must include `{x}`, `{y}` or `{-y}`,\n * and `{z}` placeholders. A `{?-?}` template pattern, for example `subdomain{a-f}.domain.com`,\n * may be used instead of defining each one separately in the `urls` option.\n * @property {Array} [urls] An array of URL templates.\n * @property {boolean} [wrapX=true] Whether to wrap the world horizontally.\n * @property {number} [transition=250] Duration of the opacity transition for rendering.\n * To disable the opacity transition, pass `transition: 0`.\n * @property {number|import(\"../array.js\").NearestDirectionFunction} [zDirection=0]\n * Choose whether to use tiles with a higher or lower zoom level when between integer\n * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.\n */\n\n/**\n * @classdesc\n * Layer source for tile data with URLs in a set XYZ format that are\n * defined in a URL template. By default, this follows the widely-used\n * Google grid where `x` 0 and `y` 0 are in the top left. Grids like\n * TMS where `x` 0 and `y` 0 are in the bottom left can be used by\n * using the `{-y}` placeholder in the URL template, so long as the\n * source does not have a custom tile grid. In this case\n * a `tileUrlFunction` can be used, such as:\n * ```js\n * tileUrlFunction: function(coordinate) {\n * return 'http://mapserver.com/' + coordinate[0] + '/' +\n * coordinate[1] + '/' + (-coordinate[2] - 1) + '.png';\n * }\n * ```\n * @api\n */\nclass XYZ extends TileImage {\n /**\n * @param {Options} [options] XYZ options.\n */\n constructor(options) {\n options = options || {};\n\n const projection =\n options.projection !== undefined ? options.projection : 'EPSG:3857';\n\n const tileGrid =\n options.tileGrid !== undefined\n ? options.tileGrid\n : createXYZ({\n extent: extentFromProjection(projection),\n maxResolution: options.maxResolution,\n maxZoom: options.maxZoom,\n minZoom: options.minZoom,\n tileSize: options.tileSize,\n });\n\n super({\n attributions: options.attributions,\n cacheSize: options.cacheSize,\n crossOrigin: options.crossOrigin,\n interpolate: options.interpolate,\n opaque: options.opaque,\n projection: projection,\n reprojectionErrorThreshold: options.reprojectionErrorThreshold,\n tileGrid: tileGrid,\n tileLoadFunction: options.tileLoadFunction,\n tilePixelRatio: options.tilePixelRatio,\n tileUrlFunction: options.tileUrlFunction,\n url: options.url,\n urls: options.urls,\n wrapX: options.wrapX !== undefined ? options.wrapX : true,\n transition: options.transition,\n attributionsCollapsible: options.attributionsCollapsible,\n zDirection: options.zDirection,\n });\n\n /**\n * @private\n * @type {number}\n */\n this.gutter_ = options.gutter !== undefined ? options.gutter : 0;\n }\n\n /**\n * @return {number} Gutter.\n */\n getGutter() {\n return this.gutter_;\n }\n}\n\nexport default XYZ;\n","/**\n * @module ol/source/CartoDB\n */\n\nimport XYZ from './XYZ.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {number} [cacheSize] Initial tile cache size. Will auto-grow to hold at least the number of tiles in the viewport.\n * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images. Note that\n * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.\n * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.\n * @property {import(\"../proj.js\").ProjectionLike} [projection='EPSG:3857'] Projection.\n * @property {number} [maxZoom=18] Max zoom.\n * @property {number} [minZoom] Minimum zoom.\n * @property {boolean} [wrapX=true] Whether to wrap the world horizontally.\n * @property {Object} [config] If using anonymous maps, the CartoDB config to use. See\n * https://carto.com/developers/maps-api/guides/anonymous-maps/\n * for more detail.\n * If using named maps, a key-value lookup with the template parameters.\n * See https://carto.com/developers/maps-api/guides/named-maps/\n * for more detail.\n * @property {string} [map] If using named maps, this will be the name of the template to load.\n * See https://carto.com/developers/maps-api/guides/named-maps/\n * for more detail.\n * @property {string} [account] Username as used to access public Carto dashboard at https://{username}.carto.com/.\n * @property {number} [transition=250] Duration of the opacity transition for rendering.\n * To disable the opacity transition, pass `transition: 0`.\n * @property {number|import(\"../array.js\").NearestDirectionFunction} [zDirection=0]\n * Choose whether to use tiles with a higher or lower zoom level when between integer\n * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.\n */\n\n/**\n * @typedef {Object} CartoDBLayerInfo\n * @property {string} layergroupid The layer group ID\n * @property {{https: string}} cdn_url The CDN URL\n */\n\n/**\n * @classdesc\n * Layer source for the CartoDB Maps API.\n * @api\n */\nclass CartoDB extends XYZ {\n /**\n * @param {Options} options CartoDB options.\n */\n constructor(options) {\n super({\n attributions: options.attributions,\n cacheSize: options.cacheSize,\n crossOrigin: options.crossOrigin,\n maxZoom: options.maxZoom !== undefined ? options.maxZoom : 18,\n minZoom: options.minZoom,\n projection: options.projection,\n transition: options.transition,\n wrapX: options.wrapX,\n zDirection: options.zDirection,\n });\n\n /**\n * @type {string}\n * @private\n */\n this.account_ = options.account;\n\n /**\n * @type {string}\n * @private\n */\n this.mapId_ = options.map || '';\n\n /**\n * @type {!Object}\n * @private\n */\n this.config_ = options.config || {};\n\n /**\n * @type {!Object}\n * @private\n */\n this.templateCache_ = {};\n\n this.initializeMap_();\n }\n\n /**\n * Returns the current config.\n * @return {!Object} The current configuration.\n * @api\n */\n getConfig() {\n return this.config_;\n }\n\n /**\n * Updates the carto db config.\n * @param {Object} config a key-value lookup. Values will replace current values\n * in the config.\n * @api\n */\n updateConfig(config) {\n Object.assign(this.config_, config);\n this.initializeMap_();\n }\n\n /**\n * Sets the CartoDB config\n * @param {Object} config In the case of anonymous maps, a CartoDB configuration\n * object.\n * If using named maps, a key-value lookup with the template parameters.\n * @api\n */\n setConfig(config) {\n this.config_ = config || {};\n this.initializeMap_();\n }\n\n /**\n * Issue a request to initialize the CartoDB map.\n * @private\n */\n initializeMap_() {\n const paramHash = JSON.stringify(this.config_);\n if (this.templateCache_[paramHash]) {\n this.applyTemplate_(this.templateCache_[paramHash]);\n return;\n }\n let mapUrl = 'https://' + this.account_ + '.carto.com/api/v1/map';\n\n if (this.mapId_) {\n mapUrl += '/named/' + this.mapId_;\n }\n\n const client = new XMLHttpRequest();\n client.addEventListener(\n 'load',\n this.handleInitResponse_.bind(this, paramHash)\n );\n client.addEventListener('error', this.handleInitError_.bind(this));\n client.open('POST', mapUrl);\n client.setRequestHeader('Content-type', 'application/json');\n client.send(JSON.stringify(this.config_));\n }\n\n /**\n * Handle map initialization response.\n * @param {string} paramHash a hash representing the parameter set that was used\n * for the request\n * @param {Event} event Event.\n * @private\n */\n handleInitResponse_(paramHash, event) {\n const client = /** @type {XMLHttpRequest} */ (event.target);\n // status will be 0 for file:// urls\n if (!client.status || (client.status >= 200 && client.status < 300)) {\n let response;\n try {\n response = /** @type {CartoDBLayerInfo} */ (\n JSON.parse(client.responseText)\n );\n } catch (err) {\n this.setState('error');\n return;\n }\n this.applyTemplate_(response);\n this.templateCache_[paramHash] = response;\n this.setState('ready');\n } else {\n this.setState('error');\n }\n }\n\n /**\n * @private\n * @param {Event} event Event.\n */\n handleInitError_(event) {\n this.setState('error');\n }\n\n /**\n * Apply the new tile urls returned by carto db\n * @param {CartoDBLayerInfo} data Result of carto db call.\n * @private\n */\n applyTemplate_(data) {\n const tilesUrl =\n 'https://' +\n data.cdn_url.https +\n '/' +\n this.account_ +\n '/api/v1/map/' +\n data.layergroupid +\n '/{z}/{x}/{y}.png';\n this.setUrl(tilesUrl);\n }\n}\n\nexport default CartoDB;\n","\nexport default function quickselect(arr, k, left, right, compare) {\n quickselectStep(arr, k, left || 0, right || (arr.length - 1), compare || defaultCompare);\n}\n\nfunction quickselectStep(arr, k, left, right, compare) {\n\n while (right > left) {\n if (right - left > 600) {\n var n = right - left + 1;\n var m = k - left + 1;\n var z = Math.log(n);\n var s = 0.5 * Math.exp(2 * z / 3);\n var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);\n var newLeft = Math.max(left, Math.floor(k - m * s / n + sd));\n var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));\n quickselectStep(arr, k, newLeft, newRight, compare);\n }\n\n var t = arr[k];\n var i = left;\n var j = right;\n\n swap(arr, left, k);\n if (compare(arr[right], t) > 0) swap(arr, left, right);\n\n while (i < j) {\n swap(arr, i, j);\n i++;\n j--;\n while (compare(arr[i], t) < 0) i++;\n while (compare(arr[j], t) > 0) j--;\n }\n\n if (compare(arr[left], t) === 0) swap(arr, left, j);\n else {\n j++;\n swap(arr, j, right);\n }\n\n if (j <= k) left = j + 1;\n if (k <= j) right = j - 1;\n }\n}\n\nfunction swap(arr, i, j) {\n var tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n}\n\nfunction defaultCompare(a, b) {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n","import quickselect from 'quickselect';\n\nexport default class RBush {\n constructor(maxEntries = 9) {\n // max entries in a node is 9 by default; min node fill is 40% for best performance\n this._maxEntries = Math.max(4, maxEntries);\n this._minEntries = Math.max(2, Math.ceil(this._maxEntries * 0.4));\n this.clear();\n }\n\n all() {\n return this._all(this.data, []);\n }\n\n search(bbox) {\n let node = this.data;\n const result = [];\n\n if (!intersects(bbox, node)) return result;\n\n const toBBox = this.toBBox;\n const nodesToSearch = [];\n\n while (node) {\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i];\n const childBBox = node.leaf ? toBBox(child) : child;\n\n if (intersects(bbox, childBBox)) {\n if (node.leaf) result.push(child);\n else if (contains(bbox, childBBox)) this._all(child, result);\n else nodesToSearch.push(child);\n }\n }\n node = nodesToSearch.pop();\n }\n\n return result;\n }\n\n collides(bbox) {\n let node = this.data;\n\n if (!intersects(bbox, node)) return false;\n\n const nodesToSearch = [];\n while (node) {\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i];\n const childBBox = node.leaf ? this.toBBox(child) : child;\n\n if (intersects(bbox, childBBox)) {\n if (node.leaf || contains(bbox, childBBox)) return true;\n nodesToSearch.push(child);\n }\n }\n node = nodesToSearch.pop();\n }\n\n return false;\n }\n\n load(data) {\n if (!(data && data.length)) return this;\n\n if (data.length < this._minEntries) {\n for (let i = 0; i < data.length; i++) {\n this.insert(data[i]);\n }\n return this;\n }\n\n // recursively build the tree with the given data from scratch using OMT algorithm\n let node = this._build(data.slice(), 0, data.length - 1, 0);\n\n if (!this.data.children.length) {\n // save as is if tree is empty\n this.data = node;\n\n } else if (this.data.height === node.height) {\n // split root if trees have the same height\n this._splitRoot(this.data, node);\n\n } else {\n if (this.data.height < node.height) {\n // swap trees if inserted one is bigger\n const tmpNode = this.data;\n this.data = node;\n node = tmpNode;\n }\n\n // insert the small tree into the large tree at appropriate level\n this._insert(node, this.data.height - node.height - 1, true);\n }\n\n return this;\n }\n\n insert(item) {\n if (item) this._insert(item, this.data.height - 1);\n return this;\n }\n\n clear() {\n this.data = createNode([]);\n return this;\n }\n\n remove(item, equalsFn) {\n if (!item) return this;\n\n let node = this.data;\n const bbox = this.toBBox(item);\n const path = [];\n const indexes = [];\n let i, parent, goingUp;\n\n // depth-first iterative tree traversal\n while (node || path.length) {\n\n if (!node) { // go up\n node = path.pop();\n parent = path[path.length - 1];\n i = indexes.pop();\n goingUp = true;\n }\n\n if (node.leaf) { // check current node\n const index = findItem(item, node.children, equalsFn);\n\n if (index !== -1) {\n // item found, remove the item and condense tree upwards\n node.children.splice(index, 1);\n path.push(node);\n this._condense(path);\n return this;\n }\n }\n\n if (!goingUp && !node.leaf && contains(node, bbox)) { // go down\n path.push(node);\n indexes.push(i);\n i = 0;\n parent = node;\n node = node.children[0];\n\n } else if (parent) { // go right\n i++;\n node = parent.children[i];\n goingUp = false;\n\n } else node = null; // nothing found\n }\n\n return this;\n }\n\n toBBox(item) { return item; }\n\n compareMinX(a, b) { return a.minX - b.minX; }\n compareMinY(a, b) { return a.minY - b.minY; }\n\n toJSON() { return this.data; }\n\n fromJSON(data) {\n this.data = data;\n return this;\n }\n\n _all(node, result) {\n const nodesToSearch = [];\n while (node) {\n if (node.leaf) result.push(...node.children);\n else nodesToSearch.push(...node.children);\n\n node = nodesToSearch.pop();\n }\n return result;\n }\n\n _build(items, left, right, height) {\n\n const N = right - left + 1;\n let M = this._maxEntries;\n let node;\n\n if (N <= M) {\n // reached leaf level; return leaf\n node = createNode(items.slice(left, right + 1));\n calcBBox(node, this.toBBox);\n return node;\n }\n\n if (!height) {\n // target height of the bulk-loaded tree\n height = Math.ceil(Math.log(N) / Math.log(M));\n\n // target number of root entries to maximize storage utilization\n M = Math.ceil(N / Math.pow(M, height - 1));\n }\n\n node = createNode([]);\n node.leaf = false;\n node.height = height;\n\n // split the items into M mostly square tiles\n\n const N2 = Math.ceil(N / M);\n const N1 = N2 * Math.ceil(Math.sqrt(M));\n\n multiSelect(items, left, right, N1, this.compareMinX);\n\n for (let i = left; i <= right; i += N1) {\n\n const right2 = Math.min(i + N1 - 1, right);\n\n multiSelect(items, i, right2, N2, this.compareMinY);\n\n for (let j = i; j <= right2; j += N2) {\n\n const right3 = Math.min(j + N2 - 1, right2);\n\n // pack each entry recursively\n node.children.push(this._build(items, j, right3, height - 1));\n }\n }\n\n calcBBox(node, this.toBBox);\n\n return node;\n }\n\n _chooseSubtree(bbox, node, level, path) {\n while (true) {\n path.push(node);\n\n if (node.leaf || path.length - 1 === level) break;\n\n let minArea = Infinity;\n let minEnlargement = Infinity;\n let targetNode;\n\n for (let i = 0; i < node.children.length; i++) {\n const child = node.children[i];\n const area = bboxArea(child);\n const enlargement = enlargedArea(bbox, child) - area;\n\n // choose entry with the least area enlargement\n if (enlargement < minEnlargement) {\n minEnlargement = enlargement;\n minArea = area < minArea ? area : minArea;\n targetNode = child;\n\n } else if (enlargement === minEnlargement) {\n // otherwise choose one with the smallest area\n if (area < minArea) {\n minArea = area;\n targetNode = child;\n }\n }\n }\n\n node = targetNode || node.children[0];\n }\n\n return node;\n }\n\n _insert(item, level, isNode) {\n const bbox = isNode ? item : this.toBBox(item);\n const insertPath = [];\n\n // find the best node for accommodating the item, saving all nodes along the path too\n const node = this._chooseSubtree(bbox, this.data, level, insertPath);\n\n // put the item into the node\n node.children.push(item);\n extend(node, bbox);\n\n // split on node overflow; propagate upwards if necessary\n while (level >= 0) {\n if (insertPath[level].children.length > this._maxEntries) {\n this._split(insertPath, level);\n level--;\n } else break;\n }\n\n // adjust bboxes along the insertion path\n this._adjustParentBBoxes(bbox, insertPath, level);\n }\n\n // split overflowed node into two\n _split(insertPath, level) {\n const node = insertPath[level];\n const M = node.children.length;\n const m = this._minEntries;\n\n this._chooseSplitAxis(node, m, M);\n\n const splitIndex = this._chooseSplitIndex(node, m, M);\n\n const newNode = createNode(node.children.splice(splitIndex, node.children.length - splitIndex));\n newNode.height = node.height;\n newNode.leaf = node.leaf;\n\n calcBBox(node, this.toBBox);\n calcBBox(newNode, this.toBBox);\n\n if (level) insertPath[level - 1].children.push(newNode);\n else this._splitRoot(node, newNode);\n }\n\n _splitRoot(node, newNode) {\n // split root node\n this.data = createNode([node, newNode]);\n this.data.height = node.height + 1;\n this.data.leaf = false;\n calcBBox(this.data, this.toBBox);\n }\n\n _chooseSplitIndex(node, m, M) {\n let index;\n let minOverlap = Infinity;\n let minArea = Infinity;\n\n for (let i = m; i <= M - m; i++) {\n const bbox1 = distBBox(node, 0, i, this.toBBox);\n const bbox2 = distBBox(node, i, M, this.toBBox);\n\n const overlap = intersectionArea(bbox1, bbox2);\n const area = bboxArea(bbox1) + bboxArea(bbox2);\n\n // choose distribution with minimum overlap\n if (overlap < minOverlap) {\n minOverlap = overlap;\n index = i;\n\n minArea = area < minArea ? area : minArea;\n\n } else if (overlap === minOverlap) {\n // otherwise choose distribution with minimum area\n if (area < minArea) {\n minArea = area;\n index = i;\n }\n }\n }\n\n return index || M - m;\n }\n\n // sorts node children by the best axis for split\n _chooseSplitAxis(node, m, M) {\n const compareMinX = node.leaf ? this.compareMinX : compareNodeMinX;\n const compareMinY = node.leaf ? this.compareMinY : compareNodeMinY;\n const xMargin = this._allDistMargin(node, m, M, compareMinX);\n const yMargin = this._allDistMargin(node, m, M, compareMinY);\n\n // if total distributions margin value is minimal for x, sort by minX,\n // otherwise it's already sorted by minY\n if (xMargin < yMargin) node.children.sort(compareMinX);\n }\n\n // total margin of all possible split distributions where each node is at least m full\n _allDistMargin(node, m, M, compare) {\n node.children.sort(compare);\n\n const toBBox = this.toBBox;\n const leftBBox = distBBox(node, 0, m, toBBox);\n const rightBBox = distBBox(node, M - m, M, toBBox);\n let margin = bboxMargin(leftBBox) + bboxMargin(rightBBox);\n\n for (let i = m; i < M - m; i++) {\n const child = node.children[i];\n extend(leftBBox, node.leaf ? toBBox(child) : child);\n margin += bboxMargin(leftBBox);\n }\n\n for (let i = M - m - 1; i >= m; i--) {\n const child = node.children[i];\n extend(rightBBox, node.leaf ? toBBox(child) : child);\n margin += bboxMargin(rightBBox);\n }\n\n return margin;\n }\n\n _adjustParentBBoxes(bbox, path, level) {\n // adjust bboxes along the given tree path\n for (let i = level; i >= 0; i--) {\n extend(path[i], bbox);\n }\n }\n\n _condense(path) {\n // go through the path, removing empty nodes and updating bboxes\n for (let i = path.length - 1, siblings; i >= 0; i--) {\n if (path[i].children.length === 0) {\n if (i > 0) {\n siblings = path[i - 1].children;\n siblings.splice(siblings.indexOf(path[i]), 1);\n\n } else this.clear();\n\n } else calcBBox(path[i], this.toBBox);\n }\n }\n}\n\nfunction findItem(item, items, equalsFn) {\n if (!equalsFn) return items.indexOf(item);\n\n for (let i = 0; i < items.length; i++) {\n if (equalsFn(item, items[i])) return i;\n }\n return -1;\n}\n\n// calculate node's bbox from bboxes of its children\nfunction calcBBox(node, toBBox) {\n distBBox(node, 0, node.children.length, toBBox, node);\n}\n\n// min bounding rectangle of node children from k to p-1\nfunction distBBox(node, k, p, toBBox, destNode) {\n if (!destNode) destNode = createNode(null);\n destNode.minX = Infinity;\n destNode.minY = Infinity;\n destNode.maxX = -Infinity;\n destNode.maxY = -Infinity;\n\n for (let i = k; i < p; i++) {\n const child = node.children[i];\n extend(destNode, node.leaf ? toBBox(child) : child);\n }\n\n return destNode;\n}\n\nfunction extend(a, b) {\n a.minX = Math.min(a.minX, b.minX);\n a.minY = Math.min(a.minY, b.minY);\n a.maxX = Math.max(a.maxX, b.maxX);\n a.maxY = Math.max(a.maxY, b.maxY);\n return a;\n}\n\nfunction compareNodeMinX(a, b) { return a.minX - b.minX; }\nfunction compareNodeMinY(a, b) { return a.minY - b.minY; }\n\nfunction bboxArea(a) { return (a.maxX - a.minX) * (a.maxY - a.minY); }\nfunction bboxMargin(a) { return (a.maxX - a.minX) + (a.maxY - a.minY); }\n\nfunction enlargedArea(a, b) {\n return (Math.max(b.maxX, a.maxX) - Math.min(b.minX, a.minX)) *\n (Math.max(b.maxY, a.maxY) - Math.min(b.minY, a.minY));\n}\n\nfunction intersectionArea(a, b) {\n const minX = Math.max(a.minX, b.minX);\n const minY = Math.max(a.minY, b.minY);\n const maxX = Math.min(a.maxX, b.maxX);\n const maxY = Math.min(a.maxY, b.maxY);\n\n return Math.max(0, maxX - minX) *\n Math.max(0, maxY - minY);\n}\n\nfunction contains(a, b) {\n return a.minX <= b.minX &&\n a.minY <= b.minY &&\n b.maxX <= a.maxX &&\n b.maxY <= a.maxY;\n}\n\nfunction intersects(a, b) {\n return b.minX <= a.maxX &&\n b.minY <= a.maxY &&\n b.maxX >= a.minX &&\n b.maxY >= a.minY;\n}\n\nfunction createNode(children) {\n return {\n children,\n height: 1,\n leaf: true,\n minX: Infinity,\n minY: Infinity,\n maxX: -Infinity,\n maxY: -Infinity\n };\n}\n\n// sort an array so that items come in groups of n unsorted items, with groups sorted between each other;\n// combines selection algorithm with binary divide & conquer approach\n\nfunction multiSelect(arr, left, right, n, compare) {\n const stack = [left, right];\n\n while (stack.length) {\n right = stack.pop();\n left = stack.pop();\n\n if (right - left <= n) continue;\n\n const mid = left + Math.ceil((right - left) / n / 2) * n;\n quickselect(arr, mid, left, right, compare);\n\n stack.push(left, mid, mid, right);\n }\n}\n","/**\n * @module ol/structs/RBush\n */\nimport RBush_ from 'rbush';\nimport {createOrUpdate, equals} from '../extent.js';\nimport {getUid} from '../util.js';\nimport {isEmpty} from '../obj.js';\n\n/**\n * @typedef {Object} Entry\n * @property {number} minX MinX.\n * @property {number} minY MinY.\n * @property {number} maxX MaxX.\n * @property {number} maxY MaxY.\n * @property {Object} [value] Value.\n */\n\n/**\n * @classdesc\n * Wrapper around the RBush by Vladimir Agafonkin.\n * See https://github.com/mourner/rbush.\n *\n * @template T\n */\nclass RBush {\n /**\n * @param {number} [maxEntries] Max entries.\n */\n constructor(maxEntries) {\n /**\n * @private\n */\n this.rbush_ = new RBush_(maxEntries);\n\n /**\n * A mapping between the objects added to this rbush wrapper\n * and the objects that are actually added to the internal rbush.\n * @private\n * @type {Object}\n */\n this.items_ = {};\n }\n\n /**\n * Insert a value into the RBush.\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @param {T} value Value.\n */\n insert(extent, value) {\n /** @type {Entry} */\n const item = {\n minX: extent[0],\n minY: extent[1],\n maxX: extent[2],\n maxY: extent[3],\n value: value,\n };\n\n this.rbush_.insert(item);\n this.items_[getUid(value)] = item;\n }\n\n /**\n * Bulk-insert values into the RBush.\n * @param {Array} extents Extents.\n * @param {Array} values Values.\n */\n load(extents, values) {\n const items = new Array(values.length);\n for (let i = 0, l = values.length; i < l; i++) {\n const extent = extents[i];\n const value = values[i];\n\n /** @type {Entry} */\n const item = {\n minX: extent[0],\n minY: extent[1],\n maxX: extent[2],\n maxY: extent[3],\n value: value,\n };\n items[i] = item;\n this.items_[getUid(value)] = item;\n }\n this.rbush_.load(items);\n }\n\n /**\n * Remove a value from the RBush.\n * @param {T} value Value.\n * @return {boolean} Removed.\n */\n remove(value) {\n const uid = getUid(value);\n\n // get the object in which the value was wrapped when adding to the\n // internal rbush. then use that object to do the removal.\n const item = this.items_[uid];\n delete this.items_[uid];\n return this.rbush_.remove(item) !== null;\n }\n\n /**\n * Update the extent of a value in the RBush.\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @param {T} value Value.\n */\n update(extent, value) {\n const item = this.items_[getUid(value)];\n const bbox = [item.minX, item.minY, item.maxX, item.maxY];\n if (!equals(bbox, extent)) {\n this.remove(value);\n this.insert(extent, value);\n }\n }\n\n /**\n * Return all values in the RBush.\n * @return {Array} All.\n */\n getAll() {\n const items = this.rbush_.all();\n return items.map(function (item) {\n return item.value;\n });\n }\n\n /**\n * Return all values in the given extent.\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @return {Array} All in extent.\n */\n getInExtent(extent) {\n /** @type {Entry} */\n const bbox = {\n minX: extent[0],\n minY: extent[1],\n maxX: extent[2],\n maxY: extent[3],\n };\n const items = this.rbush_.search(bbox);\n return items.map(function (item) {\n return item.value;\n });\n }\n\n /**\n * Calls a callback function with each value in the tree.\n * If the callback returns a truthy value, this value is returned without\n * checking the rest of the tree.\n * @param {function(T): *} callback Callback.\n * @return {*} Callback return value.\n */\n forEach(callback) {\n return this.forEach_(this.getAll(), callback);\n }\n\n /**\n * Calls a callback function with each value in the provided extent.\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @param {function(T): *} callback Callback.\n * @return {*} Callback return value.\n */\n forEachInExtent(extent, callback) {\n return this.forEach_(this.getInExtent(extent), callback);\n }\n\n /**\n * @param {Array} values Values.\n * @param {function(T): *} callback Callback.\n * @private\n * @return {*} Callback return value.\n */\n forEach_(values, callback) {\n let result;\n for (let i = 0, l = values.length; i < l; i++) {\n result = callback(values[i]);\n if (result) {\n return result;\n }\n }\n return result;\n }\n\n /**\n * @return {boolean} Is empty.\n */\n isEmpty() {\n return isEmpty(this.items_);\n }\n\n /**\n * Remove all values from the RBush.\n */\n clear() {\n this.rbush_.clear();\n this.items_ = {};\n }\n\n /**\n * @param {import(\"../extent.js\").Extent} [extent] Extent.\n * @return {import(\"../extent.js\").Extent} Extent.\n */\n getExtent(extent) {\n const data = this.rbush_.toJSON();\n return createOrUpdate(data.minX, data.minY, data.maxX, data.maxY, extent);\n }\n\n /**\n * @param {RBush} rbush R-Tree.\n */\n concat(rbush) {\n this.rbush_.load(rbush.rbush_.all());\n for (const i in rbush.items_) {\n this.items_[i] = rbush.items_[i];\n }\n }\n}\n\nexport default RBush;\n","/**\n * @module ol/source/VectorEventType\n */\n\n/**\n * @enum {string}\n */\nexport default {\n /**\n * Triggered when a feature is added to the source.\n * @event module:ol/source/Vector.VectorSourceEvent#addfeature\n * @api\n */\n ADDFEATURE: 'addfeature',\n\n /**\n * Triggered when a feature is updated.\n * @event module:ol/source/Vector.VectorSourceEvent#changefeature\n * @api\n */\n CHANGEFEATURE: 'changefeature',\n\n /**\n * Triggered when the clear method is called on the source.\n * @event module:ol/source/Vector.VectorSourceEvent#clear\n * @api\n */\n CLEAR: 'clear',\n\n /**\n * Triggered when a feature is removed from the source.\n * See {@link module:ol/source/Vector~VectorSource#clear source.clear()} for exceptions.\n * @event module:ol/source/Vector.VectorSourceEvent#removefeature\n * @api\n */\n REMOVEFEATURE: 'removefeature',\n\n /**\n * Triggered when features starts loading.\n * @event module:ol/source/Vector.VectorSourceEvent#featuresloadstart\n * @api\n */\n FEATURESLOADSTART: 'featuresloadstart',\n\n /**\n * Triggered when features finishes loading.\n * @event module:ol/source/Vector.VectorSourceEvent#featuresloadend\n * @api\n */\n FEATURESLOADEND: 'featuresloadend',\n\n /**\n * Triggered if feature loading results in an error.\n * @event module:ol/source/Vector.VectorSourceEvent#featuresloaderror\n * @api\n */\n FEATURESLOADERROR: 'featuresloaderror',\n};\n\n/**\n * @typedef {'addfeature'|'changefeature'|'clear'|'removefeature'|'featuresloadstart'|'featuresloadend'|'featuresloaderror'} VectorSourceEventTypes\n */\n","/**\n * @module ol/source/Vector\n */\n\nimport Collection from '../Collection.js';\nimport CollectionEventType from '../CollectionEventType.js';\nimport Event from '../events/Event.js';\nimport EventType from '../events/EventType.js';\nimport ObjectEventType from '../ObjectEventType.js';\nimport RBush from '../structs/RBush.js';\nimport Source from './Source.js';\nimport VectorEventType from './VectorEventType.js';\nimport {TRUE, VOID} from '../functions.js';\nimport {all as allStrategy} from '../loadingstrategy.js';\nimport {assert} from '../asserts.js';\nimport {containsExtent, equals, wrapAndSliceX} from '../extent.js';\nimport {extend} from '../array.js';\nimport {getUid} from '../util.js';\nimport {isEmpty} from '../obj.js';\nimport {listen, unlistenByKey} from '../events.js';\nimport {xhr} from '../featureloader.js';\n\n/**\n * A function that takes an {@link module:ol/extent~Extent} and a resolution as arguments, and\n * returns an array of {@link module:ol/extent~Extent} with the extents to load. Usually this\n * is one of the standard {@link module:ol/loadingstrategy} strategies.\n *\n * @typedef {function(import(\"../extent.js\").Extent, number, import(\"../proj/Projection.js\").default): Array} LoadingStrategy\n * @api\n */\n\n/**\n * @classdesc\n * Events emitted by {@link module:ol/source/Vector~VectorSource} instances are instances of this\n * type.\n * @template {import(\"../geom/Geometry.js\").default} [Geometry=import(\"../geom/Geometry.js\").default]\n */\nexport class VectorSourceEvent extends Event {\n /**\n * @param {string} type Type.\n * @param {import(\"../Feature.js\").default} [feature] Feature.\n * @param {Array>} [features] Features.\n */\n constructor(type, feature, features) {\n super(type);\n\n /**\n * The added or removed feature for the `ADDFEATURE` and `REMOVEFEATURE` events, `undefined` otherwise.\n * @type {import(\"../Feature.js\").default|undefined}\n * @api\n */\n this.feature = feature;\n\n /**\n * The loaded features for the `FEATURESLOADED` event, `undefined` otherwise.\n * @type {Array>|undefined}\n * @api\n */\n this.features = features;\n }\n}\n\n/***\n * @template Return\n * @typedef {import(\"../Observable\").OnSignature &\n * import(\"../Observable\").OnSignature &\n * import(\"../Observable\").OnSignature &\n * import(\"../Observable\").CombinedOnSignature} VectorSourceOnSignature\n */\n\n/**\n * @template {import(\"../geom/Geometry.js\").default} [Geometry=import(\"../geom/Geometry.js\").default]\n * @typedef {Object} Options\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {Array>|Collection>} [features]\n * Features. If provided as {@link module:ol/Collection~Collection}, the features in the source\n * and the collection will stay in sync.\n * @property {import(\"../format/Feature.js\").default} [format] The feature format used by the XHR\n * feature loader when `url` is set. Required if `url` is set, otherwise ignored.\n * @property {import(\"../featureloader.js\").FeatureLoader} [loader]\n * The loader function used to load features, from a remote source for example.\n * If this is not set and `url` is set, the source will create and use an XHR\n * feature loader. The `'featuresloadend'` and `'featuresloaderror'` events\n * will only fire if the `success` and `failure` callbacks are used.\n *\n * Example:\n *\n * ```js\n * import Vector from 'ol/source/Vector.js';\n * import GeoJSON from 'ol/format/GeoJSON.js';\n * import {bbox} from 'ol/loadingstrategy.js';\n *\n * const vectorSource = new Vector({\n * format: new GeoJSON(),\n * loader: function(extent, resolution, projection, success, failure) {\n * const proj = projection.getCode();\n * const url = 'https://ahocevar.com/geoserver/wfs?service=WFS&' +\n * 'version=1.1.0&request=GetFeature&typename=osm:water_areas&' +\n * 'outputFormat=application/json&srsname=' + proj + '&' +\n * 'bbox=' + extent.join(',') + ',' + proj;\n * const xhr = new XMLHttpRequest();\n * xhr.open('GET', url);\n * const onError = function() {\n * vectorSource.removeLoadedExtent(extent);\n * failure();\n * }\n * xhr.onerror = onError;\n * xhr.onload = function() {\n * if (xhr.status == 200) {\n * const features = vectorSource.getFormat().readFeatures(xhr.responseText);\n * vectorSource.addFeatures(features);\n * success(features);\n * } else {\n * onError();\n * }\n * }\n * xhr.send();\n * },\n * strategy: bbox,\n * });\n * ```\n * @property {boolean} [overlaps=true] This source may have overlapping geometries.\n * Setting this to `false` (e.g. for sources with polygons that represent administrative\n * boundaries or TopoJSON sources) allows the renderer to optimise fill and\n * stroke operations.\n * @property {LoadingStrategy} [strategy] The loading strategy to use.\n * By default an {@link module:ol/loadingstrategy.all}\n * strategy is used, a one-off strategy which loads all features at once.\n * @property {string|import(\"../featureloader.js\").FeatureUrlFunction} [url]\n * Setting this option instructs the source to load features using an XHR loader\n * (see {@link module:ol/featureloader.xhr}). Use a `string` and an\n * {@link module:ol/loadingstrategy.all} for a one-off download of all features from\n * the given URL. Use a {@link module:ol/featureloader~FeatureUrlFunction} to generate the url with\n * other loading strategies.\n * Requires `format` to be set as well.\n * When default XHR feature loader is provided, the features will\n * be transformed from the data projection to the view projection\n * during parsing. If your remote data source does not advertise its projection\n * properly, this transformation will be incorrect. For some formats, the\n * default projection (usually EPSG:4326) can be overridden by setting the\n * dataProjection constructor option on the format.\n * Note that if a source contains non-feature data, such as a GeoJSON geometry\n * or a KML NetworkLink, these will be ignored. Use a custom loader to load these.\n * @property {boolean} [useSpatialIndex=true]\n * By default, an RTree is used as spatial index. When features are removed and\n * added frequently, and the total number of features is low, setting this to\n * `false` may improve performance.\n *\n * Note that\n * {@link module:ol/source/Vector~VectorSource#getFeaturesInExtent},\n * {@link module:ol/source/Vector~VectorSource#getClosestFeatureToCoordinate} and\n * {@link module:ol/source/Vector~VectorSource#getExtent} cannot be used when `useSpatialIndex` is\n * set to `false`, and {@link module:ol/source/Vector~VectorSource#forEachFeatureInExtent} will loop\n * through all features.\n *\n * When set to `false`, the features will be maintained in an\n * {@link module:ol/Collection~Collection}, which can be retrieved through\n * {@link module:ol/source/Vector~VectorSource#getFeaturesCollection}.\n * @property {boolean} [wrapX=true] Wrap the world horizontally. For vector editing across the\n * -180° and 180° meridians to work properly, this should be set to `false`. The\n * resulting geometry coordinates will then exceed the world bounds.\n */\n\n/**\n * @classdesc\n * Provides a source of features for vector layers. Vector features provided\n * by this source are suitable for editing. See {@link module:ol/source/VectorTile~VectorTile} for\n * vector data that is optimized for rendering.\n *\n * @fires VectorSourceEvent\n * @api\n * @template {import(\"../geom/Geometry.js\").default} [Geometry=import(\"../geom/Geometry.js\").default]\n */\nclass VectorSource extends Source {\n /**\n * @param {Options} [options] Vector source options.\n */\n constructor(options) {\n options = options || {};\n\n super({\n attributions: options.attributions,\n interpolate: true,\n projection: undefined,\n state: 'ready',\n wrapX: options.wrapX !== undefined ? options.wrapX : true,\n });\n\n /***\n * @type {VectorSourceOnSignature}\n */\n this.on;\n\n /***\n * @type {VectorSourceOnSignature}\n */\n this.once;\n\n /***\n * @type {VectorSourceOnSignature}\n */\n this.un;\n\n /**\n * @private\n * @type {import(\"../featureloader.js\").FeatureLoader}\n */\n this.loader_ = VOID;\n\n /**\n * @private\n * @type {import(\"../format/Feature.js\").default|undefined}\n */\n this.format_ = options.format;\n\n /**\n * @private\n * @type {boolean}\n */\n this.overlaps_ = options.overlaps === undefined ? true : options.overlaps;\n\n /**\n * @private\n * @type {string|import(\"../featureloader.js\").FeatureUrlFunction|undefined}\n */\n this.url_ = options.url;\n\n if (options.loader !== undefined) {\n this.loader_ = options.loader;\n } else if (this.url_ !== undefined) {\n assert(this.format_, 7); // `format` must be set when `url` is set\n // create a XHR feature loader for \"url\" and \"format\"\n this.loader_ = xhr(\n this.url_,\n /** @type {import(\"../format/Feature.js\").default} */ (this.format_)\n );\n }\n\n /**\n * @private\n * @type {LoadingStrategy}\n */\n this.strategy_ =\n options.strategy !== undefined ? options.strategy : allStrategy;\n\n const useSpatialIndex =\n options.useSpatialIndex !== undefined ? options.useSpatialIndex : true;\n\n /**\n * @private\n * @type {RBush>}\n */\n this.featuresRtree_ = useSpatialIndex ? new RBush() : null;\n\n /**\n * @private\n * @type {RBush<{extent: import(\"../extent.js\").Extent}>}\n */\n this.loadedExtentsRtree_ = new RBush();\n\n /**\n * @type {number}\n * @private\n */\n this.loadingExtentsCount_ = 0;\n\n /**\n * @private\n * @type {!Object>}\n */\n this.nullGeometryFeatures_ = {};\n\n /**\n * A lookup of features by id (the return from feature.getId()).\n * @private\n * @type {!Object>}\n */\n this.idIndex_ = {};\n\n /**\n * A lookup of features by uid (using getUid(feature)).\n * @private\n * @type {!Object>}\n */\n this.uidIndex_ = {};\n\n /**\n * @private\n * @type {Object>}\n */\n this.featureChangeKeys_ = {};\n\n /**\n * @private\n * @type {Collection>|null}\n */\n this.featuresCollection_ = null;\n\n /** @type {Collection>} */\n let collection;\n /** @type {Array>} */\n let features;\n if (Array.isArray(options.features)) {\n features = options.features;\n } else if (options.features) {\n collection = options.features;\n features = collection.getArray();\n }\n if (!useSpatialIndex && collection === undefined) {\n collection = new Collection(features);\n }\n if (features !== undefined) {\n this.addFeaturesInternal(features);\n }\n if (collection !== undefined) {\n this.bindFeaturesCollection_(collection);\n }\n }\n\n /**\n * Add a single feature to the source. If you want to add a batch of features\n * at once, call {@link module:ol/source/Vector~VectorSource#addFeatures #addFeatures()}\n * instead. A feature will not be added to the source if feature with\n * the same id is already there. The reason for this behavior is to avoid\n * feature duplication when using bbox or tile loading strategies.\n * Note: this also applies if an {@link module:ol/Collection~Collection} is used for features,\n * meaning that if a feature with a duplicate id is added in the collection, it will\n * be removed from it right away.\n * @param {import(\"../Feature.js\").default} feature Feature to add.\n * @api\n */\n addFeature(feature) {\n this.addFeatureInternal(feature);\n this.changed();\n }\n\n /**\n * Add a feature without firing a `change` event.\n * @param {import(\"../Feature.js\").default} feature Feature.\n * @protected\n */\n addFeatureInternal(feature) {\n const featureKey = getUid(feature);\n\n if (!this.addToIndex_(featureKey, feature)) {\n if (this.featuresCollection_) {\n this.featuresCollection_.remove(feature);\n }\n return;\n }\n\n this.setupChangeEvents_(featureKey, feature);\n\n const geometry = feature.getGeometry();\n if (geometry) {\n const extent = geometry.getExtent();\n if (this.featuresRtree_) {\n this.featuresRtree_.insert(extent, feature);\n }\n } else {\n this.nullGeometryFeatures_[featureKey] = feature;\n }\n\n this.dispatchEvent(\n new VectorSourceEvent(VectorEventType.ADDFEATURE, feature)\n );\n }\n\n /**\n * @param {string} featureKey Unique identifier for the feature.\n * @param {import(\"../Feature.js\").default} feature The feature.\n * @private\n */\n setupChangeEvents_(featureKey, feature) {\n this.featureChangeKeys_[featureKey] = [\n listen(feature, EventType.CHANGE, this.handleFeatureChange_, this),\n listen(\n feature,\n ObjectEventType.PROPERTYCHANGE,\n this.handleFeatureChange_,\n this\n ),\n ];\n }\n\n /**\n * @param {string} featureKey Unique identifier for the feature.\n * @param {import(\"../Feature.js\").default} feature The feature.\n * @return {boolean} The feature is \"valid\", in the sense that it is also a\n * candidate for insertion into the Rtree.\n * @private\n */\n addToIndex_(featureKey, feature) {\n let valid = true;\n const id = feature.getId();\n if (id !== undefined) {\n if (!(id.toString() in this.idIndex_)) {\n this.idIndex_[id.toString()] = feature;\n } else {\n valid = false;\n }\n }\n if (valid) {\n assert(!(featureKey in this.uidIndex_), 30); // The passed `feature` was already added to the source\n this.uidIndex_[featureKey] = feature;\n }\n return valid;\n }\n\n /**\n * Add a batch of features to the source.\n * @param {Array>} features Features to add.\n * @api\n */\n addFeatures(features) {\n this.addFeaturesInternal(features);\n this.changed();\n }\n\n /**\n * Add features without firing a `change` event.\n * @param {Array>} features Features.\n * @protected\n */\n addFeaturesInternal(features) {\n const extents = [];\n const newFeatures = [];\n const geometryFeatures = [];\n\n for (let i = 0, length = features.length; i < length; i++) {\n const feature = features[i];\n const featureKey = getUid(feature);\n if (this.addToIndex_(featureKey, feature)) {\n newFeatures.push(feature);\n }\n }\n\n for (let i = 0, length = newFeatures.length; i < length; i++) {\n const feature = newFeatures[i];\n const featureKey = getUid(feature);\n this.setupChangeEvents_(featureKey, feature);\n\n const geometry = feature.getGeometry();\n if (geometry) {\n const extent = geometry.getExtent();\n extents.push(extent);\n geometryFeatures.push(feature);\n } else {\n this.nullGeometryFeatures_[featureKey] = feature;\n }\n }\n if (this.featuresRtree_) {\n this.featuresRtree_.load(extents, geometryFeatures);\n }\n\n if (this.hasListener(VectorEventType.ADDFEATURE)) {\n for (let i = 0, length = newFeatures.length; i < length; i++) {\n this.dispatchEvent(\n new VectorSourceEvent(VectorEventType.ADDFEATURE, newFeatures[i])\n );\n }\n }\n }\n\n /**\n * @param {!Collection>} collection Collection.\n * @private\n */\n bindFeaturesCollection_(collection) {\n let modifyingCollection = false;\n this.addEventListener(\n VectorEventType.ADDFEATURE,\n /**\n * @param {VectorSourceEvent} evt The vector source event\n */\n function (evt) {\n if (!modifyingCollection) {\n modifyingCollection = true;\n collection.push(evt.feature);\n modifyingCollection = false;\n }\n }\n );\n this.addEventListener(\n VectorEventType.REMOVEFEATURE,\n /**\n * @param {VectorSourceEvent} evt The vector source event\n */\n function (evt) {\n if (!modifyingCollection) {\n modifyingCollection = true;\n collection.remove(evt.feature);\n modifyingCollection = false;\n }\n }\n );\n collection.addEventListener(\n CollectionEventType.ADD,\n /**\n * @param {import(\"../Collection.js\").CollectionEvent>} evt The collection event\n */\n (evt) => {\n if (!modifyingCollection) {\n modifyingCollection = true;\n this.addFeature(evt.element);\n modifyingCollection = false;\n }\n }\n );\n collection.addEventListener(\n CollectionEventType.REMOVE,\n /**\n * @param {import(\"../Collection.js\").CollectionEvent>} evt The collection event\n */\n (evt) => {\n if (!modifyingCollection) {\n modifyingCollection = true;\n this.removeFeature(evt.element);\n modifyingCollection = false;\n }\n }\n );\n this.featuresCollection_ = collection;\n }\n\n /**\n * Remove all features from the source.\n * @param {boolean} [fast] Skip dispatching of {@link module:ol/source/Vector.VectorSourceEvent#event:removefeature} events.\n * @api\n */\n clear(fast) {\n if (fast) {\n for (const featureId in this.featureChangeKeys_) {\n const keys = this.featureChangeKeys_[featureId];\n keys.forEach(unlistenByKey);\n }\n if (!this.featuresCollection_) {\n this.featureChangeKeys_ = {};\n this.idIndex_ = {};\n this.uidIndex_ = {};\n }\n } else {\n if (this.featuresRtree_) {\n const removeAndIgnoreReturn = (feature) => {\n this.removeFeatureInternal(feature);\n };\n this.featuresRtree_.forEach(removeAndIgnoreReturn);\n for (const id in this.nullGeometryFeatures_) {\n this.removeFeatureInternal(this.nullGeometryFeatures_[id]);\n }\n }\n }\n if (this.featuresCollection_) {\n this.featuresCollection_.clear();\n }\n\n if (this.featuresRtree_) {\n this.featuresRtree_.clear();\n }\n this.nullGeometryFeatures_ = {};\n\n const clearEvent = new VectorSourceEvent(VectorEventType.CLEAR);\n this.dispatchEvent(clearEvent);\n this.changed();\n }\n\n /**\n * Iterate through all features on the source, calling the provided callback\n * with each one. If the callback returns any \"truthy\" value, iteration will\n * stop and the function will return the same value.\n * Note: this function only iterate through the feature that have a defined geometry.\n *\n * @param {function(import(\"../Feature.js\").default): T} callback Called with each feature\n * on the source. Return a truthy value to stop iteration.\n * @return {T|undefined} The return value from the last call to the callback.\n * @template T\n * @api\n */\n forEachFeature(callback) {\n if (this.featuresRtree_) {\n return this.featuresRtree_.forEach(callback);\n }\n if (this.featuresCollection_) {\n this.featuresCollection_.forEach(callback);\n }\n }\n\n /**\n * Iterate through all features whose geometries contain the provided\n * coordinate, calling the callback with each feature. If the callback returns\n * a \"truthy\" value, iteration will stop and the function will return the same\n * value.\n *\n * @param {import(\"../coordinate.js\").Coordinate} coordinate Coordinate.\n * @param {function(import(\"../Feature.js\").default): T} callback Called with each feature\n * whose goemetry contains the provided coordinate.\n * @return {T|undefined} The return value from the last call to the callback.\n * @template T\n */\n forEachFeatureAtCoordinateDirect(coordinate, callback) {\n const extent = [coordinate[0], coordinate[1], coordinate[0], coordinate[1]];\n return this.forEachFeatureInExtent(extent, function (feature) {\n const geometry = feature.getGeometry();\n if (geometry.intersectsCoordinate(coordinate)) {\n return callback(feature);\n }\n return undefined;\n });\n }\n\n /**\n * Iterate through all features whose bounding box intersects the provided\n * extent (note that the feature's geometry may not intersect the extent),\n * calling the callback with each feature. If the callback returns a \"truthy\"\n * value, iteration will stop and the function will return the same value.\n *\n * If you are interested in features whose geometry intersects an extent, call\n * the {@link module:ol/source/Vector~VectorSource#forEachFeatureIntersectingExtent #forEachFeatureIntersectingExtent()} method instead.\n *\n * When `useSpatialIndex` is set to false, this method will loop through all\n * features, equivalent to {@link module:ol/source/Vector~VectorSource#forEachFeature #forEachFeature()}.\n *\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @param {function(import(\"../Feature.js\").default): T} callback Called with each feature\n * whose bounding box intersects the provided extent.\n * @return {T|undefined} The return value from the last call to the callback.\n * @template T\n * @api\n */\n forEachFeatureInExtent(extent, callback) {\n if (this.featuresRtree_) {\n return this.featuresRtree_.forEachInExtent(extent, callback);\n }\n if (this.featuresCollection_) {\n this.featuresCollection_.forEach(callback);\n }\n }\n\n /**\n * Iterate through all features whose geometry intersects the provided extent,\n * calling the callback with each feature. If the callback returns a \"truthy\"\n * value, iteration will stop and the function will return the same value.\n *\n * If you only want to test for bounding box intersection, call the\n * {@link module:ol/source/Vector~VectorSource#forEachFeatureInExtent #forEachFeatureInExtent()} method instead.\n *\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @param {function(import(\"../Feature.js\").default): T} callback Called with each feature\n * whose geometry intersects the provided extent.\n * @return {T|undefined} The return value from the last call to the callback.\n * @template T\n * @api\n */\n forEachFeatureIntersectingExtent(extent, callback) {\n return this.forEachFeatureInExtent(\n extent,\n /**\n * @param {import(\"../Feature.js\").default} feature Feature.\n * @return {T|undefined} The return value from the last call to the callback.\n */\n function (feature) {\n const geometry = feature.getGeometry();\n if (geometry.intersectsExtent(extent)) {\n const result = callback(feature);\n if (result) {\n return result;\n }\n }\n }\n );\n }\n\n /**\n * Get the features collection associated with this source. Will be `null`\n * unless the source was configured with `useSpatialIndex` set to `false`, or\n * with an {@link module:ol/Collection~Collection} as `features`.\n * @return {Collection>|null} The collection of features.\n * @api\n */\n getFeaturesCollection() {\n return this.featuresCollection_;\n }\n\n /**\n * Get a snapshot of the features currently on the source in random order. The returned array\n * is a copy, the features are references to the features in the source.\n * @return {Array>} Features.\n * @api\n */\n getFeatures() {\n let features;\n if (this.featuresCollection_) {\n features = this.featuresCollection_.getArray().slice(0);\n } else if (this.featuresRtree_) {\n features = this.featuresRtree_.getAll();\n if (!isEmpty(this.nullGeometryFeatures_)) {\n extend(features, Object.values(this.nullGeometryFeatures_));\n }\n }\n return /** @type {Array>} */ (\n features\n );\n }\n\n /**\n * Get all features whose geometry intersects the provided coordinate.\n * @param {import(\"../coordinate.js\").Coordinate} coordinate Coordinate.\n * @return {Array>} Features.\n * @api\n */\n getFeaturesAtCoordinate(coordinate) {\n const features = [];\n this.forEachFeatureAtCoordinateDirect(coordinate, function (feature) {\n features.push(feature);\n });\n return features;\n }\n\n /**\n * Get all features whose bounding box intersects the provided extent. Note that this returns an array of\n * all features intersecting the given extent in random order (so it may include\n * features whose geometries do not intersect the extent).\n *\n * When `useSpatialIndex` is set to false, this method will return all\n * features.\n *\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @param {import(\"../proj/Projection.js\").default} [projection] Include features\n * where `extent` exceeds the x-axis bounds of `projection` and wraps around the world.\n * @return {Array>} Features.\n * @api\n */\n getFeaturesInExtent(extent, projection) {\n if (this.featuresRtree_) {\n const multiWorld = projection && projection.canWrapX() && this.getWrapX();\n\n if (!multiWorld) {\n return this.featuresRtree_.getInExtent(extent);\n }\n\n const extents = wrapAndSliceX(extent, projection);\n\n return [].concat(\n ...extents.map((anExtent) => this.featuresRtree_.getInExtent(anExtent))\n );\n }\n if (this.featuresCollection_) {\n return this.featuresCollection_.getArray().slice(0);\n }\n return [];\n }\n\n /**\n * Get the closest feature to the provided coordinate.\n *\n * This method is not available when the source is configured with\n * `useSpatialIndex` set to `false`.\n * @param {import(\"../coordinate.js\").Coordinate} coordinate Coordinate.\n * @param {function(import(\"../Feature.js\").default):boolean} [filter] Feature filter function.\n * The filter function will receive one argument, the {@link module:ol/Feature~Feature feature}\n * and it should return a boolean value. By default, no filtering is made.\n * @return {import(\"../Feature.js\").default} Closest feature.\n * @api\n */\n getClosestFeatureToCoordinate(coordinate, filter) {\n // Find the closest feature using branch and bound. We start searching an\n // infinite extent, and find the distance from the first feature found. This\n // becomes the closest feature. We then compute a smaller extent which any\n // closer feature must intersect. We continue searching with this smaller\n // extent, trying to find a closer feature. Every time we find a closer\n // feature, we update the extent being searched so that any even closer\n // feature must intersect it. We continue until we run out of features.\n const x = coordinate[0];\n const y = coordinate[1];\n let closestFeature = null;\n const closestPoint = [NaN, NaN];\n let minSquaredDistance = Infinity;\n const extent = [-Infinity, -Infinity, Infinity, Infinity];\n filter = filter ? filter : TRUE;\n this.featuresRtree_.forEachInExtent(\n extent,\n /**\n * @param {import(\"../Feature.js\").default} feature Feature.\n */\n function (feature) {\n if (filter(feature)) {\n const geometry = feature.getGeometry();\n const previousMinSquaredDistance = minSquaredDistance;\n minSquaredDistance = geometry.closestPointXY(\n x,\n y,\n closestPoint,\n minSquaredDistance\n );\n if (minSquaredDistance < previousMinSquaredDistance) {\n closestFeature = feature;\n // This is sneaky. Reduce the extent that it is currently being\n // searched while the R-Tree traversal using this same extent object\n // is still in progress. This is safe because the new extent is\n // strictly contained by the old extent.\n const minDistance = Math.sqrt(minSquaredDistance);\n extent[0] = x - minDistance;\n extent[1] = y - minDistance;\n extent[2] = x + minDistance;\n extent[3] = y + minDistance;\n }\n }\n }\n );\n return closestFeature;\n }\n\n /**\n * Get the extent of the features currently in the source.\n *\n * This method is not available when the source is configured with\n * `useSpatialIndex` set to `false`.\n * @param {import(\"../extent.js\").Extent} [extent] Destination extent. If provided, no new extent\n * will be created. Instead, that extent's coordinates will be overwritten.\n * @return {import(\"../extent.js\").Extent} Extent.\n * @api\n */\n getExtent(extent) {\n return this.featuresRtree_.getExtent(extent);\n }\n\n /**\n * Get a feature by its identifier (the value returned by feature.getId()).\n * Note that the index treats string and numeric identifiers as the same. So\n * `source.getFeatureById(2)` will return a feature with id `'2'` or `2`.\n *\n * @param {string|number} id Feature identifier.\n * @return {import(\"../Feature.js\").default|null} The feature (or `null` if not found).\n * @api\n */\n getFeatureById(id) {\n const feature = this.idIndex_[id.toString()];\n return feature !== undefined ? feature : null;\n }\n\n /**\n * Get a feature by its internal unique identifier (using `getUid`).\n *\n * @param {string} uid Feature identifier.\n * @return {import(\"../Feature.js\").default|null} The feature (or `null` if not found).\n */\n getFeatureByUid(uid) {\n const feature = this.uidIndex_[uid];\n return feature !== undefined ? feature : null;\n }\n\n /**\n * Get the format associated with this source.\n *\n * @return {import(\"../format/Feature.js\").default|undefined} The feature format.\n * @api\n */\n getFormat() {\n return this.format_;\n }\n\n /**\n * @return {boolean} The source can have overlapping geometries.\n */\n getOverlaps() {\n return this.overlaps_;\n }\n\n /**\n * Get the url associated with this source.\n *\n * @return {string|import(\"../featureloader.js\").FeatureUrlFunction|undefined} The url.\n * @api\n */\n getUrl() {\n return this.url_;\n }\n\n /**\n * @param {Event} event Event.\n * @private\n */\n handleFeatureChange_(event) {\n const feature = /** @type {import(\"../Feature.js\").default} */ (\n event.target\n );\n const featureKey = getUid(feature);\n const geometry = feature.getGeometry();\n if (!geometry) {\n if (!(featureKey in this.nullGeometryFeatures_)) {\n if (this.featuresRtree_) {\n this.featuresRtree_.remove(feature);\n }\n this.nullGeometryFeatures_[featureKey] = feature;\n }\n } else {\n const extent = geometry.getExtent();\n if (featureKey in this.nullGeometryFeatures_) {\n delete this.nullGeometryFeatures_[featureKey];\n if (this.featuresRtree_) {\n this.featuresRtree_.insert(extent, feature);\n }\n } else {\n if (this.featuresRtree_) {\n this.featuresRtree_.update(extent, feature);\n }\n }\n }\n const id = feature.getId();\n if (id !== undefined) {\n const sid = id.toString();\n if (this.idIndex_[sid] !== feature) {\n this.removeFromIdIndex_(feature);\n this.idIndex_[sid] = feature;\n }\n } else {\n this.removeFromIdIndex_(feature);\n this.uidIndex_[featureKey] = feature;\n }\n this.changed();\n this.dispatchEvent(\n new VectorSourceEvent(VectorEventType.CHANGEFEATURE, feature)\n );\n }\n\n /**\n * Returns true if the feature is contained within the source.\n * @param {import(\"../Feature.js\").default} feature Feature.\n * @return {boolean} Has feature.\n * @api\n */\n hasFeature(feature) {\n const id = feature.getId();\n if (id !== undefined) {\n return id in this.idIndex_;\n }\n return getUid(feature) in this.uidIndex_;\n }\n\n /**\n * @return {boolean} Is empty.\n */\n isEmpty() {\n if (this.featuresRtree_) {\n return (\n this.featuresRtree_.isEmpty() && isEmpty(this.nullGeometryFeatures_)\n );\n }\n if (this.featuresCollection_) {\n return this.featuresCollection_.getLength() === 0;\n }\n return true;\n }\n\n /**\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @param {number} resolution Resolution.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n */\n loadFeatures(extent, resolution, projection) {\n const loadedExtentsRtree = this.loadedExtentsRtree_;\n const extentsToLoad = this.strategy_(extent, resolution, projection);\n for (let i = 0, ii = extentsToLoad.length; i < ii; ++i) {\n const extentToLoad = extentsToLoad[i];\n const alreadyLoaded = loadedExtentsRtree.forEachInExtent(\n extentToLoad,\n /**\n * @param {{extent: import(\"../extent.js\").Extent}} object Object.\n * @return {boolean} Contains.\n */\n function (object) {\n return containsExtent(object.extent, extentToLoad);\n }\n );\n if (!alreadyLoaded) {\n ++this.loadingExtentsCount_;\n this.dispatchEvent(\n new VectorSourceEvent(VectorEventType.FEATURESLOADSTART)\n );\n this.loader_.call(\n this,\n extentToLoad,\n resolution,\n projection,\n (features) => {\n --this.loadingExtentsCount_;\n this.dispatchEvent(\n new VectorSourceEvent(\n VectorEventType.FEATURESLOADEND,\n undefined,\n features\n )\n );\n },\n () => {\n --this.loadingExtentsCount_;\n this.dispatchEvent(\n new VectorSourceEvent(VectorEventType.FEATURESLOADERROR)\n );\n }\n );\n loadedExtentsRtree.insert(extentToLoad, {extent: extentToLoad.slice()});\n }\n }\n this.loading =\n this.loader_.length < 4 ? false : this.loadingExtentsCount_ > 0;\n }\n\n refresh() {\n this.clear(true);\n this.loadedExtentsRtree_.clear();\n super.refresh();\n }\n\n /**\n * Remove an extent from the list of loaded extents.\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @api\n */\n removeLoadedExtent(extent) {\n const loadedExtentsRtree = this.loadedExtentsRtree_;\n let obj;\n loadedExtentsRtree.forEachInExtent(extent, function (object) {\n if (equals(object.extent, extent)) {\n obj = object;\n return true;\n }\n });\n if (obj) {\n loadedExtentsRtree.remove(obj);\n }\n }\n\n /**\n * Remove a single feature from the source. If you want to remove all features\n * at once, use the {@link module:ol/source/Vector~VectorSource#clear #clear()} method\n * instead.\n * @param {import(\"../Feature.js\").default} feature Feature to remove.\n * @api\n */\n removeFeature(feature) {\n if (!feature) {\n return;\n }\n const featureKey = getUid(feature);\n if (featureKey in this.nullGeometryFeatures_) {\n delete this.nullGeometryFeatures_[featureKey];\n } else {\n if (this.featuresRtree_) {\n this.featuresRtree_.remove(feature);\n }\n }\n const result = this.removeFeatureInternal(feature);\n if (result) {\n this.changed();\n }\n }\n\n /**\n * Remove feature without firing a `change` event.\n * @param {import(\"../Feature.js\").default} feature Feature.\n * @return {import(\"../Feature.js\").default|undefined} The removed feature\n * (or undefined if the feature was not found).\n * @protected\n */\n removeFeatureInternal(feature) {\n const featureKey = getUid(feature);\n const featureChangeKeys = this.featureChangeKeys_[featureKey];\n if (!featureChangeKeys) {\n return;\n }\n featureChangeKeys.forEach(unlistenByKey);\n delete this.featureChangeKeys_[featureKey];\n const id = feature.getId();\n if (id !== undefined) {\n delete this.idIndex_[id.toString()];\n }\n delete this.uidIndex_[featureKey];\n this.dispatchEvent(\n new VectorSourceEvent(VectorEventType.REMOVEFEATURE, feature)\n );\n return feature;\n }\n\n /**\n * Remove a feature from the id index. Called internally when the feature id\n * may have changed.\n * @param {import(\"../Feature.js\").default} feature The feature.\n * @return {boolean} Removed the feature from the index.\n * @private\n */\n removeFromIdIndex_(feature) {\n let removed = false;\n for (const id in this.idIndex_) {\n if (this.idIndex_[id] === feature) {\n delete this.idIndex_[id];\n removed = true;\n break;\n }\n }\n return removed;\n }\n\n /**\n * Set the new loader of the source. The next render cycle will use the\n * new loader.\n * @param {import(\"../featureloader.js\").FeatureLoader} loader The loader to set.\n * @api\n */\n setLoader(loader) {\n this.loader_ = loader;\n }\n\n /**\n * Points the source to a new url. The next render cycle will use the new url.\n * @param {string|import(\"../featureloader.js\").FeatureUrlFunction} url Url.\n * @api\n */\n setUrl(url) {\n assert(this.format_, 7); // `format` must be set when `url` is set\n this.url_ = url;\n this.setLoader(xhr(url, this.format_));\n }\n}\n\nexport default VectorSource;\n","/**\n * @module ol/source/Cluster\n */\n\nimport EventType from '../events/EventType.js';\nimport Feature from '../Feature.js';\nimport Point from '../geom/Point.js';\nimport VectorSource from './Vector.js';\nimport {add as addCoordinate, scale as scaleCoordinate} from '../coordinate.js';\nimport {assert} from '../asserts.js';\nimport {\n buffer,\n createEmpty,\n createOrUpdateFromCoordinate,\n getCenter,\n} from '../extent.js';\nimport {getUid} from '../util.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {number} [distance=20] Distance in pixels within which features will\n * be clustered together.\n * @property {number} [minDistance=0] Minimum distance in pixels between clusters.\n * Will be capped at the configured distance.\n * By default no minimum distance is guaranteed. This config can be used to avoid\n * overlapping icons. As a tradoff, the cluster feature's position will no longer be\n * the center of all its features.\n * @property {function(Feature):Point} [geometryFunction]\n * Function that takes an {@link module:ol/Feature~Feature} as argument and returns an\n * {@link module:ol/geom/Point~Point} as cluster calculation point for the feature. When a\n * feature should not be considered for clustering, the function should return\n * `null`. The default, which works when the underlying source contains point\n * features only, is\n * ```js\n * function(feature) {\n * return feature.getGeometry();\n * }\n * ```\n * See {@link module:ol/geom/Polygon~Polygon#getInteriorPoint} for a way to get a cluster\n * calculation point for polygons.\n * @property {function(Point, Array):Feature} [createCluster]\n * Function that takes the cluster's center {@link module:ol/geom/Point~Point} and an array\n * of {@link module:ol/Feature~Feature} included in this cluster. Must return a\n * {@link module:ol/Feature~Feature} that will be used to render. Default implementation is:\n * ```js\n * function(point, features) {\n * return new Feature({\n * geometry: point,\n * features: features\n * });\n * }\n * ```\n * @property {VectorSource} [source=null] Source.\n * @property {boolean} [wrapX=true] Whether to wrap the world horizontally.\n */\n\n/**\n * @classdesc\n * Layer source to cluster vector data. Works out of the box with point\n * geometries. For other geometry types, or if not all geometries should be\n * considered for clustering, a custom `geometryFunction` can be defined.\n *\n * If the instance is disposed without also disposing the underlying\n * source `setSource(null)` has to be called to remove the listener reference\n * from the wrapped source.\n * @api\n */\nclass Cluster extends VectorSource {\n /**\n * @param {Options} options Cluster options.\n */\n constructor(options) {\n super({\n attributions: options.attributions,\n wrapX: options.wrapX,\n });\n\n /**\n * @type {number|undefined}\n * @protected\n */\n this.resolution = undefined;\n\n /**\n * @type {number}\n * @protected\n */\n this.distance = options.distance !== undefined ? options.distance : 20;\n\n /**\n * @type {number}\n * @protected\n */\n this.minDistance = options.minDistance || 0;\n\n /**\n * @type {number}\n * @protected\n */\n this.interpolationRatio = 0;\n\n /**\n * @type {Array}\n * @protected\n */\n this.features = [];\n\n /**\n * @param {Feature} feature Feature.\n * @return {Point} Cluster calculation point.\n * @protected\n */\n this.geometryFunction =\n options.geometryFunction ||\n function (feature) {\n const geometry = /** @type {Point} */ (feature.getGeometry());\n assert(!geometry || geometry.getType() === 'Point', 10); // The default `geometryFunction` can only handle `Point` or null geometries\n return geometry;\n };\n\n /**\n * @type {function(Point, Array):Feature}\n * @private\n */\n this.createCustomCluster_ = options.createCluster;\n\n /**\n * @type {VectorSource|null}\n * @protected\n */\n this.source = null;\n\n /**\n * @private\n */\n this.boundRefresh_ = this.refresh.bind(this);\n\n this.updateDistance(this.distance, this.minDistance);\n this.setSource(options.source || null);\n }\n\n /**\n * Remove all features from the source.\n * @param {boolean} [fast] Skip dispatching of {@link module:ol/source/VectorEventType~VectorEventType#removefeature} events.\n * @api\n */\n clear(fast) {\n this.features.length = 0;\n super.clear(fast);\n }\n\n /**\n * Get the distance in pixels between clusters.\n * @return {number} Distance.\n * @api\n */\n getDistance() {\n return this.distance;\n }\n\n /**\n * Get a reference to the wrapped source.\n * @return {VectorSource|null} Source.\n * @api\n */\n getSource() {\n return this.source;\n }\n\n /**\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @param {number} resolution Resolution.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n */\n loadFeatures(extent, resolution, projection) {\n this.source.loadFeatures(extent, resolution, projection);\n if (resolution !== this.resolution) {\n this.resolution = resolution;\n this.refresh();\n }\n }\n\n /**\n * Set the distance within which features will be clusterd together.\n * @param {number} distance The distance in pixels.\n * @api\n */\n setDistance(distance) {\n this.updateDistance(distance, this.minDistance);\n }\n\n /**\n * Set the minimum distance between clusters. Will be capped at the\n * configured distance.\n * @param {number} minDistance The minimum distance in pixels.\n * @api\n */\n setMinDistance(minDistance) {\n this.updateDistance(this.distance, minDistance);\n }\n\n /**\n * The configured minimum distance between clusters.\n * @return {number} The minimum distance in pixels.\n * @api\n */\n getMinDistance() {\n return this.minDistance;\n }\n\n /**\n * Replace the wrapped source.\n * @param {VectorSource|null} source The new source for this instance.\n * @api\n */\n setSource(source) {\n if (this.source) {\n this.source.removeEventListener(EventType.CHANGE, this.boundRefresh_);\n }\n this.source = source;\n if (source) {\n source.addEventListener(EventType.CHANGE, this.boundRefresh_);\n }\n this.refresh();\n }\n\n /**\n * Handle the source changing.\n */\n refresh() {\n this.clear();\n this.cluster();\n this.addFeatures(this.features);\n }\n\n /**\n * Update the distances and refresh the source if necessary.\n * @param {number} distance The new distance.\n * @param {number} minDistance The new minimum distance.\n */\n updateDistance(distance, minDistance) {\n const ratio =\n distance === 0 ? 0 : Math.min(minDistance, distance) / distance;\n const changed =\n distance !== this.distance || this.interpolationRatio !== ratio;\n this.distance = distance;\n this.minDistance = minDistance;\n this.interpolationRatio = ratio;\n if (changed) {\n this.refresh();\n }\n }\n\n /**\n * @protected\n */\n cluster() {\n if (this.resolution === undefined || !this.source) {\n return;\n }\n const extent = createEmpty();\n const mapDistance = this.distance * this.resolution;\n const features = this.source.getFeatures();\n\n /** @type {Object} */\n const clustered = {};\n\n for (let i = 0, ii = features.length; i < ii; i++) {\n const feature = features[i];\n if (!(getUid(feature) in clustered)) {\n const geometry = this.geometryFunction(feature);\n if (geometry) {\n const coordinates = geometry.getCoordinates();\n createOrUpdateFromCoordinate(coordinates, extent);\n buffer(extent, mapDistance, extent);\n\n const neighbors = this.source\n .getFeaturesInExtent(extent)\n .filter(function (neighbor) {\n const uid = getUid(neighbor);\n if (uid in clustered) {\n return false;\n }\n clustered[uid] = true;\n return true;\n });\n this.features.push(this.createCluster(neighbors, extent));\n }\n }\n }\n }\n\n /**\n * @param {Array} features Features\n * @param {import(\"../extent.js\").Extent} extent The searched extent for these features.\n * @return {Feature} The cluster feature.\n * @protected\n */\n createCluster(features, extent) {\n const centroid = [0, 0];\n for (let i = features.length - 1; i >= 0; --i) {\n const geometry = this.geometryFunction(features[i]);\n if (geometry) {\n addCoordinate(centroid, geometry.getCoordinates());\n } else {\n features.splice(i, 1);\n }\n }\n scaleCoordinate(centroid, 1 / features.length);\n const searchCenter = getCenter(extent);\n const ratio = this.interpolationRatio;\n const geometry = new Point([\n centroid[0] * (1 - ratio) + searchCenter[0] * ratio,\n centroid[1] * (1 - ratio) + searchCenter[1] * ratio,\n ]);\n if (this.createCustomCluster_) {\n return this.createCustomCluster_(geometry, features);\n }\n return new Feature({\n geometry,\n features,\n });\n }\n}\n\nexport default Cluster;\n","/**\n * @module ol/reproj/DataTile\n */\nimport {ERROR_THRESHOLD} from './common.js';\n\nimport DataTile, {asArrayLike, asImageLike, toArray} from '../DataTile.js';\nimport EventType from '../events/EventType.js';\nimport TileState from '../TileState.js';\nimport Triangulation from './Triangulation.js';\nimport {\n calculateSourceExtentResolution,\n canvasPool,\n render as renderReprojected,\n} from '../reproj.js';\nimport {clamp} from '../math.js';\nimport {createCanvasContext2D, releaseCanvas} from '../dom.js';\nimport {getArea, getIntersection} from '../extent.js';\nimport {listen, unlistenByKey} from '../events.js';\n\n/**\n * @typedef {function(number, number, number, number) : import(\"../DataTile.js\").default} TileGetter\n */\n\n/**\n * @typedef {Object} Options\n * @property {import(\"../proj/Projection.js\").default} sourceProj Source projection.\n * @property {import(\"../tilegrid/TileGrid.js\").default} sourceTileGrid Source tile grid.\n * @property {import(\"../proj/Projection.js\").default} targetProj Target projection.\n * @property {import(\"../tilegrid/TileGrid.js\").default} targetTileGrid Target tile grid.\n * @property {import(\"../tilecoord.js\").TileCoord} tileCoord Coordinate of the tile.\n * @property {import(\"../tilecoord.js\").TileCoord} [wrappedTileCoord] Coordinate of the tile wrapped in X.\n * @property {number} pixelRatio Pixel ratio.\n * @property {number} gutter Gutter of the source tiles.\n * @property {TileGetter} getTileFunction Function returning source tiles (z, x, y, pixelRatio).\n * @property {boolean} [interpolate=false] Use interpolated values when resampling. By default,\n * the nearest neighbor is used when resampling.\n * @property {number} [errorThreshold] Acceptable reprojection error (in px).\n * @property {number} [transition=250] A duration for tile opacity\n * transitions in milliseconds. A duration of 0 disables the opacity transition.\n */\n\n/**\n * @classdesc\n * Class encapsulating single reprojected data tile.\n * See {@link module:ol/source/DataTile~DataTileSource}.\n *\n */\nclass ReprojDataTile extends DataTile {\n /**\n * @param {Options} options Tile options.\n */\n constructor(options) {\n super({\n tileCoord: options.tileCoord,\n loader: () => Promise.resolve(new Uint8Array(4)),\n interpolate: options.interpolate,\n transition: options.transition,\n });\n\n /**\n * @private\n * @type {number}\n */\n this.pixelRatio_ = options.pixelRatio;\n\n /**\n * @private\n * @type {number}\n */\n this.gutter_ = options.gutter;\n\n /**\n * @type {import(\"../DataTile.js\").Data}\n * @private\n */\n this.reprojData_ = null;\n\n /**\n * @type {Error}\n * @private\n */\n this.reprojError_ = null;\n\n /**\n * @type {import('../size.js').Size}\n * @private\n */\n this.reprojSize_ = undefined;\n\n /**\n * @private\n * @type {import(\"../tilegrid/TileGrid.js\").default}\n */\n this.sourceTileGrid_ = options.sourceTileGrid;\n\n /**\n * @private\n * @type {import(\"../tilegrid/TileGrid.js\").default}\n */\n this.targetTileGrid_ = options.targetTileGrid;\n\n /**\n * @private\n * @type {import(\"../tilecoord.js\").TileCoord}\n */\n this.wrappedTileCoord_ = options.wrappedTileCoord || options.tileCoord;\n\n /**\n * @private\n * @type {!Array}\n */\n this.sourceTiles_ = [];\n\n /**\n * @private\n * @type {?Array}\n */\n this.sourcesListenerKeys_ = null;\n\n /**\n * @private\n * @type {number}\n */\n this.sourceZ_ = 0;\n\n const targetExtent = this.targetTileGrid_.getTileCoordExtent(\n this.wrappedTileCoord_\n );\n const maxTargetExtent = this.targetTileGrid_.getExtent();\n let maxSourceExtent = this.sourceTileGrid_.getExtent();\n\n const limitedTargetExtent = maxTargetExtent\n ? getIntersection(targetExtent, maxTargetExtent)\n : targetExtent;\n\n if (getArea(limitedTargetExtent) === 0) {\n // Tile is completely outside range -> EMPTY\n // TODO: is it actually correct that the source even creates the tile ?\n this.state = TileState.EMPTY;\n return;\n }\n\n const sourceProj = options.sourceProj;\n const sourceProjExtent = sourceProj.getExtent();\n if (sourceProjExtent) {\n if (!maxSourceExtent) {\n maxSourceExtent = sourceProjExtent;\n } else {\n maxSourceExtent = getIntersection(maxSourceExtent, sourceProjExtent);\n }\n }\n\n const targetResolution = this.targetTileGrid_.getResolution(\n this.wrappedTileCoord_[0]\n );\n\n const targetProj = options.targetProj;\n const sourceResolution = calculateSourceExtentResolution(\n sourceProj,\n targetProj,\n limitedTargetExtent,\n targetResolution\n );\n\n if (!isFinite(sourceResolution) || sourceResolution <= 0) {\n // invalid sourceResolution -> EMPTY\n // probably edges of the projections when no extent is defined\n this.state = TileState.EMPTY;\n return;\n }\n\n const errorThresholdInPixels =\n options.errorThreshold !== undefined\n ? options.errorThreshold\n : ERROR_THRESHOLD;\n\n /**\n * @private\n * @type {!import(\"./Triangulation.js\").default}\n */\n this.triangulation_ = new Triangulation(\n sourceProj,\n targetProj,\n limitedTargetExtent,\n maxSourceExtent,\n sourceResolution * errorThresholdInPixels,\n targetResolution\n );\n\n if (this.triangulation_.getTriangles().length === 0) {\n // no valid triangles -> EMPTY\n this.state = TileState.EMPTY;\n return;\n }\n\n this.sourceZ_ = this.sourceTileGrid_.getZForResolution(sourceResolution);\n let sourceExtent = this.triangulation_.calculateSourceExtent();\n\n if (maxSourceExtent) {\n if (sourceProj.canWrapX()) {\n sourceExtent[1] = clamp(\n sourceExtent[1],\n maxSourceExtent[1],\n maxSourceExtent[3]\n );\n sourceExtent[3] = clamp(\n sourceExtent[3],\n maxSourceExtent[1],\n maxSourceExtent[3]\n );\n } else {\n sourceExtent = getIntersection(sourceExtent, maxSourceExtent);\n }\n }\n\n if (!getArea(sourceExtent)) {\n this.state = TileState.EMPTY;\n } else {\n const sourceRange = this.sourceTileGrid_.getTileRangeForExtentAndZ(\n sourceExtent,\n this.sourceZ_\n );\n const getTile = options.getTileFunction;\n for (let srcX = sourceRange.minX; srcX <= sourceRange.maxX; srcX++) {\n for (let srcY = sourceRange.minY; srcY <= sourceRange.maxY; srcY++) {\n const tile = getTile(this.sourceZ_, srcX, srcY, this.pixelRatio_);\n if (tile) {\n this.sourceTiles_.push(tile);\n }\n }\n }\n\n if (this.sourceTiles_.length === 0) {\n this.state = TileState.EMPTY;\n }\n }\n }\n\n /**\n * Get the tile size.\n * @return {import('../size.js').Size} Tile size.\n */\n getSize() {\n return this.reprojSize_;\n }\n\n /**\n * Get the data for the tile.\n * @return {import(\"../DataTile.js\").Data} Tile data.\n */\n getData() {\n return this.reprojData_;\n }\n\n /**\n * Get any loading error.\n * @return {Error} Loading error.\n */\n getError() {\n return this.reprojError_;\n }\n\n /**\n * @private\n */\n reproject_() {\n const dataSources = [];\n this.sourceTiles_.forEach((tile) => {\n if (!tile || tile.getState() !== TileState.LOADED) {\n return;\n }\n const size = tile.getSize();\n const gutter = this.gutter_;\n /**\n * @type {import(\"../DataTile.js\").ArrayLike}\n */\n let tileData;\n const arrayData = asArrayLike(tile.getData());\n if (arrayData) {\n tileData = arrayData;\n } else {\n tileData = toArray(asImageLike(tile.getData()));\n }\n const pixelSize = [size[0] + 2 * gutter, size[1] + 2 * gutter];\n const isFloat = tileData instanceof Float32Array;\n const pixelCount = pixelSize[0] * pixelSize[1];\n const DataType = isFloat ? Float32Array : Uint8Array;\n const tileDataR = new DataType(tileData.buffer);\n const bytesPerElement = DataType.BYTES_PER_ELEMENT;\n const bytesPerPixel = (bytesPerElement * tileDataR.length) / pixelCount;\n const bytesPerRow = tileDataR.byteLength / pixelSize[1];\n const bandCount = Math.floor(\n bytesPerRow / bytesPerElement / pixelSize[0]\n );\n const packedLength = pixelCount * bandCount;\n let packedData = tileDataR;\n if (tileDataR.length !== packedLength) {\n packedData = new DataType(packedLength);\n let dataIndex = 0;\n let rowOffset = 0;\n const colCount = pixelSize[0] * bandCount;\n for (let rowIndex = 0; rowIndex < pixelSize[1]; ++rowIndex) {\n for (let colIndex = 0; colIndex < colCount; ++colIndex) {\n packedData[dataIndex++] = tileDataR[rowOffset + colIndex];\n }\n rowOffset += bytesPerRow / bytesPerElement;\n }\n }\n dataSources.push({\n extent: this.sourceTileGrid_.getTileCoordExtent(tile.tileCoord),\n data: new Uint8Array(packedData.buffer),\n dataType: DataType,\n bytesPerPixel: bytesPerPixel,\n pixelSize: pixelSize,\n });\n });\n this.sourceTiles_.length = 0;\n\n if (dataSources.length === 0) {\n this.state = TileState.ERROR;\n } else {\n const z = this.wrappedTileCoord_[0];\n const size = this.targetTileGrid_.getTileSize(z);\n const targetWidth = typeof size === 'number' ? size : size[0];\n const targetHeight = typeof size === 'number' ? size : size[1];\n const targetResolution = this.targetTileGrid_.getResolution(z);\n const sourceResolution = this.sourceTileGrid_.getResolution(\n this.sourceZ_\n );\n\n const targetExtent = this.targetTileGrid_.getTileCoordExtent(\n this.wrappedTileCoord_\n );\n\n let dataR, dataU;\n\n const bytesPerPixel = dataSources[0].bytesPerPixel;\n\n const reprojs = Math.ceil(bytesPerPixel / 3);\n for (let reproj = reprojs - 1; reproj >= 0; --reproj) {\n const sources = [];\n for (let i = 0, len = dataSources.length; i < len; ++i) {\n const dataSource = dataSources[i];\n const buffer = dataSource.data;\n const pixelSize = dataSource.pixelSize;\n const width = pixelSize[0];\n const height = pixelSize[1];\n const context = createCanvasContext2D(width, height, canvasPool);\n const imageData = context.createImageData(width, height);\n const data = imageData.data;\n let offset = reproj * 3;\n for (let j = 0, len = data.length; j < len; j += 4) {\n data[j] = buffer[offset];\n data[j + 1] = buffer[offset + 1];\n data[j + 2] = buffer[offset + 2];\n data[j + 3] = 255;\n offset += bytesPerPixel;\n }\n context.putImageData(imageData, 0, 0);\n sources.push({\n extent: dataSource.extent,\n image: context.canvas,\n });\n }\n\n const canvas = renderReprojected(\n targetWidth,\n targetHeight,\n this.pixelRatio_,\n sourceResolution,\n this.sourceTileGrid_.getExtent(),\n targetResolution,\n targetExtent,\n this.triangulation_,\n sources,\n this.gutter_,\n false,\n false\n );\n\n for (let i = 0, len = sources.length; i < len; ++i) {\n const canvas = sources[i].image;\n const context = canvas.getContext('2d');\n releaseCanvas(context);\n canvasPool.push(context.canvas);\n }\n\n const context = canvas.getContext('2d');\n const imageData = context.getImageData(\n 0,\n 0,\n canvas.width,\n canvas.height\n );\n\n releaseCanvas(context);\n canvasPool.push(canvas);\n\n if (!dataR) {\n dataU = new Uint8Array(\n bytesPerPixel * imageData.width * imageData.height\n );\n dataR = new dataSources[0].dataType(dataU.buffer);\n }\n\n const data = imageData.data;\n let offset = reproj * 3;\n for (let i = 0, len = data.length; i < len; i += 4) {\n if (data[i + 3] === 255) {\n dataU[offset] = data[i];\n dataU[offset + 1] = data[i + 1];\n dataU[offset + 2] = data[i + 2];\n } else {\n dataU[offset] = 0;\n dataU[offset + 1] = 0;\n dataU[offset + 2] = 0;\n }\n offset += bytesPerPixel;\n }\n }\n\n this.reprojData_ = dataR;\n this.reprojSize_ = [\n Math.round(targetWidth * this.pixelRatio_),\n Math.round(targetHeight * this.pixelRatio_),\n ];\n this.state = TileState.LOADED;\n }\n this.changed();\n }\n\n /**\n * Load not yet loaded URI.\n */\n load() {\n if (this.state !== TileState.IDLE && this.state !== TileState.ERROR) {\n return;\n }\n this.state = TileState.LOADING;\n this.changed();\n\n let leftToLoad = 0;\n\n this.sourcesListenerKeys_ = [];\n this.sourceTiles_.forEach((tile) => {\n const state = tile.getState();\n if (state !== TileState.IDLE && state !== TileState.LOADING) {\n return;\n }\n leftToLoad++;\n\n const sourceListenKey = listen(\n tile,\n EventType.CHANGE,\n function () {\n const state = tile.getState();\n if (\n state == TileState.LOADED ||\n state == TileState.ERROR ||\n state == TileState.EMPTY\n ) {\n unlistenByKey(sourceListenKey);\n leftToLoad--;\n if (leftToLoad === 0) {\n this.unlistenSources_();\n this.reproject_();\n }\n }\n },\n this\n );\n this.sourcesListenerKeys_.push(sourceListenKey);\n });\n\n if (leftToLoad === 0) {\n setTimeout(this.reproject_.bind(this), 0);\n } else {\n this.sourceTiles_.forEach(function (tile) {\n const state = tile.getState();\n if (state == TileState.IDLE) {\n tile.load();\n }\n });\n }\n }\n\n /**\n * @private\n */\n unlistenSources_() {\n this.sourcesListenerKeys_.forEach(unlistenByKey);\n this.sourcesListenerKeys_ = null;\n }\n}\n\nexport default ReprojDataTile;\n","/**\n * @module ol/source/DataTile\n */\nimport DataTile from '../DataTile.js';\nimport EventType from '../events/EventType.js';\nimport ReprojDataTile from '../reproj/DataTile.js';\nimport TileCache from '../TileCache.js';\nimport TileEventType from './TileEventType.js';\nimport TileSource, {TileSourceEvent} from './Tile.js';\nimport TileState from '../TileState.js';\nimport {\n createXYZ,\n extentFromProjection,\n getForProjection as getTileGridForProjection,\n} from '../tilegrid.js';\nimport {equivalent, get as getProjection} from '../proj.js';\nimport {getKeyZXY} from '../tilecoord.js';\nimport {getUid} from '../util.js';\nimport {toPromise} from '../functions.js';\nimport {toSize} from '../size.js';\n\n/**\n * Data tile loading function. The function is called with z, x, and y tile coordinates and\n * returns {@link import(\"../DataTile.js\").Data data} for a tile or a promise for the same.\n * @typedef {function(number, number, number) : (import(\"../DataTile.js\").Data|Promise)} Loader\n */\n\n/**\n * @typedef {Object} Options\n * @property {Loader} [loader] Data loader. Called with z, x, and y tile coordinates.\n * Returns {@link import(\"../DataTile.js\").Data data} for a tile or a promise for the same.\n * For loaders that generate images, the promise should not resolve until the image is loaded.\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.\n * @property {number} [maxZoom=42] Optional max zoom level. Not used if `tileGrid` is provided.\n * @property {number} [minZoom=0] Optional min zoom level. Not used if `tileGrid` is provided.\n * @property {number|import(\"../size.js\").Size} [tileSize=[256, 256]] The pixel width and height of the source tiles.\n * This may be different than the rendered pixel size if a `tileGrid` is provided.\n * @property {number} [gutter=0] The size in pixels of the gutter around data tiles to ignore.\n * This allows artifacts of rendering at tile edges to be ignored.\n * Supported data should be wider and taller than the tile size by a value of `2 x gutter`.\n * @property {number} [maxResolution] Optional tile grid resolution at level zero. Not used if `tileGrid` is provided.\n * @property {import(\"../proj.js\").ProjectionLike} [projection='EPSG:3857'] Tile projection.\n * @property {import(\"../tilegrid/TileGrid.js\").default} [tileGrid] Tile grid.\n * @property {boolean} [opaque=false] Whether the layer is opaque.\n * @property {import(\"./Source.js\").State} [state] The source state.\n * @property {boolean} [wrapX=false] Render tiles beyond the antimeridian.\n * @property {number} [transition] Transition time when fading in new tiles (in milliseconds).\n * @property {number} [bandCount=4] Number of bands represented in the data.\n * @property {boolean} [interpolate=false] Use interpolated values when resampling. By default,\n * the nearest neighbor is used when resampling.\n */\n\n/**\n * @classdesc\n * A source for typed array data tiles.\n *\n * @fires import(\"./Tile.js\").TileSourceEvent\n * @api\n */\nclass DataTileSource extends TileSource {\n /**\n * @param {Options} options DataTile source options.\n */\n constructor(options) {\n const projection =\n options.projection === undefined ? 'EPSG:3857' : options.projection;\n\n let tileGrid = options.tileGrid;\n if (tileGrid === undefined && projection) {\n tileGrid = createXYZ({\n extent: extentFromProjection(projection),\n maxResolution: options.maxResolution,\n maxZoom: options.maxZoom,\n minZoom: options.minZoom,\n tileSize: options.tileSize,\n });\n }\n\n super({\n cacheSize: 0.1, // don't cache on the source\n attributions: options.attributions,\n attributionsCollapsible: options.attributionsCollapsible,\n projection: projection,\n tileGrid: tileGrid,\n opaque: options.opaque,\n state: options.state,\n wrapX: options.wrapX,\n transition: options.transition,\n interpolate: options.interpolate,\n });\n\n /**\n * @private\n * @type {number}\n */\n this.gutter_ = options.gutter !== undefined ? options.gutter : 0;\n\n /**\n * @private\n * @type {import('../size.js').Size|null}\n */\n this.tileSize_ = options.tileSize ? toSize(options.tileSize) : null;\n\n /**\n * @private\n * @type {Array|null}\n */\n this.tileSizes_ = null;\n\n /**\n * @private\n * @type {!Object}\n */\n this.tileLoadingKeys_ = {};\n\n /**\n * @private\n */\n this.loader_ = options.loader;\n\n this.handleTileChange_ = this.handleTileChange_.bind(this);\n\n /**\n * @type {number}\n */\n this.bandCount = options.bandCount === undefined ? 4 : options.bandCount; // assume RGBA if undefined\n\n /**\n * @private\n * @type {!Object}\n */\n this.tileGridForProjection_ = {};\n\n /**\n * @private\n * @type {!Object}\n */\n this.tileCacheForProjection_ = {};\n }\n\n /**\n * Set the source tile sizes. The length of the array is expected to match the number of\n * levels in the tile grid.\n * @protected\n * @param {Array} tileSizes An array of tile sizes.\n */\n setTileSizes(tileSizes) {\n this.tileSizes_ = tileSizes;\n }\n\n /**\n * Get the source tile size at the given zoom level. This may be different than the rendered tile\n * size.\n * @protected\n * @param {number} z Tile zoom level.\n * @return {import('../size.js').Size} The source tile size.\n */\n getTileSize(z) {\n if (this.tileSizes_) {\n return this.tileSizes_[z];\n }\n if (this.tileSize_) {\n return this.tileSize_;\n }\n const tileGrid = this.getTileGrid();\n return tileGrid ? toSize(tileGrid.getTileSize(z)) : [256, 256];\n }\n\n /**\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {number} Gutter.\n */\n getGutterForProjection(projection) {\n const thisProj = this.getProjection();\n if (!thisProj || equivalent(thisProj, projection)) {\n return this.gutter_;\n }\n\n return 0;\n }\n\n /**\n * @param {Loader} loader The data loader.\n * @protected\n */\n setLoader(loader) {\n this.loader_ = loader;\n }\n\n /**\n * @param {number} z Tile coordinate z.\n * @param {number} x Tile coordinate x.\n * @param {number} y Tile coordinate y.\n * @param {import(\"../proj/Projection.js\").default} targetProj The output projection.\n * @param {import(\"../proj/Projection.js\").default} sourceProj The input projection.\n * @return {!DataTile} Tile.\n */\n getReprojTile_(z, x, y, targetProj, sourceProj) {\n const cache = this.getTileCacheForProjection(targetProj);\n const tileCoordKey = getKeyZXY(z, x, y);\n if (cache.containsKey(tileCoordKey)) {\n const tile = cache.get(tileCoordKey);\n if (tile && tile.key == this.getKey()) {\n return tile;\n }\n }\n\n const tileGrid = this.getTileGrid();\n const reprojTilePixelRatio = Math.max.apply(\n null,\n tileGrid.getResolutions().map((r, z) => {\n const tileSize = toSize(tileGrid.getTileSize(z));\n const textureSize = this.getTileSize(z);\n return Math.max(\n textureSize[0] / tileSize[0],\n textureSize[1] / tileSize[1]\n );\n })\n );\n\n const sourceTileGrid = this.getTileGridForProjection(sourceProj);\n const targetTileGrid = this.getTileGridForProjection(targetProj);\n const tileCoord = [z, x, y];\n const wrappedTileCoord = this.getTileCoordForTileUrlFunction(\n tileCoord,\n targetProj\n );\n\n const options = Object.assign(\n {\n sourceProj,\n sourceTileGrid,\n targetProj,\n targetTileGrid,\n tileCoord,\n wrappedTileCoord,\n pixelRatio: reprojTilePixelRatio,\n gutter: this.getGutterForProjection(sourceProj),\n getTileFunction: (z, x, y, pixelRatio) =>\n this.getTile(z, x, y, pixelRatio, sourceProj),\n },\n this.tileOptions\n );\n const newTile = new ReprojDataTile(options);\n newTile.key = this.getKey();\n return newTile;\n }\n\n /**\n * @param {number} z Tile coordinate z.\n * @param {number} x Tile coordinate x.\n * @param {number} y Tile coordinate y.\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {!DataTile} Tile.\n */\n getTile(z, x, y, pixelRatio, projection) {\n const sourceProjection = this.getProjection();\n if (\n sourceProjection &&\n projection &&\n !equivalent(sourceProjection, projection)\n ) {\n return this.getReprojTile_(z, x, y, projection, sourceProjection);\n }\n\n const size = this.getTileSize(z);\n const tileCoordKey = getKeyZXY(z, x, y);\n if (this.tileCache.containsKey(tileCoordKey)) {\n return this.tileCache.get(tileCoordKey);\n }\n\n const sourceLoader = this.loader_;\n\n function loader() {\n return toPromise(function () {\n return sourceLoader(z, x, y);\n });\n }\n\n const options = Object.assign(\n {\n tileCoord: [z, x, y],\n loader: loader,\n size: size,\n },\n this.tileOptions\n );\n\n const tile = new DataTile(options);\n tile.key = this.getKey();\n tile.addEventListener(EventType.CHANGE, this.handleTileChange_);\n\n this.tileCache.set(tileCoordKey, tile);\n return tile;\n }\n\n /**\n * Handle tile change events.\n * @param {import(\"../events/Event.js\").default} event Event.\n */\n handleTileChange_(event) {\n const tile = /** @type {import(\"../Tile.js\").default} */ (event.target);\n const uid = getUid(tile);\n const tileState = tile.getState();\n let type;\n if (tileState == TileState.LOADING) {\n this.tileLoadingKeys_[uid] = true;\n type = TileEventType.TILELOADSTART;\n } else if (uid in this.tileLoadingKeys_) {\n delete this.tileLoadingKeys_[uid];\n type =\n tileState == TileState.ERROR\n ? TileEventType.TILELOADERROR\n : tileState == TileState.LOADED\n ? TileEventType.TILELOADEND\n : undefined;\n }\n if (type) {\n this.dispatchEvent(new TileSourceEvent(type, tile));\n }\n }\n\n /**\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {!import(\"../tilegrid/TileGrid.js\").default} Tile grid.\n */\n getTileGridForProjection(projection) {\n const thisProj = this.getProjection();\n if (this.tileGrid && (!thisProj || equivalent(thisProj, projection))) {\n return this.tileGrid;\n }\n\n const projKey = getUid(projection);\n if (!(projKey in this.tileGridForProjection_)) {\n this.tileGridForProjection_[projKey] =\n getTileGridForProjection(projection);\n }\n return this.tileGridForProjection_[projKey];\n }\n\n /**\n * Sets the tile grid to use when reprojecting the tiles to the given\n * projection instead of the default tile grid for the projection.\n *\n * This can be useful when the default tile grid cannot be created\n * (e.g. projection has no extent defined) or\n * for optimization reasons (custom tile size, resolutions, ...).\n *\n * @param {import(\"../proj.js\").ProjectionLike} projection Projection.\n * @param {import(\"../tilegrid/TileGrid.js\").default} tilegrid Tile grid to use for the projection.\n * @api\n */\n setTileGridForProjection(projection, tilegrid) {\n const proj = getProjection(projection);\n if (proj) {\n const projKey = getUid(proj);\n if (!(projKey in this.tileGridForProjection_)) {\n this.tileGridForProjection_[projKey] = tilegrid;\n }\n }\n }\n\n /**\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {import(\"../TileCache.js\").default} Tile cache.\n */\n getTileCacheForProjection(projection) {\n const thisProj = this.getProjection();\n if (!thisProj || equivalent(thisProj, projection)) {\n return this.tileCache;\n }\n\n const projKey = getUid(projection);\n if (!(projKey in this.tileCacheForProjection_)) {\n this.tileCacheForProjection_[projKey] = new TileCache(0.1); // don't cache\n }\n return this.tileCacheForProjection_[projKey];\n }\n\n /**\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @param {!Object} usedTiles Used tiles.\n */\n expireCache(projection, usedTiles) {\n const usedTileCache = this.getTileCacheForProjection(projection);\n\n this.tileCache.expireCache(\n this.tileCache == usedTileCache ? usedTiles : {}\n );\n for (const id in this.tileCacheForProjection_) {\n const tileCache = this.tileCacheForProjection_[id];\n tileCache.expireCache(tileCache == usedTileCache ? usedTiles : {});\n }\n }\n\n clear() {\n super.clear();\n for (const id in this.tileCacheForProjection_) {\n this.tileCacheForProjection_[id].clear();\n }\n }\n}\n\nexport default DataTileSource;\n","/**\n * @module ol/source/GeoTIFF\n */\nimport DataTile from './DataTile.js';\nimport TileGrid from '../tilegrid/TileGrid.js';\nimport {\n Pool,\n globals as geotiffGlobals,\n fromBlob as tiffFromBlob,\n fromUrl as tiffFromUrl,\n fromUrls as tiffFromUrls,\n} from 'geotiff';\nimport {\n Projection,\n get as getCachedProjection,\n toUserCoordinate,\n toUserExtent,\n} from '../proj.js';\nimport {clamp} from '../math.js';\nimport {getCenter, getIntersection} from '../extent.js';\nimport {error as logError} from '../console.js';\nimport {fromCode as unitsFromCode} from '../proj/Units.js';\n\n/**\n * Determine if an image type is a mask.\n * See https://www.awaresystems.be/imaging/tiff/tifftags/newsubfiletype.html\n * @param {GeoTIFFImage} image The image.\n * @return {boolean} The image is a mask.\n */\nfunction isMask(image) {\n const fileDirectory = image.fileDirectory;\n const type = fileDirectory.NewSubfileType || 0;\n return (type & 4) === 4;\n}\n\n/**\n * @param {true|false|'auto'} preference The convertToRGB option.\n * @param {GeoTIFFImage} image The image.\n * @return {boolean} Use the `image.readRGB()` method.\n */\nfunction readRGB(preference, image) {\n if (!preference) {\n return false;\n }\n if (preference === true) {\n return true;\n }\n if (image.getSamplesPerPixel() !== 3) {\n return false;\n }\n const interpretation = image.fileDirectory.PhotometricInterpretation;\n const interpretations = geotiffGlobals.photometricInterpretations;\n return (\n interpretation === interpretations.CMYK ||\n interpretation === interpretations.YCbCr ||\n interpretation === interpretations.CIELab ||\n interpretation === interpretations.ICCLab\n );\n}\n\n/**\n * @typedef {Object} SourceInfo\n * @property {string} [url] URL for the source GeoTIFF.\n * @property {Array} [overviews] List of any overview URLs, only applies if the url parameter is given.\n * @property {Blob} [blob] Blob containing the source GeoTIFF. `blob` and `url` are mutually exclusive.\n * @property {number} [min=0] The minimum source data value. Rendered values are scaled from 0 to 1 based on\n * the configured min and max. If not provided and raster statistics are available, those will be used instead.\n * If neither are available, the minimum for the data type will be used. To disable this behavior, set\n * the `normalize` option to `false` in the constructor.\n * @property {number} [max] The maximum source data value. Rendered values are scaled from 0 to 1 based on\n * the configured min and max. If not provided and raster statistics are available, those will be used instead.\n * If neither are available, the maximum for the data type will be used. To disable this behavior, set\n * the `normalize` option to `false` in the constructor.\n * @property {number} [nodata] Values to discard (overriding any nodata values in the metadata).\n * When provided, an additional alpha band will be added to the data. Often the GeoTIFF metadata\n * will include information about nodata values, so you should only need to set this property if\n * you find that it is not already extracted from the metadata.\n * @property {Array} [bands] Band numbers to be read from (where the first band is `1`). If not provided, all bands will\n * be read. For example, if a GeoTIFF has blue (1), green (2), red (3), and near-infrared (4) bands, and you only need the\n * near-infrared band, configure `bands: [4]`.\n */\n\n/**\n * @typedef {Object} GeoKeys\n * @property {number} GTModelTypeGeoKey Model type.\n * @property {number} GTRasterTypeGeoKey Raster type.\n * @property {number} GeogAngularUnitsGeoKey Angular units.\n * @property {number} GeogInvFlatteningGeoKey Inverse flattening.\n * @property {number} GeogSemiMajorAxisGeoKey Semi-major axis.\n * @property {number} GeographicTypeGeoKey Geographic coordinate system code.\n * @property {number} ProjLinearUnitsGeoKey Projected linear unit code.\n * @property {number} ProjectedCSTypeGeoKey Projected coordinate system code.\n */\n\n/**\n * @typedef {import(\"geotiff\").GeoTIFF} GeoTIFF\n */\n\n/**\n * @typedef {import(\"geotiff\").MultiGeoTIFF} MultiGeoTIFF\n */\n\n/**\n * @typedef {Object} GDALMetadata\n * @property {string} STATISTICS_MINIMUM The minimum value (as a string).\n * @property {string} STATISTICS_MAXIMUM The maximum value (as a string).\n */\n\nconst STATISTICS_MAXIMUM = 'STATISTICS_MAXIMUM';\nconst STATISTICS_MINIMUM = 'STATISTICS_MINIMUM';\n\nconst defaultTileSize = 256;\n\n/**\n * @typedef {import(\"geotiff\").GeoTIFFImage} GeoTIFFImage\n */\n\nlet workerPool;\nfunction getWorkerPool() {\n if (!workerPool) {\n workerPool = new Pool();\n }\n return workerPool;\n}\n\n/**\n * Get the bounding box of an image. If the image does not have an affine transform,\n * the pixel bounds are returned.\n * @param {GeoTIFFImage} image The image.\n * @return {Array} The image bounding box.\n */\nfunction getBoundingBox(image) {\n try {\n return image.getBoundingBox();\n } catch (_) {\n return [0, 0, image.getWidth(), image.getHeight()];\n }\n}\n\n/**\n * Get the origin of an image. If the image does not have an affine transform,\n * the top-left corner of the pixel bounds is returned.\n * @param {GeoTIFFImage} image The image.\n * @return {Array} The image origin.\n */\nfunction getOrigin(image) {\n try {\n return image.getOrigin().slice(0, 2);\n } catch (_) {\n return [0, image.getHeight()];\n }\n}\n\n/**\n * Get the resolution of an image. If the image does not have an affine transform,\n * the width of the image is compared with the reference image.\n * @param {GeoTIFFImage} image The image.\n * @param {GeoTIFFImage} referenceImage The reference image.\n * @return {Array} The map x and y units per pixel.\n */\nfunction getResolutions(image, referenceImage) {\n try {\n return image.getResolution(referenceImage);\n } catch (_) {\n return [\n referenceImage.getWidth() / image.getWidth(),\n referenceImage.getHeight() / image.getHeight(),\n ];\n }\n}\n\n/**\n * @param {GeoTIFFImage} image A GeoTIFF.\n * @return {import(\"../proj/Projection.js\").default} The image projection.\n */\nfunction getProjection(image) {\n const geoKeys = image.geoKeys;\n if (!geoKeys) {\n return null;\n }\n\n if (\n geoKeys.ProjectedCSTypeGeoKey &&\n geoKeys.ProjectedCSTypeGeoKey !== 32767\n ) {\n const code = 'EPSG:' + geoKeys.ProjectedCSTypeGeoKey;\n let projection = getCachedProjection(code);\n if (!projection) {\n const units = unitsFromCode(geoKeys.ProjLinearUnitsGeoKey);\n if (units) {\n projection = new Projection({\n code: code,\n units: units,\n });\n }\n }\n return projection;\n }\n\n if (geoKeys.GeographicTypeGeoKey && geoKeys.GeographicTypeGeoKey !== 32767) {\n const code = 'EPSG:' + geoKeys.GeographicTypeGeoKey;\n let projection = getCachedProjection(code);\n if (!projection) {\n const units = unitsFromCode(geoKeys.GeogAngularUnitsGeoKey);\n if (units) {\n projection = new Projection({\n code: code,\n units: units,\n });\n }\n }\n return projection;\n }\n\n return null;\n}\n\n/**\n * @param {GeoTIFF|MultiGeoTIFF} tiff A GeoTIFF.\n * @return {Promise>} Resolves to a list of images.\n */\nfunction getImagesForTIFF(tiff) {\n return tiff.getImageCount().then(function (count) {\n const requests = new Array(count);\n for (let i = 0; i < count; ++i) {\n requests[i] = tiff.getImage(i);\n }\n return Promise.all(requests);\n });\n}\n\n/**\n * @param {SourceInfo} source The GeoTIFF source.\n * @param {Object} options Options for the GeoTIFF source.\n * @return {Promise>} Resolves to a list of images.\n */\nfunction getImagesForSource(source, options) {\n let request;\n if (source.blob) {\n request = tiffFromBlob(source.blob);\n } else if (source.overviews) {\n request = tiffFromUrls(source.url, source.overviews, options);\n } else {\n request = tiffFromUrl(source.url, options);\n }\n return request.then(getImagesForTIFF);\n}\n\n/**\n * @param {number|Array|Array>} expected Expected value.\n * @param {number|Array|Array>} got Actual value.\n * @param {number} tolerance Accepted tolerance in fraction of expected between expected and got.\n * @param {string} message The error message.\n * @param {function(Error):void} rejector A function to be called with any error.\n */\nfunction assertEqual(expected, got, tolerance, message, rejector) {\n if (Array.isArray(expected)) {\n const length = expected.length;\n if (!Array.isArray(got) || length != got.length) {\n const error = new Error(message);\n rejector(error);\n throw error;\n }\n for (let i = 0; i < length; ++i) {\n assertEqual(expected[i], got[i], tolerance, message, rejector);\n }\n return;\n }\n\n got = /** @type {number} */ (got);\n if (Math.abs(expected - got) > tolerance * expected) {\n throw new Error(message);\n }\n}\n\n/**\n * @param {Array} array The data array.\n * @return {number} The minimum value.\n */\nfunction getMinForDataType(array) {\n if (array instanceof Int8Array) {\n return -128;\n }\n if (array instanceof Int16Array) {\n return -32768;\n }\n if (array instanceof Int32Array) {\n return -2147483648;\n }\n if (array instanceof Float32Array) {\n return 1.2e-38;\n }\n return 0;\n}\n\n/**\n * @param {Array} array The data array.\n * @return {number} The maximum value.\n */\nfunction getMaxForDataType(array) {\n if (array instanceof Int8Array) {\n return 127;\n }\n if (array instanceof Uint8Array) {\n return 255;\n }\n if (array instanceof Uint8ClampedArray) {\n return 255;\n }\n if (array instanceof Int16Array) {\n return 32767;\n }\n if (array instanceof Uint16Array) {\n return 65535;\n }\n if (array instanceof Int32Array) {\n return 2147483647;\n }\n if (array instanceof Uint32Array) {\n return 4294967295;\n }\n if (array instanceof Float32Array) {\n return 3.4e38;\n }\n return 255;\n}\n\n/**\n * @typedef {Object} GeoTIFFSourceOptions\n * @property {boolean} [forceXHR=false] Whether to force the usage of the browsers XMLHttpRequest API.\n * @property {Object} [headers] additional key-value pairs of headers to be passed with each request. Key is the header name, value the header value.\n * @property {string} [credentials] How credentials shall be handled. See\n * https://developer.mozilla.org/en-US/docs/Web/API/fetch for reference and possible values\n * @property {number} [maxRanges] The maximum amount of ranges to request in a single multi-range request.\n * By default only a single range is used.\n * @property {boolean} [allowFullFile=false] Whether or not a full file is accepted when only a portion is\n * requested. Only use this when you know the source image to be small enough to fit in memory.\n * @property {number} [blockSize=65536] The block size to use.\n * @property {number} [cacheSize=100] The number of blocks that shall be held in a LRU cache.\n */\n\n/**\n * @typedef {Object} Options\n * @property {Array} sources List of information about GeoTIFF sources.\n * Multiple sources can be combined when their resolution sets are equal after applying a scale.\n * The list of sources defines a mapping between input bands as they are read from each GeoTIFF and\n * the output bands that are provided by data tiles. To control which bands to read from each GeoTIFF,\n * use the {@link import(\"./GeoTIFF.js\").SourceInfo bands} property. If, for example, you specify two\n * sources, one with 3 bands and {@link import(\"./GeoTIFF.js\").SourceInfo nodata} configured, and\n * another with 1 band, the resulting data tiles will have 5 bands: 3 from the first source, 1 alpha\n * band from the first source, and 1 band from the second source.\n * @property {GeoTIFFSourceOptions} [sourceOptions] Additional options to be passed to [geotiff.js](https://geotiffjs.github.io/geotiff.js/module-geotiff.html)'s `fromUrl` or `fromUrls` methods.\n * @property {true|false|'auto'} [convertToRGB=false] By default, bands from the sources are read as-is. When\n * reading GeoTIFFs with the purpose of displaying them as RGB images, setting this to `true` will\n * convert other color spaces (YCbCr, CMYK) to RGB. Setting the option to `'auto'` will make it so CMYK, YCbCr,\n * CIELab, and ICCLab images will automatically be converted to RGB.\n * @property {boolean} [normalize=true] By default, the source data is normalized to values between\n * 0 and 1 with scaling factors based on the raster statistics or `min` and `max` properties of each source.\n * If instead you want to work with the raw values in a style expression, set this to `false`. Setting this option\n * to `false` will make it so any `min` and `max` properties on sources are ignored.\n * @property {boolean} [opaque=false] Whether the layer is opaque.\n * @property {number} [transition=250] Duration of the opacity transition for rendering.\n * To disable the opacity transition, pass `transition: 0`.\n * @property {boolean} [wrapX=false] Render tiles beyond the tile grid extent.\n * @property {boolean} [interpolate=true] Use interpolated values when resampling. By default,\n * the linear interpolation is used to resample the data. If false, nearest neighbor is used.\n */\n\n/**\n * @classdesc\n * A source for working with GeoTIFF data.\n * **Note for users of the full build**: The `GeoTIFF` source requires the\n * [geotiff.js](https://github.com/geotiffjs/geotiff.js) library to be loaded as well.\n *\n * @api\n */\nclass GeoTIFFSource extends DataTile {\n /**\n * @param {Options} options Data tile options.\n */\n constructor(options) {\n super({\n state: 'loading',\n tileGrid: null,\n projection: null,\n opaque: options.opaque,\n transition: options.transition,\n interpolate: options.interpolate !== false,\n wrapX: options.wrapX,\n });\n\n /**\n * @type {Array}\n * @private\n */\n this.sourceInfo_ = options.sources;\n\n const numSources = this.sourceInfo_.length;\n\n /**\n * @type {Object}\n * @private\n */\n this.sourceOptions_ = options.sourceOptions;\n\n /**\n * @type {Array>}\n * @private\n */\n this.sourceImagery_ = new Array(numSources);\n\n /**\n * @type {Array>}\n * @private\n */\n this.sourceMasks_ = new Array(numSources);\n\n /**\n * @type {Array}\n * @private\n */\n this.resolutionFactors_ = new Array(numSources);\n\n /**\n * @type {Array}\n * @private\n */\n this.samplesPerPixel_;\n\n /**\n * @type {Array>}\n * @private\n */\n this.nodataValues_;\n\n /**\n * @type {Array>}\n * @private\n */\n this.metadata_;\n\n /**\n * @type {boolean}\n * @private\n */\n this.normalize_ = options.normalize !== false;\n\n /**\n * @type {boolean}\n * @private\n */\n this.addAlpha_ = false;\n\n /**\n * @type {Error}\n * @private\n */\n this.error_ = null;\n\n /**\n * @type {true|false|'auto'}\n */\n this.convertToRGB_ = options.convertToRGB || false;\n\n this.setKey(this.sourceInfo_.map((source) => source.url).join(','));\n\n const self = this;\n const requests = new Array(numSources);\n for (let i = 0; i < numSources; ++i) {\n requests[i] = getImagesForSource(\n this.sourceInfo_[i],\n this.sourceOptions_\n );\n }\n Promise.all(requests)\n .then(function (sources) {\n self.configure_(sources);\n })\n .catch(function (error) {\n logError(error);\n self.error_ = error;\n self.setState('error');\n });\n }\n\n /**\n * @return {Error} A source loading error. When the source state is `error`, use this function\n * to get more information about the error. To debug a faulty configuration, you may want to use\n * a listener like\n * ```js\n * geotiffSource.on('change', () => {\n * if (geotiffSource.getState() === 'error') {\n * console.error(geotiffSource.getError());\n * }\n * });\n * ```\n */\n getError() {\n return this.error_;\n }\n\n /**\n * Determine the projection of the images in this GeoTIFF.\n * The default implementation looks at the ProjectedCSTypeGeoKey and the GeographicTypeGeoKey\n * of each image in turn.\n * You can override this method in a subclass to support more projections.\n *\n * @param {Array>} sources Each source is a list of images\n * from a single GeoTIFF.\n */\n determineProjection(sources) {\n const firstSource = sources[0];\n for (let i = firstSource.length - 1; i >= 0; --i) {\n const image = firstSource[i];\n const projection = getProjection(image);\n if (projection) {\n this.projection = projection;\n break;\n }\n }\n }\n\n /**\n * Configure the tile grid based on images within the source GeoTIFFs. Each GeoTIFF\n * must have the same internal tiled structure.\n * @param {Array>} sources Each source is a list of images\n * from a single GeoTIFF.\n * @private\n */\n configure_(sources) {\n let extent;\n let origin;\n let commonRenderTileSizes;\n let commonSourceTileSizes;\n let resolutions;\n const samplesPerPixel = new Array(sources.length);\n const nodataValues = new Array(sources.length);\n const metadata = new Array(sources.length);\n let minZoom = 0;\n\n const sourceCount = sources.length;\n for (let sourceIndex = 0; sourceIndex < sourceCount; ++sourceIndex) {\n const images = [];\n const masks = [];\n sources[sourceIndex].forEach((item) => {\n if (isMask(item)) {\n masks.push(item);\n } else {\n images.push(item);\n }\n });\n\n const imageCount = images.length;\n if (masks.length > 0 && masks.length !== imageCount) {\n throw new Error(\n `Expected one mask per image found ${masks.length} masks and ${imageCount} images`\n );\n }\n\n let sourceExtent;\n let sourceOrigin;\n const sourceTileSizes = new Array(imageCount);\n const renderTileSizes = new Array(imageCount);\n const sourceResolutions = new Array(imageCount);\n\n nodataValues[sourceIndex] = new Array(imageCount);\n metadata[sourceIndex] = new Array(imageCount);\n\n for (let imageIndex = 0; imageIndex < imageCount; ++imageIndex) {\n const image = images[imageIndex];\n const nodataValue = image.getGDALNoData();\n metadata[sourceIndex][imageIndex] = image.getGDALMetadata(0);\n nodataValues[sourceIndex][imageIndex] = nodataValue;\n\n const wantedSamples = this.sourceInfo_[sourceIndex].bands;\n samplesPerPixel[sourceIndex] = wantedSamples\n ? wantedSamples.length\n : image.getSamplesPerPixel();\n const level = imageCount - (imageIndex + 1);\n\n if (!sourceExtent) {\n sourceExtent = getBoundingBox(image);\n }\n\n if (!sourceOrigin) {\n sourceOrigin = getOrigin(image);\n }\n\n const imageResolutions = getResolutions(image, images[0]);\n sourceResolutions[level] = imageResolutions[0];\n\n const sourceTileSize = [image.getTileWidth(), image.getTileHeight()];\n\n // request larger blocks for untiled layouts\n if (\n sourceTileSize[0] !== sourceTileSize[1] &&\n sourceTileSize[1] < defaultTileSize\n ) {\n sourceTileSize[0] = defaultTileSize;\n sourceTileSize[1] = defaultTileSize;\n }\n\n sourceTileSizes[level] = sourceTileSize;\n\n const aspectRatio = imageResolutions[0] / Math.abs(imageResolutions[1]);\n renderTileSizes[level] = [\n sourceTileSize[0],\n sourceTileSize[1] / aspectRatio,\n ];\n }\n\n if (!extent) {\n extent = sourceExtent;\n } else {\n getIntersection(extent, sourceExtent, extent);\n }\n\n if (!origin) {\n origin = sourceOrigin;\n } else {\n const message = `Origin mismatch for source ${sourceIndex}, got [${sourceOrigin}] but expected [${origin}]`;\n assertEqual(origin, sourceOrigin, 0, message, this.viewRejector);\n }\n\n if (!resolutions) {\n resolutions = sourceResolutions;\n this.resolutionFactors_[sourceIndex] = 1;\n } else {\n if (resolutions.length - minZoom > sourceResolutions.length) {\n minZoom = resolutions.length - sourceResolutions.length;\n }\n const resolutionFactor =\n resolutions[resolutions.length - 1] /\n sourceResolutions[sourceResolutions.length - 1];\n this.resolutionFactors_[sourceIndex] = resolutionFactor;\n const scaledSourceResolutions = sourceResolutions.map(\n (resolution) => (resolution *= resolutionFactor)\n );\n const message = `Resolution mismatch for source ${sourceIndex}, got [${scaledSourceResolutions}] but expected [${resolutions}]`;\n assertEqual(\n resolutions.slice(minZoom, resolutions.length),\n scaledSourceResolutions,\n 0.02,\n message,\n this.viewRejector\n );\n }\n\n if (!commonRenderTileSizes) {\n commonRenderTileSizes = renderTileSizes;\n } else {\n assertEqual(\n commonRenderTileSizes.slice(minZoom, commonRenderTileSizes.length),\n renderTileSizes,\n 0.01,\n `Tile size mismatch for source ${sourceIndex}`,\n this.viewRejector\n );\n }\n\n if (!commonSourceTileSizes) {\n commonSourceTileSizes = sourceTileSizes;\n } else {\n assertEqual(\n commonSourceTileSizes.slice(minZoom, commonSourceTileSizes.length),\n sourceTileSizes,\n 0,\n `Tile size mismatch for source ${sourceIndex}`,\n this.viewRejector\n );\n }\n\n this.sourceImagery_[sourceIndex] = images.reverse();\n this.sourceMasks_[sourceIndex] = masks.reverse();\n }\n\n for (let i = 0, ii = this.sourceImagery_.length; i < ii; ++i) {\n const sourceImagery = this.sourceImagery_[i];\n while (sourceImagery.length < resolutions.length) {\n sourceImagery.unshift(undefined);\n }\n }\n\n if (!this.getProjection()) {\n this.determineProjection(sources);\n }\n\n this.samplesPerPixel_ = samplesPerPixel;\n this.nodataValues_ = nodataValues;\n this.metadata_ = metadata;\n\n // decide if we need to add an alpha band to handle nodata\n outer: for (let sourceIndex = 0; sourceIndex < sourceCount; ++sourceIndex) {\n // option 1: source is configured with a nodata value\n if (this.sourceInfo_[sourceIndex].nodata !== undefined) {\n this.addAlpha_ = true;\n break;\n }\n if (this.sourceMasks_[sourceIndex].length) {\n this.addAlpha_ = true;\n break;\n }\n\n const values = nodataValues[sourceIndex];\n\n // option 2: check image metadata for limited bands\n const bands = this.sourceInfo_[sourceIndex].bands;\n if (bands) {\n for (let i = 0; i < bands.length; ++i) {\n if (values[bands[i] - 1] !== null) {\n this.addAlpha_ = true;\n break outer;\n }\n }\n continue;\n }\n\n // option 3: check image metadata for all bands\n for (let imageIndex = 0; imageIndex < values.length; ++imageIndex) {\n if (values[imageIndex] !== null) {\n this.addAlpha_ = true;\n break outer;\n }\n }\n }\n\n let bandCount = this.addAlpha_ ? 1 : 0;\n for (let sourceIndex = 0; sourceIndex < sourceCount; ++sourceIndex) {\n bandCount += samplesPerPixel[sourceIndex];\n }\n this.bandCount = bandCount;\n\n const tileGrid = new TileGrid({\n extent: extent,\n minZoom: minZoom,\n origin: origin,\n resolutions: resolutions,\n tileSizes: commonRenderTileSizes,\n });\n\n this.tileGrid = tileGrid;\n this.setTileSizes(commonSourceTileSizes);\n\n this.setLoader(this.loadTile_.bind(this));\n this.setState('ready');\n\n const zoom = 1;\n if (resolutions.length === 2) {\n resolutions = [resolutions[0], resolutions[1], resolutions[1] / 2];\n } else if (resolutions.length === 1) {\n resolutions = [resolutions[0] * 2, resolutions[0], resolutions[0] / 2];\n }\n\n this.viewResolver({\n showFullExtent: true,\n projection: this.projection,\n resolutions: resolutions,\n center: toUserCoordinate(getCenter(extent), this.projection),\n extent: toUserExtent(extent, this.projection),\n zoom: zoom,\n });\n }\n\n /**\n * @param {number} z The z tile index.\n * @param {number} x The x tile index.\n * @param {number} y The y tile index.\n * @return {Promise} The composed tile data.\n * @private\n */\n loadTile_(z, x, y) {\n const sourceTileSize = this.getTileSize(z);\n const sourceCount = this.sourceImagery_.length;\n const requests = new Array(sourceCount * 2);\n const nodataValues = this.nodataValues_;\n const sourceInfo = this.sourceInfo_;\n const pool = getWorkerPool();\n for (let sourceIndex = 0; sourceIndex < sourceCount; ++sourceIndex) {\n const source = sourceInfo[sourceIndex];\n const resolutionFactor = this.resolutionFactors_[sourceIndex];\n const pixelBounds = [\n Math.round(x * (sourceTileSize[0] * resolutionFactor)),\n Math.round(y * (sourceTileSize[1] * resolutionFactor)),\n Math.round((x + 1) * (sourceTileSize[0] * resolutionFactor)),\n Math.round((y + 1) * (sourceTileSize[1] * resolutionFactor)),\n ];\n const image = this.sourceImagery_[sourceIndex][z];\n let samples;\n if (source.bands) {\n samples = source.bands.map(function (bandNumber) {\n return bandNumber - 1;\n });\n }\n\n /** @type {number|Array} */\n let fillValue;\n if ('nodata' in source && source.nodata !== null) {\n fillValue = source.nodata;\n } else {\n if (!samples) {\n fillValue = nodataValues[sourceIndex];\n } else {\n fillValue = samples.map(function (sampleIndex) {\n return nodataValues[sourceIndex][sampleIndex];\n });\n }\n }\n\n const readOptions = {\n window: pixelBounds,\n width: sourceTileSize[0],\n height: sourceTileSize[1],\n samples: samples,\n fillValue: fillValue,\n pool: pool,\n interleave: false,\n };\n if (readRGB(this.convertToRGB_, image)) {\n requests[sourceIndex] = image.readRGB(readOptions);\n } else {\n requests[sourceIndex] = image.readRasters(readOptions);\n }\n\n // requests after `sourceCount` are for mask data (if any)\n const maskIndex = sourceCount + sourceIndex;\n const mask = this.sourceMasks_[sourceIndex][z];\n if (!mask) {\n requests[maskIndex] = Promise.resolve(null);\n continue;\n }\n\n requests[maskIndex] = mask.readRasters({\n window: pixelBounds,\n width: sourceTileSize[0],\n height: sourceTileSize[1],\n samples: [0],\n pool: pool,\n interleave: false,\n });\n }\n\n return Promise.all(requests)\n .then(this.composeTile_.bind(this, sourceTileSize))\n .catch(function (error) {\n logError(error);\n throw error;\n });\n }\n\n /**\n * @param {import(\"../size.js\").Size} sourceTileSize The source tile size.\n * @param {Array} sourceSamples The source samples.\n * @return {import(\"../DataTile.js\").Data} The composed tile data.\n * @private\n */\n composeTile_(sourceTileSize, sourceSamples) {\n const metadata = this.metadata_;\n const sourceInfo = this.sourceInfo_;\n const sourceCount = this.sourceImagery_.length;\n const bandCount = this.bandCount;\n const samplesPerPixel = this.samplesPerPixel_;\n const nodataValues = this.nodataValues_;\n const normalize = this.normalize_;\n const addAlpha = this.addAlpha_;\n\n const pixelCount = sourceTileSize[0] * sourceTileSize[1];\n const dataLength = pixelCount * bandCount;\n\n /** @type {Uint8Array|Float32Array} */\n let data;\n if (normalize) {\n data = new Uint8Array(dataLength);\n } else {\n data = new Float32Array(dataLength);\n }\n\n let dataIndex = 0;\n for (let pixelIndex = 0; pixelIndex < pixelCount; ++pixelIndex) {\n let transparent = addAlpha;\n for (let sourceIndex = 0; sourceIndex < sourceCount; ++sourceIndex) {\n const source = sourceInfo[sourceIndex];\n\n let min = source.min;\n let max = source.max;\n let gain, bias;\n if (normalize) {\n const stats = metadata[sourceIndex][0];\n if (min === undefined) {\n if (stats && STATISTICS_MINIMUM in stats) {\n min = parseFloat(stats[STATISTICS_MINIMUM]);\n } else {\n min = getMinForDataType(sourceSamples[sourceIndex][0]);\n }\n }\n if (max === undefined) {\n if (stats && STATISTICS_MAXIMUM in stats) {\n max = parseFloat(stats[STATISTICS_MAXIMUM]);\n } else {\n max = getMaxForDataType(sourceSamples[sourceIndex][0]);\n }\n }\n\n gain = 255 / (max - min);\n bias = -min * gain;\n }\n\n for (\n let sampleIndex = 0;\n sampleIndex < samplesPerPixel[sourceIndex];\n ++sampleIndex\n ) {\n const sourceValue =\n sourceSamples[sourceIndex][sampleIndex][pixelIndex];\n\n let value;\n if (normalize) {\n value = clamp(gain * sourceValue + bias, 0, 255);\n } else {\n value = sourceValue;\n }\n\n if (!addAlpha) {\n data[dataIndex] = value;\n } else {\n let nodata = source.nodata;\n if (nodata === undefined) {\n let bandIndex;\n if (source.bands) {\n bandIndex = source.bands[sampleIndex] - 1;\n } else {\n bandIndex = sampleIndex;\n }\n nodata = nodataValues[sourceIndex][bandIndex];\n }\n\n const nodataIsNaN = isNaN(nodata);\n if (\n (!nodataIsNaN && sourceValue !== nodata) ||\n (nodataIsNaN && !isNaN(sourceValue))\n ) {\n transparent = false;\n data[dataIndex] = value;\n }\n }\n dataIndex++;\n }\n if (!transparent) {\n const maskIndex = sourceCount + sourceIndex;\n const mask = sourceSamples[maskIndex];\n if (mask && !mask[0][pixelIndex]) {\n transparent = true;\n }\n }\n }\n if (addAlpha) {\n if (!transparent) {\n data[dataIndex] = 255;\n }\n dataIndex++;\n }\n }\n\n return data;\n }\n}\n\n/**\n * Get a promise for view properties based on the source. Use the result of this function\n * as the `view` option in a map constructor.\n *\n * const source = new GeoTIFF(options);\n *\n * const map = new Map({\n * target: 'map',\n * layers: [\n * new TileLayer({\n * source: source,\n * }),\n * ],\n * view: source.getView(),\n * });\n *\n * @function\n * @return {Promise} A promise for view-related properties.\n * @api\n *\n */\nGeoTIFFSource.prototype.getView;\n\nexport default GeoTIFFSource;\n","/**\n * @module ol/source/Zoomify\n */\nimport {DEFAULT_TILE_SIZE} from '../tilegrid/common.js';\n\nimport ImageTile from '../ImageTile.js';\nimport TileGrid from '../tilegrid/TileGrid.js';\nimport TileImage from './TileImage.js';\nimport TileState from '../TileState.js';\nimport {assert} from '../asserts.js';\nimport {createCanvasContext2D} from '../dom.js';\nimport {createFromTileUrlFunctions, expandUrl} from '../tileurlfunction.js';\nimport {getCenter} from '../extent.js';\nimport {toSize} from '../size.js';\n\n/**\n * @typedef {'default' | 'truncated'} TierSizeCalculation\n */\n\nexport class CustomTile extends ImageTile {\n /**\n * @param {import(\"../size.js\").Size} tileSize Full tile size.\n * @param {import(\"../tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n * @param {import(\"../TileState.js\").default} state State.\n * @param {string} src Image source URI.\n * @param {?string} crossOrigin Cross origin.\n * @param {import(\"../Tile.js\").LoadFunction} tileLoadFunction Tile load function.\n * @param {import(\"../Tile.js\").Options} [options] Tile options.\n */\n constructor(\n tileSize,\n tileCoord,\n state,\n src,\n crossOrigin,\n tileLoadFunction,\n options\n ) {\n super(tileCoord, state, src, crossOrigin, tileLoadFunction, options);\n\n /**\n * @private\n * @type {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement}\n */\n this.zoomifyImage_ = null;\n\n /**\n * @type {import(\"../size.js\").Size}\n */\n this.tileSize_ = tileSize;\n }\n\n /**\n * Get the image element for this tile.\n * @return {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} Image.\n */\n getImage() {\n if (this.zoomifyImage_) {\n return this.zoomifyImage_;\n }\n const image = super.getImage();\n if (this.state == TileState.LOADED) {\n const tileSize = this.tileSize_;\n if (image.width == tileSize[0] && image.height == tileSize[1]) {\n this.zoomifyImage_ = image;\n return image;\n }\n const context = createCanvasContext2D(tileSize[0], tileSize[1]);\n context.drawImage(image, 0, 0);\n this.zoomifyImage_ = context.canvas;\n return context.canvas;\n }\n return image;\n }\n}\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {number} [cacheSize] Initial tile cache size. Will auto-grow to hold at least the number of tiles in the viewport.\n * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images. Note that\n * you must provide a `crossOrigin` value you want to access pixel data with the Canvas renderer.\n * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.\n * @property {boolean} [interpolate=true] Use interpolated values when resampling. By default,\n * linear interpolation is used when resampling. Set to false to use the nearest neighbor instead.\n * @property {import(\"../proj.js\").ProjectionLike} [projection] Projection.\n * @property {number} [tilePixelRatio] The pixel ratio used by the tile service. For example, if the tile service advertizes 256px by 256px tiles but actually sends 512px by 512px images (for retina/hidpi devices) then `tilePixelRatio` should be set to `2`\n * @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).\n * Higher values can increase reprojection performance, but decrease precision.\n * @property {string} url URL template or base URL of the Zoomify service.\n * A base URL is the fixed part\n * of the URL, excluding the tile group, z, x, and y folder structure, e.g.\n * `http://my.zoomify.info/IMAGE.TIF/`. A URL template must include\n * `{TileGroup}`, `{x}`, `{y}`, and `{z}` placeholders, e.g.\n * `http://my.zoomify.info/IMAGE.TIF/{TileGroup}/{z}-{x}-{y}.jpg`.\n * Internet Imaging Protocol (IIP) with JTL extension can be also used with\n * `{tileIndex}` and `{z}` placeholders, e.g.\n * `http://my.zoomify.info?FIF=IMAGE.TIF&JTL={z},{tileIndex}`.\n * A `{?-?}` template pattern, for example `subdomain{a-f}.domain.com`, may be\n * used instead of defining each one separately in the `urls` option.\n * @property {TierSizeCalculation} [tierSizeCalculation] Tier size calculation method: `default` or `truncated`.\n * @property {import(\"../size.js\").Size} size Size.\n * @property {import(\"../extent.js\").Extent} [extent] Extent for the TileGrid that is created.\n * Default sets the TileGrid in the\n * fourth quadrant, meaning extent is `[0, -height, width, 0]`. To change the\n * extent to the first quadrant (the default for OpenLayers 2) set the extent\n * as `[0, 0, width, height]`.\n * @property {number} [transition] Duration of the opacity transition for rendering.\n * To disable the opacity transition, pass `transition: 0`.\n * @property {number} [tileSize=256] Tile size. Same tile size is used for all zoom levels.\n * @property {number|import(\"../array.js\").NearestDirectionFunction} [zDirection=0]\n * Choose whether to use tiles with a higher or lower zoom level when between integer\n * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.\n */\n\n/**\n * @classdesc\n * Layer source for tile data in Zoomify format (both Zoomify and Internet\n * Imaging Protocol are supported).\n * @api\n */\nclass Zoomify extends TileImage {\n /**\n * @param {Options} options Options.\n */\n constructor(options) {\n const size = options.size;\n const tierSizeCalculation =\n options.tierSizeCalculation !== undefined\n ? options.tierSizeCalculation\n : 'default';\n\n const tilePixelRatio = options.tilePixelRatio || 1;\n const imageWidth = size[0];\n const imageHeight = size[1];\n const tierSizeInTiles = [];\n const tileSize = options.tileSize || DEFAULT_TILE_SIZE;\n let tileSizeForTierSizeCalculation = tileSize * tilePixelRatio;\n\n switch (tierSizeCalculation) {\n case 'default':\n while (\n imageWidth > tileSizeForTierSizeCalculation ||\n imageHeight > tileSizeForTierSizeCalculation\n ) {\n tierSizeInTiles.push([\n Math.ceil(imageWidth / tileSizeForTierSizeCalculation),\n Math.ceil(imageHeight / tileSizeForTierSizeCalculation),\n ]);\n tileSizeForTierSizeCalculation += tileSizeForTierSizeCalculation;\n }\n break;\n case 'truncated':\n let width = imageWidth;\n let height = imageHeight;\n while (\n width > tileSizeForTierSizeCalculation ||\n height > tileSizeForTierSizeCalculation\n ) {\n tierSizeInTiles.push([\n Math.ceil(width / tileSizeForTierSizeCalculation),\n Math.ceil(height / tileSizeForTierSizeCalculation),\n ]);\n width >>= 1;\n height >>= 1;\n }\n break;\n default: // Unknown `tierSizeCalculation` configured\n assert(false, 53);\n break;\n }\n\n tierSizeInTiles.push([1, 1]);\n tierSizeInTiles.reverse();\n\n const resolutions = [tilePixelRatio];\n const tileCountUpToTier = [0];\n for (let i = 1, ii = tierSizeInTiles.length; i < ii; i++) {\n resolutions.push(tilePixelRatio << i);\n tileCountUpToTier.push(\n tierSizeInTiles[i - 1][0] * tierSizeInTiles[i - 1][1] +\n tileCountUpToTier[i - 1]\n );\n }\n resolutions.reverse();\n\n const tileGrid = new TileGrid({\n tileSize: tileSize,\n extent: options.extent || [0, -imageHeight, imageWidth, 0],\n resolutions: resolutions,\n });\n\n let url = options.url;\n if (url && !url.includes('{TileGroup}') && !url.includes('{tileIndex}')) {\n url += '{TileGroup}/{z}-{x}-{y}.jpg';\n }\n const urls = expandUrl(url);\n\n let tileWidth = tileSize * tilePixelRatio;\n\n /**\n * @param {string} template Template.\n * @return {import(\"../Tile.js\").UrlFunction} Tile URL function.\n */\n function createFromTemplate(template) {\n return (\n /**\n * @param {import(\"../tilecoord.js\").TileCoord} tileCoord Tile Coordinate.\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {string|undefined} Tile URL.\n */\n function (tileCoord, pixelRatio, projection) {\n if (!tileCoord) {\n return undefined;\n }\n const tileCoordZ = tileCoord[0];\n const tileCoordX = tileCoord[1];\n const tileCoordY = tileCoord[2];\n const tileIndex =\n tileCoordX + tileCoordY * tierSizeInTiles[tileCoordZ][0];\n const tileGroup =\n ((tileIndex + tileCountUpToTier[tileCoordZ]) / tileWidth) | 0;\n const localContext = {\n 'z': tileCoordZ,\n 'x': tileCoordX,\n 'y': tileCoordY,\n 'tileIndex': tileIndex,\n 'TileGroup': 'TileGroup' + tileGroup,\n };\n return template.replace(/\\{(\\w+?)\\}/g, function (m, p) {\n return localContext[p];\n });\n }\n );\n }\n\n const tileUrlFunction = createFromTileUrlFunctions(\n urls.map(createFromTemplate)\n );\n\n const ZoomifyTileClass = CustomTile.bind(\n null,\n toSize(tileSize * tilePixelRatio)\n );\n\n super({\n attributions: options.attributions,\n cacheSize: options.cacheSize,\n crossOrigin: options.crossOrigin,\n interpolate: options.interpolate,\n projection: options.projection,\n tilePixelRatio: tilePixelRatio,\n reprojectionErrorThreshold: options.reprojectionErrorThreshold,\n tileClass: ZoomifyTileClass,\n tileGrid: tileGrid,\n tileUrlFunction: tileUrlFunction,\n transition: options.transition,\n });\n\n /**\n * @type {number|import(\"../array.js\").NearestDirectionFunction}\n */\n this.zDirection = options.zDirection;\n\n // Server retina tile detection (non-standard):\n // Try loading the center tile for the highest resolution. If it is not\n // available, we are dealing with retina tiles, and need to adjust the\n // tile url calculation.\n const tileUrl = tileGrid.getTileCoordForCoordAndResolution(\n getCenter(tileGrid.getExtent()),\n resolutions[resolutions.length - 1]\n );\n const testTileUrl = tileUrlFunction(tileUrl, 1, null);\n const image = new Image();\n image.addEventListener('error', () => {\n tileWidth = tileSize;\n this.changed();\n });\n image.src = testTileUrl;\n }\n}\n\nexport default Zoomify;\n","/**\n * @module ol/format/IIIFInfo\n */\n\nimport {assert} from '../asserts.js';\n\n/**\n * @typedef {Object} PreferredOptions\n * @property {string} [format] Preferred image format. Will be used if the image information\n * indicates support for that format.\n * @property {string} [quality] IIIF image qualitiy. Will be used if the image information\n * indicates support for that quality.\n */\n\n/**\n * @typedef {Object} SupportedFeatures\n * @property {Array} [supports] Supported IIIF image size and region\n * calculation features.\n * @property {Array} [formats] Supported image formats.\n * @property {Array} [qualities] Supported IIIF image qualities.\n */\n\n/**\n * @typedef {Object} TileInfo\n * @property {Array} scaleFactors Supported resolution scaling factors.\n * @property {number} width Tile width in pixels.\n * @property {number} [height] Tile height in pixels. Same as tile width if height is\n * not given.\n */\n\n/**\n * @typedef {Object} IiifProfile\n * @property {Array} [formats] Supported image formats for the image service.\n * @property {Array} [qualities] Supported IIIF image qualities.\n * @property {Array} [supports] Supported features.\n * @property {number} [maxArea] Maximum area (pixels) available for this image service.\n * @property {number} [maxHeight] Maximum height.\n * @property {number} [maxWidth] Maximum width.\n */\n\n/**\n * @typedef {Object|TileInfo>>}\n * ImageInformationResponse\n */\n\n/**\n * Enum representing the major IIIF Image API versions\n * @enum {string}\n */\nexport const Versions = {\n VERSION1: 'version1',\n VERSION2: 'version2',\n VERSION3: 'version3',\n};\n\n/**\n * Supported image formats, qualities and supported region / size calculation features\n * for different image API versions and compliance levels\n * @const\n * @type {Object>}\n */\nconst IIIF_PROFILE_VALUES = {};\nIIIF_PROFILE_VALUES[Versions.VERSION1] = {\n 'level0': {\n supports: [],\n formats: [],\n qualities: ['native'],\n },\n 'level1': {\n supports: ['regionByPx', 'sizeByW', 'sizeByH', 'sizeByPct'],\n formats: ['jpg'],\n qualities: ['native'],\n },\n 'level2': {\n supports: [\n 'regionByPx',\n 'regionByPct',\n 'sizeByW',\n 'sizeByH',\n 'sizeByPct',\n 'sizeByConfinedWh',\n 'sizeByWh',\n ],\n formats: ['jpg', 'png'],\n qualities: ['native', 'color', 'grey', 'bitonal'],\n },\n};\nIIIF_PROFILE_VALUES[Versions.VERSION2] = {\n 'level0': {\n supports: [],\n formats: ['jpg'],\n qualities: ['default'],\n },\n 'level1': {\n supports: ['regionByPx', 'sizeByW', 'sizeByH', 'sizeByPct'],\n formats: ['jpg'],\n qualities: ['default'],\n },\n 'level2': {\n supports: [\n 'regionByPx',\n 'regionByPct',\n 'sizeByW',\n 'sizeByH',\n 'sizeByPct',\n 'sizeByConfinedWh',\n 'sizeByDistortedWh',\n 'sizeByWh',\n ],\n formats: ['jpg', 'png'],\n qualities: ['default', 'bitonal'],\n },\n};\nIIIF_PROFILE_VALUES[Versions.VERSION3] = {\n 'level0': {\n supports: [],\n formats: ['jpg'],\n qualities: ['default'],\n },\n 'level1': {\n supports: ['regionByPx', 'regionSquare', 'sizeByW', 'sizeByH', 'sizeByWh'],\n formats: ['jpg'],\n qualities: ['default'],\n },\n 'level2': {\n supports: [\n 'regionByPx',\n 'regionSquare',\n 'regionByPct',\n 'sizeByW',\n 'sizeByH',\n 'sizeByPct',\n 'sizeByConfinedWh',\n 'sizeByWh',\n ],\n formats: ['jpg', 'png'],\n qualities: ['default'],\n },\n};\nIIIF_PROFILE_VALUES['none'] = {\n 'none': {\n supports: [],\n formats: [],\n qualities: [],\n },\n};\n\nconst COMPLIANCE_VERSION1 =\n /^https?:\\/\\/library\\.stanford\\.edu\\/iiif\\/image-api\\/(?:1\\.1\\/)?compliance\\.html#level[0-2]$/;\nconst COMPLIANCE_VERSION2 =\n /^https?:\\/\\/iiif\\.io\\/api\\/image\\/2\\/level[0-2](?:\\.json)?$/;\nconst COMPLIANCE_VERSION3 =\n /(^https?:\\/\\/iiif\\.io\\/api\\/image\\/3\\/level[0-2](?:\\.json)?$)|(^level[0-2]$)/;\n\nfunction generateVersion1Options(iiifInfo) {\n let levelProfile = iiifInfo.getComplianceLevelSupportedFeatures();\n // Version 1.0 and 1.1 do not require a profile.\n if (levelProfile === undefined) {\n levelProfile = IIIF_PROFILE_VALUES[Versions.VERSION1]['level0'];\n }\n return {\n url:\n iiifInfo.imageInfo['@id'] === undefined\n ? undefined\n : iiifInfo.imageInfo['@id'].replace(/\\/?(?:info\\.json)?$/g, ''),\n supports: levelProfile.supports,\n formats: [\n ...levelProfile.formats,\n iiifInfo.imageInfo.formats === undefined\n ? []\n : iiifInfo.imageInfo.formats,\n ],\n qualities: [\n ...levelProfile.qualities,\n iiifInfo.imageInfo.qualities === undefined\n ? []\n : iiifInfo.imageInfo.qualities,\n ],\n resolutions: iiifInfo.imageInfo.scale_factors,\n tileSize:\n iiifInfo.imageInfo.tile_width !== undefined\n ? iiifInfo.imageInfo.tile_height !== undefined\n ? [iiifInfo.imageInfo.tile_width, iiifInfo.imageInfo.tile_height]\n : [iiifInfo.imageInfo.tile_width, iiifInfo.imageInfo.tile_width]\n : iiifInfo.imageInfo.tile_height != undefined\n ? [iiifInfo.imageInfo.tile_height, iiifInfo.imageInfo.tile_height]\n : undefined,\n };\n}\n\nfunction generateVersion2Options(iiifInfo) {\n const levelProfile = iiifInfo.getComplianceLevelSupportedFeatures(),\n additionalProfile =\n Array.isArray(iiifInfo.imageInfo.profile) &&\n iiifInfo.imageInfo.profile.length > 1,\n profileSupports =\n additionalProfile && iiifInfo.imageInfo.profile[1].supports\n ? iiifInfo.imageInfo.profile[1].supports\n : [],\n profileFormats =\n additionalProfile && iiifInfo.imageInfo.profile[1].formats\n ? iiifInfo.imageInfo.profile[1].formats\n : [],\n profileQualities =\n additionalProfile && iiifInfo.imageInfo.profile[1].qualities\n ? iiifInfo.imageInfo.profile[1].qualities\n : [];\n return {\n url: iiifInfo.imageInfo['@id'].replace(/\\/?(?:info\\.json)?$/g, ''),\n sizes:\n iiifInfo.imageInfo.sizes === undefined\n ? undefined\n : iiifInfo.imageInfo.sizes.map(function (size) {\n return [size.width, size.height];\n }),\n tileSize:\n iiifInfo.imageInfo.tiles === undefined\n ? undefined\n : [\n iiifInfo.imageInfo.tiles.map(function (tile) {\n return tile.width;\n })[0],\n iiifInfo.imageInfo.tiles.map(function (tile) {\n return tile.height === undefined ? tile.width : tile.height;\n })[0],\n ],\n resolutions:\n iiifInfo.imageInfo.tiles === undefined\n ? undefined\n : iiifInfo.imageInfo.tiles.map(function (tile) {\n return tile.scaleFactors;\n })[0],\n supports: [...levelProfile.supports, ...profileSupports],\n formats: [...levelProfile.formats, ...profileFormats],\n qualities: [...levelProfile.qualities, ...profileQualities],\n };\n}\n\nfunction generateVersion3Options(iiifInfo) {\n const levelProfile = iiifInfo.getComplianceLevelSupportedFeatures(),\n formats =\n iiifInfo.imageInfo.extraFormats === undefined\n ? levelProfile.formats\n : [...levelProfile.formats, ...iiifInfo.imageInfo.extraFormats],\n preferredFormat =\n iiifInfo.imageInfo.preferredFormats !== undefined &&\n Array.isArray(iiifInfo.imageInfo.preferredFormats) &&\n iiifInfo.imageInfo.preferredFormats.length > 0\n ? iiifInfo.imageInfo.preferredFormats\n .filter(function (format) {\n return ['jpg', 'png', 'gif'].includes(format);\n })\n .reduce(function (acc, format) {\n return acc === undefined && formats.includes(format)\n ? format\n : acc;\n }, undefined)\n : undefined;\n return {\n url: iiifInfo.imageInfo['id'],\n sizes:\n iiifInfo.imageInfo.sizes === undefined\n ? undefined\n : iiifInfo.imageInfo.sizes.map(function (size) {\n return [size.width, size.height];\n }),\n tileSize:\n iiifInfo.imageInfo.tiles === undefined\n ? undefined\n : [\n iiifInfo.imageInfo.tiles.map(function (tile) {\n return tile.width;\n })[0],\n iiifInfo.imageInfo.tiles.map(function (tile) {\n return tile.height;\n })[0],\n ],\n resolutions:\n iiifInfo.imageInfo.tiles === undefined\n ? undefined\n : iiifInfo.imageInfo.tiles.map(function (tile) {\n return tile.scaleFactors;\n })[0],\n supports:\n iiifInfo.imageInfo.extraFeatures === undefined\n ? levelProfile.supports\n : [...levelProfile.supports, ...iiifInfo.imageInfo.extraFeatures],\n formats: formats,\n qualities:\n iiifInfo.imageInfo.extraQualities === undefined\n ? levelProfile.qualities\n : [...levelProfile.qualities, ...iiifInfo.imageInfo.extraQualities],\n preferredFormat: preferredFormat,\n };\n}\n\nconst versionFunctions = {};\nversionFunctions[Versions.VERSION1] = generateVersion1Options;\nversionFunctions[Versions.VERSION2] = generateVersion2Options;\nversionFunctions[Versions.VERSION3] = generateVersion3Options;\n\n/**\n * @classdesc\n * Format for transforming IIIF Image API image information responses into\n * IIIF tile source ready options\n *\n * @api\n */\nclass IIIFInfo {\n /**\n * @param {string|ImageInformationResponse} imageInfo\n * Deserialized image information JSON response object or JSON response as string\n */\n constructor(imageInfo) {\n this.setImageInfo(imageInfo);\n }\n\n /**\n * @param {string|ImageInformationResponse} imageInfo\n * Deserialized image information JSON response object or JSON response as string\n * @api\n */\n setImageInfo(imageInfo) {\n if (typeof imageInfo == 'string') {\n this.imageInfo = JSON.parse(imageInfo);\n } else {\n this.imageInfo = imageInfo;\n }\n }\n\n /**\n * @return {Versions|undefined} Major IIIF version.\n * @api\n */\n getImageApiVersion() {\n if (this.imageInfo === undefined) {\n return undefined;\n }\n let context = this.imageInfo['@context'] || 'ol-no-context';\n if (typeof context == 'string') {\n context = [context];\n }\n for (let i = 0; i < context.length; i++) {\n switch (context[i]) {\n case 'http://library.stanford.edu/iiif/image-api/1.1/context.json':\n case 'http://iiif.io/api/image/1/context.json':\n return Versions.VERSION1;\n case 'http://iiif.io/api/image/2/context.json':\n return Versions.VERSION2;\n case 'http://iiif.io/api/image/3/context.json':\n return Versions.VERSION3;\n case 'ol-no-context':\n // Image API 1.0 has no '@context'\n if (\n this.getComplianceLevelEntryFromProfile(Versions.VERSION1) &&\n this.imageInfo.identifier\n ) {\n return Versions.VERSION1;\n }\n break;\n default:\n }\n }\n assert(false, 61);\n }\n\n /**\n * @param {Versions} version Optional IIIF image API version\n * @return {string|undefined} Compliance level as it appears in the IIIF image information\n * response.\n */\n getComplianceLevelEntryFromProfile(version) {\n if (this.imageInfo === undefined || this.imageInfo.profile === undefined) {\n return undefined;\n }\n if (version === undefined) {\n version = this.getImageApiVersion();\n }\n switch (version) {\n case Versions.VERSION1:\n if (COMPLIANCE_VERSION1.test(this.imageInfo.profile)) {\n return this.imageInfo.profile;\n }\n break;\n case Versions.VERSION3:\n if (COMPLIANCE_VERSION3.test(this.imageInfo.profile)) {\n return this.imageInfo.profile;\n }\n break;\n case Versions.VERSION2:\n if (\n typeof this.imageInfo.profile === 'string' &&\n COMPLIANCE_VERSION2.test(this.imageInfo.profile)\n ) {\n return this.imageInfo.profile;\n }\n if (\n Array.isArray(this.imageInfo.profile) &&\n this.imageInfo.profile.length > 0 &&\n typeof this.imageInfo.profile[0] === 'string' &&\n COMPLIANCE_VERSION2.test(this.imageInfo.profile[0])\n ) {\n return this.imageInfo.profile[0];\n }\n break;\n default:\n }\n return undefined;\n }\n\n /**\n * @param {Versions} version Optional IIIF image API version\n * @return {string} Compliance level, on of 'level0', 'level1' or 'level2' or undefined\n */\n getComplianceLevelFromProfile(version) {\n const complianceLevel = this.getComplianceLevelEntryFromProfile(version);\n if (complianceLevel === undefined) {\n return undefined;\n }\n const level = complianceLevel.match(/level[0-2](?:\\.json)?$/g);\n return Array.isArray(level) ? level[0].replace('.json', '') : undefined;\n }\n\n /**\n * @return {SupportedFeatures|undefined} Image formats, qualities and region / size calculation\n * methods that are supported by the IIIF service.\n */\n getComplianceLevelSupportedFeatures() {\n if (this.imageInfo === undefined) {\n return undefined;\n }\n const version = this.getImageApiVersion();\n const level = this.getComplianceLevelFromProfile(version);\n if (level === undefined) {\n return IIIF_PROFILE_VALUES['none']['none'];\n }\n return IIIF_PROFILE_VALUES[version][level];\n }\n\n /**\n * @param {PreferredOptions} [preferredOptions] Optional options for preferred format and quality.\n * @return {import(\"../source/IIIF.js\").Options|undefined} IIIF tile source ready constructor options.\n * @api\n */\n getTileSourceOptions(preferredOptions) {\n const options = preferredOptions || {},\n version = this.getImageApiVersion();\n if (version === undefined) {\n return undefined;\n }\n const imageOptions =\n version === undefined ? undefined : versionFunctions[version](this);\n if (imageOptions === undefined) {\n return undefined;\n }\n return {\n url: imageOptions.url,\n version: version,\n size: [this.imageInfo.width, this.imageInfo.height],\n sizes: imageOptions.sizes,\n format:\n options.format !== undefined &&\n imageOptions.formats.includes(options.format)\n ? options.format\n : imageOptions.preferredFormat !== undefined\n ? imageOptions.preferredFormat\n : 'jpg',\n supports: imageOptions.supports,\n quality:\n options.quality && imageOptions.qualities.includes(options.quality)\n ? options.quality\n : imageOptions.qualities.includes('native')\n ? 'native'\n : 'default',\n resolutions: Array.isArray(imageOptions.resolutions)\n ? imageOptions.resolutions.sort(function (a, b) {\n return b - a;\n })\n : undefined,\n tileSize: imageOptions.tileSize,\n };\n }\n}\n\nexport default IIIFInfo;\n","/**\n * @module ol/source/IIIF\n */\n\nimport TileGrid from '../tilegrid/TileGrid.js';\nimport TileImage from './TileImage.js';\nimport {CustomTile} from './Zoomify.js';\nimport {DEFAULT_TILE_SIZE} from '../tilegrid/common.js';\nimport {Versions} from '../format/IIIFInfo.js';\nimport {assert} from '../asserts.js';\nimport {getTopLeft} from '../extent.js';\nimport {toSize} from '../size.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.\n * @property {number} [cacheSize] Size of the cache.\n * @property {null|string} [crossOrigin] The value for the crossOrigin option of the request.\n * @property {import(\"../extent.js\").Extent} [extent=[0, -height, width, 0]] The extent.\n * @property {string} [format='jpg'] Requested image format.\n * @property {boolean} [interpolate=true] Use interpolated values when resampling. By default,\n * linear interpolation is used when resampling. Set to false to use the nearest neighbor instead.\n * @property {import(\"../proj.js\").ProjectionLike} [projection] Projection.\n * @property {string} [quality] Requested IIIF image quality. Default is 'native'\n * for version 1, 'default' for versions 2 and 3.\n * @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).\n * Higher values can increase reprojection performance, but decrease precision.\n * @property {Array} [resolutions] Supported resolutions as given in IIIF 'scaleFactors'\n * @property {import(\"../size.js\").Size} size Size of the image [width, height].\n * @property {Array} [sizes] Supported scaled image sizes.\n * Content of the IIIF info.json 'sizes' property, but as array of Size objects.\n * @property {import(\"./Source.js\").State} [state] Source state.\n * @property {Array} [supports=[]] Supported IIIF region and size calculation\n * features.\n * @property {number} [tilePixelRatio] Tile pixel ratio.\n * @property {number|import(\"../size.js\").Size} [tileSize] Tile size.\n * Same tile size is used for all zoom levels. If tile size is a number,\n * a square tile is assumed. If the IIIF image service supports arbitrary\n * tiling (sizeByH, sizeByW, sizeByWh or sizeByPct as well as regionByPx or regionByPct\n * are supported), the default tilesize is 256.\n * @property {number} [transition] Transition.\n * @property {string} [url] Base URL of the IIIF Image service.\n * This should be the same as the IIIF Image ID.\n * @property {import(\"../format/IIIFInfo.js\").Versions} [version=Versions.VERSION2] Service's IIIF Image API version.\n * @property {number|import(\"../array.js\").NearestDirectionFunction} [zDirection=0]\n * Choose whether to use tiles with a higher or lower zoom level when between integer\n * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.\n */\n\nfunction formatPercentage(percentage) {\n return percentage.toLocaleString('en', {maximumFractionDigits: 10});\n}\n\n/**\n * @classdesc\n * Layer source for IIIF Image API services.\n * @api\n */\nclass IIIF extends TileImage {\n /**\n * @param {Options} [options] Tile source options. Use {@link import(\"../format/IIIFInfo.js\").IIIFInfo}\n * to parse Image API service information responses into constructor options.\n * @api\n */\n constructor(options) {\n /**\n * @type {Partial}\n */\n const partialOptions = options || {};\n\n let baseUrl = partialOptions.url || '';\n baseUrl =\n baseUrl +\n (baseUrl.lastIndexOf('/') === baseUrl.length - 1 || baseUrl === ''\n ? ''\n : '/');\n const version = partialOptions.version || Versions.VERSION2;\n const sizes = partialOptions.sizes || [];\n const size = partialOptions.size;\n assert(\n size != undefined &&\n Array.isArray(size) &&\n size.length == 2 &&\n !isNaN(size[0]) &&\n size[0] > 0 &&\n !isNaN(size[1]) &&\n size[1] > 0,\n 60\n );\n const width = size[0];\n const height = size[1];\n const tileSize = partialOptions.tileSize;\n const tilePixelRatio = partialOptions.tilePixelRatio || 1;\n const format = partialOptions.format || 'jpg';\n const quality =\n partialOptions.quality ||\n (partialOptions.version == Versions.VERSION1 ? 'native' : 'default');\n let resolutions = partialOptions.resolutions || [];\n const supports = partialOptions.supports || [];\n const extent = partialOptions.extent || [0, -height, width, 0];\n\n const supportsListedSizes =\n sizes != undefined && Array.isArray(sizes) && sizes.length > 0;\n const supportsListedTiles =\n tileSize !== undefined &&\n ((typeof tileSize === 'number' &&\n Number.isInteger(tileSize) &&\n tileSize > 0) ||\n (Array.isArray(tileSize) && tileSize.length > 0));\n const supportsArbitraryTiling =\n supports != undefined &&\n Array.isArray(supports) &&\n (supports.includes('regionByPx') || supports.includes('regionByPct')) &&\n (supports.includes('sizeByWh') ||\n supports.includes('sizeByH') ||\n supports.includes('sizeByW') ||\n supports.includes('sizeByPct'));\n\n let tileWidth, tileHeight, maxZoom;\n\n resolutions.sort(function (a, b) {\n return b - a;\n });\n\n if (supportsListedTiles || supportsArbitraryTiling) {\n if (tileSize != undefined) {\n if (\n typeof tileSize === 'number' &&\n Number.isInteger(tileSize) &&\n tileSize > 0\n ) {\n tileWidth = tileSize;\n tileHeight = tileSize;\n } else if (Array.isArray(tileSize) && tileSize.length > 0) {\n if (\n tileSize.length == 1 ||\n (tileSize[1] == undefined && Number.isInteger(tileSize[0]))\n ) {\n tileWidth = tileSize[0];\n tileHeight = tileSize[0];\n }\n if (tileSize.length == 2) {\n if (\n Number.isInteger(tileSize[0]) &&\n Number.isInteger(tileSize[1])\n ) {\n tileWidth = tileSize[0];\n tileHeight = tileSize[1];\n } else if (\n tileSize[0] == undefined &&\n Number.isInteger(tileSize[1])\n ) {\n tileWidth = tileSize[1];\n tileHeight = tileSize[1];\n }\n }\n }\n }\n if (tileWidth === undefined || tileHeight === undefined) {\n tileWidth = DEFAULT_TILE_SIZE;\n tileHeight = DEFAULT_TILE_SIZE;\n }\n if (resolutions.length == 0) {\n maxZoom = Math.max(\n Math.ceil(Math.log(width / tileWidth) / Math.LN2),\n Math.ceil(Math.log(height / tileHeight) / Math.LN2)\n );\n for (let i = maxZoom; i >= 0; i--) {\n resolutions.push(Math.pow(2, i));\n }\n } else {\n const maxScaleFactor = Math.max(...resolutions);\n // TODO maxScaleFactor might not be a power to 2\n maxZoom = Math.round(Math.log(maxScaleFactor) / Math.LN2);\n }\n } else {\n // No tile support.\n tileWidth = width;\n tileHeight = height;\n resolutions = [];\n if (supportsListedSizes) {\n /*\n * 'sizes' provided. Use full region in different resolutions. Every\n * resolution has only one tile.\n */\n sizes.sort(function (a, b) {\n return a[0] - b[0];\n });\n maxZoom = -1;\n const ignoredSizesIndex = [];\n for (let i = 0; i < sizes.length; i++) {\n const resolution = width / sizes[i][0];\n if (\n resolutions.length > 0 &&\n resolutions[resolutions.length - 1] == resolution\n ) {\n ignoredSizesIndex.push(i);\n continue;\n }\n resolutions.push(resolution);\n maxZoom++;\n }\n if (ignoredSizesIndex.length > 0) {\n for (let i = 0; i < ignoredSizesIndex.length; i++) {\n sizes.splice(ignoredSizesIndex[i] - i, 1);\n }\n }\n } else {\n // No useful image information at all. Try pseudo tile with full image.\n resolutions.push(1);\n sizes.push([width, height]);\n maxZoom = 0;\n }\n }\n\n const tileGrid = new TileGrid({\n tileSize: [tileWidth, tileHeight],\n extent: extent,\n origin: getTopLeft(extent),\n resolutions: resolutions,\n });\n\n const tileUrlFunction = function (tileCoord, pixelRatio, projection) {\n let regionParam, sizeParam;\n const zoom = tileCoord[0];\n if (zoom > maxZoom) {\n return;\n }\n const tileX = tileCoord[1],\n tileY = tileCoord[2],\n scale = resolutions[zoom];\n if (\n tileX === undefined ||\n tileY === undefined ||\n scale === undefined ||\n tileX < 0 ||\n Math.ceil(width / scale / tileWidth) <= tileX ||\n tileY < 0 ||\n Math.ceil(height / scale / tileHeight) <= tileY\n ) {\n return;\n }\n if (supportsArbitraryTiling || supportsListedTiles) {\n const regionX = tileX * tileWidth * scale,\n regionY = tileY * tileHeight * scale;\n let regionW = tileWidth * scale,\n regionH = tileHeight * scale,\n sizeW = tileWidth,\n sizeH = tileHeight;\n if (regionX + regionW > width) {\n regionW = width - regionX;\n }\n if (regionY + regionH > height) {\n regionH = height - regionY;\n }\n if (regionX + tileWidth * scale > width) {\n sizeW = Math.floor((width - regionX + scale - 1) / scale);\n }\n if (regionY + tileHeight * scale > height) {\n sizeH = Math.floor((height - regionY + scale - 1) / scale);\n }\n if (\n regionX == 0 &&\n regionW == width &&\n regionY == 0 &&\n regionH == height\n ) {\n // canonical full image region parameter is 'full', not 'x,y,w,h'\n regionParam = 'full';\n } else if (\n !supportsArbitraryTiling ||\n supports.includes('regionByPx')\n ) {\n regionParam = regionX + ',' + regionY + ',' + regionW + ',' + regionH;\n } else if (supports.includes('regionByPct')) {\n const pctX = formatPercentage((regionX / width) * 100),\n pctY = formatPercentage((regionY / height) * 100),\n pctW = formatPercentage((regionW / width) * 100),\n pctH = formatPercentage((regionH / height) * 100);\n regionParam = 'pct:' + pctX + ',' + pctY + ',' + pctW + ',' + pctH;\n }\n if (\n version == Versions.VERSION3 &&\n (!supportsArbitraryTiling || supports.includes('sizeByWh'))\n ) {\n sizeParam = sizeW + ',' + sizeH;\n } else if (!supportsArbitraryTiling || supports.includes('sizeByW')) {\n sizeParam = sizeW + ',';\n } else if (supports.includes('sizeByH')) {\n sizeParam = ',' + sizeH;\n } else if (supports.includes('sizeByWh')) {\n sizeParam = sizeW + ',' + sizeH;\n } else if (supports.includes('sizeByPct')) {\n sizeParam = 'pct:' + formatPercentage(100 / scale);\n }\n } else {\n regionParam = 'full';\n if (supportsListedSizes) {\n const regionWidth = sizes[zoom][0],\n regionHeight = sizes[zoom][1];\n if (version == Versions.VERSION3) {\n if (regionWidth == width && regionHeight == height) {\n sizeParam = 'max';\n } else {\n sizeParam = regionWidth + ',' + regionHeight;\n }\n } else {\n if (regionWidth == width) {\n sizeParam = 'full';\n } else {\n sizeParam = regionWidth + ',';\n }\n }\n } else {\n sizeParam = version == Versions.VERSION3 ? 'max' : 'full';\n }\n }\n return (\n baseUrl + regionParam + '/' + sizeParam + '/0/' + quality + '.' + format\n );\n };\n\n const IiifTileClass = CustomTile.bind(\n null,\n toSize(tileSize || 256).map(function (size) {\n return size * tilePixelRatio;\n })\n );\n\n super({\n attributions: partialOptions.attributions,\n attributionsCollapsible: partialOptions.attributionsCollapsible,\n cacheSize: partialOptions.cacheSize,\n crossOrigin: partialOptions.crossOrigin,\n interpolate: partialOptions.interpolate,\n projection: partialOptions.projection,\n reprojectionErrorThreshold: partialOptions.reprojectionErrorThreshold,\n state: partialOptions.state,\n tileClass: IiifTileClass,\n tileGrid: tileGrid,\n tilePixelRatio: partialOptions.tilePixelRatio,\n tileUrlFunction: tileUrlFunction,\n transition: partialOptions.transition,\n });\n\n /**\n * @type {number|import(\"../array.js\").NearestDirectionFunction}\n */\n this.zDirection = partialOptions.zDirection;\n }\n}\n\nexport default IIIF;\n","/**\n * @module ol/reproj/Image\n */\nimport {ERROR_THRESHOLD} from './common.js';\n\nimport EventType from '../events/EventType.js';\nimport ImageBase from '../ImageBase.js';\nimport ImageState from '../ImageState.js';\nimport Triangulation from './Triangulation.js';\nimport {\n calculateSourceResolution,\n render as renderReprojected,\n} from '../reproj.js';\nimport {\n getCenter,\n getHeight,\n getIntersection,\n getWidth,\n isEmpty,\n} from '../extent.js';\nimport {listen, unlistenByKey} from '../events.js';\n\n/**\n * @typedef {function(import(\"../extent.js\").Extent, number, number) : import(\"../ImageBase.js\").default} FunctionType\n */\n\n/**\n * @classdesc\n * Class encapsulating single reprojected image.\n * See {@link module:ol/source/Image~ImageSource}.\n */\nclass ReprojImage extends ImageBase {\n /**\n * @param {import(\"../proj/Projection.js\").default} sourceProj Source projection (of the data).\n * @param {import(\"../proj/Projection.js\").default} targetProj Target projection.\n * @param {import(\"../extent.js\").Extent} targetExtent Target extent.\n * @param {number} targetResolution Target resolution.\n * @param {number} pixelRatio Pixel ratio.\n * @param {FunctionType} getImageFunction\n * Function returning source images (extent, resolution, pixelRatio).\n * @param {boolean} interpolate Use linear interpolation when resampling.\n */\n constructor(\n sourceProj,\n targetProj,\n targetExtent,\n targetResolution,\n pixelRatio,\n getImageFunction,\n interpolate\n ) {\n let maxSourceExtent = sourceProj.getExtent();\n if (maxSourceExtent && sourceProj.canWrapX()) {\n maxSourceExtent = maxSourceExtent.slice();\n maxSourceExtent[0] = -Infinity;\n maxSourceExtent[2] = Infinity;\n }\n let maxTargetExtent = targetProj.getExtent();\n if (maxTargetExtent && targetProj.canWrapX()) {\n maxTargetExtent = maxTargetExtent.slice();\n maxTargetExtent[0] = -Infinity;\n maxTargetExtent[2] = Infinity;\n }\n\n const limitedTargetExtent = maxTargetExtent\n ? getIntersection(targetExtent, maxTargetExtent)\n : targetExtent;\n\n const targetCenter = getCenter(limitedTargetExtent);\n const sourceResolution = calculateSourceResolution(\n sourceProj,\n targetProj,\n targetCenter,\n targetResolution\n );\n\n const errorThresholdInPixels = ERROR_THRESHOLD;\n\n const triangulation = new Triangulation(\n sourceProj,\n targetProj,\n limitedTargetExtent,\n maxSourceExtent,\n sourceResolution * errorThresholdInPixels,\n targetResolution\n );\n\n const sourceExtent = triangulation.calculateSourceExtent();\n const sourceImage = isEmpty(sourceExtent)\n ? null\n : getImageFunction(sourceExtent, sourceResolution, pixelRatio);\n const state = sourceImage ? ImageState.IDLE : ImageState.EMPTY;\n const sourcePixelRatio = sourceImage ? sourceImage.getPixelRatio() : 1;\n\n super(targetExtent, targetResolution, sourcePixelRatio, state);\n\n /**\n * @private\n * @type {import(\"../proj/Projection.js\").default}\n */\n this.targetProj_ = targetProj;\n\n /**\n * @private\n * @type {import(\"../extent.js\").Extent}\n */\n this.maxSourceExtent_ = maxSourceExtent;\n\n /**\n * @private\n * @type {!import(\"./Triangulation.js\").default}\n */\n this.triangulation_ = triangulation;\n\n /**\n * @private\n * @type {number}\n */\n this.targetResolution_ = targetResolution;\n\n /**\n * @private\n * @type {import(\"../extent.js\").Extent}\n */\n this.targetExtent_ = targetExtent;\n\n /**\n * @private\n * @type {import(\"../ImageBase.js\").default}\n */\n this.sourceImage_ = sourceImage;\n\n /**\n * @private\n * @type {number}\n */\n this.sourcePixelRatio_ = sourcePixelRatio;\n\n /**\n * @private\n * @type {boolean}\n */\n this.interpolate_ = interpolate;\n\n /**\n * @private\n * @type {HTMLCanvasElement}\n */\n this.canvas_ = null;\n\n /**\n * @private\n * @type {?import(\"../events.js\").EventsKey}\n */\n this.sourceListenerKey_ = null;\n }\n\n /**\n * Clean up.\n */\n disposeInternal() {\n if (this.state == ImageState.LOADING) {\n this.unlistenSource_();\n }\n super.disposeInternal();\n }\n\n /**\n * @return {HTMLCanvasElement} Image.\n */\n getImage() {\n return this.canvas_;\n }\n\n /**\n * @return {import(\"../proj/Projection.js\").default} Projection.\n */\n getProjection() {\n return this.targetProj_;\n }\n\n /**\n * @private\n */\n reproject_() {\n const sourceState = this.sourceImage_.getState();\n if (sourceState == ImageState.LOADED) {\n const width = getWidth(this.targetExtent_) / this.targetResolution_;\n const height = getHeight(this.targetExtent_) / this.targetResolution_;\n\n this.canvas_ = renderReprojected(\n width,\n height,\n this.sourcePixelRatio_,\n this.sourceImage_.getResolution(),\n this.maxSourceExtent_,\n this.targetResolution_,\n this.targetExtent_,\n this.triangulation_,\n [\n {\n extent: this.sourceImage_.getExtent(),\n image: this.sourceImage_.getImage(),\n },\n ],\n 0,\n undefined,\n this.interpolate_\n );\n }\n this.state = sourceState;\n this.changed();\n }\n\n /**\n * Load not yet loaded URI.\n */\n load() {\n if (this.state == ImageState.IDLE) {\n this.state = ImageState.LOADING;\n this.changed();\n\n const sourceState = this.sourceImage_.getState();\n if (sourceState == ImageState.LOADED || sourceState == ImageState.ERROR) {\n this.reproject_();\n } else {\n this.sourceListenerKey_ = listen(\n this.sourceImage_,\n EventType.CHANGE,\n function (e) {\n const sourceState = this.sourceImage_.getState();\n if (\n sourceState == ImageState.LOADED ||\n sourceState == ImageState.ERROR\n ) {\n this.unlistenSource_();\n this.reproject_();\n }\n },\n this\n );\n this.sourceImage_.load();\n }\n }\n }\n\n /**\n * @private\n */\n unlistenSource_() {\n unlistenByKey(\n /** @type {!import(\"../events.js\").EventsKey} */ (this.sourceListenerKey_)\n );\n this.sourceListenerKey_ = null;\n }\n}\n\nexport default ReprojImage;\n","/**\n * @module ol/source/Image\n */\nimport Event from '../events/Event.js';\nimport ImageState from '../ImageState.js';\nimport ReprojImage from '../reproj/Image.js';\nimport Source from './Source.js';\nimport {abstract} from '../util.js';\nimport {equals} from '../extent.js';\nimport {equivalent} from '../proj.js';\nimport {linearFindNearest} from '../array.js';\n\n/**\n * @enum {string}\n */\nexport const ImageSourceEventType = {\n /**\n * Triggered when an image starts loading.\n * @event module:ol/source/Image.ImageSourceEvent#imageloadstart\n * @api\n */\n IMAGELOADSTART: 'imageloadstart',\n\n /**\n * Triggered when an image finishes loading.\n * @event module:ol/source/Image.ImageSourceEvent#imageloadend\n * @api\n */\n IMAGELOADEND: 'imageloadend',\n\n /**\n * Triggered if image loading results in an error.\n * @event module:ol/source/Image.ImageSourceEvent#imageloaderror\n * @api\n */\n IMAGELOADERROR: 'imageloaderror',\n};\n\n/**\n * @typedef {'imageloadend'|'imageloaderror'|'imageloadstart'} ImageSourceEventTypes\n */\n\n/**\n * @classdesc\n * Events emitted by {@link module:ol/source/Image~ImageSource} instances are instances of this\n * type.\n */\nexport class ImageSourceEvent extends Event {\n /**\n * @param {string} type Type.\n * @param {import(\"../Image.js\").default} image The image.\n */\n constructor(type, image) {\n super(type);\n\n /**\n * The image related to the event.\n * @type {import(\"../Image.js\").default}\n * @api\n */\n this.image = image;\n }\n}\n\n/***\n * @template Return\n * @typedef {import(\"../Observable\").OnSignature &\n * import(\"../Observable\").OnSignature &\n * import(\"../Observable\").OnSignature &\n * import(\"../Observable\").CombinedOnSignature} ImageSourceOnSignature\n */\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {boolean} [interpolate=true] Use interpolated values when resampling. By default,\n * linear interpolation is used when resampling. Set to false to use the nearest neighbor instead.\n * @property {import(\"../proj.js\").ProjectionLike} [projection] Projection.\n * @property {Array} [resolutions] Resolutions.\n * @property {import(\"./Source.js\").State} [state] State.\n */\n\n/**\n * @classdesc\n * Abstract base class; normally only used for creating subclasses and not\n * instantiated in apps.\n * Base class for sources providing a single image.\n * @abstract\n * @fires module:ol/source/Image.ImageSourceEvent\n * @api\n */\nclass ImageSource extends Source {\n /**\n * @param {Options} options Single image source options.\n */\n constructor(options) {\n super({\n attributions: options.attributions,\n projection: options.projection,\n state: options.state,\n interpolate:\n options.interpolate !== undefined ? options.interpolate : true,\n });\n\n /***\n * @type {ImageSourceOnSignature}\n */\n this.on;\n\n /***\n * @type {ImageSourceOnSignature}\n */\n this.once;\n\n /***\n * @type {ImageSourceOnSignature}\n */\n this.un;\n\n /**\n * @private\n * @type {Array|null}\n */\n this.resolutions_ =\n options.resolutions !== undefined ? options.resolutions : null;\n\n /**\n * @private\n * @type {import(\"../reproj/Image.js\").default}\n */\n this.reprojectedImage_ = null;\n\n /**\n * @private\n * @type {number}\n */\n this.reprojectedRevision_ = 0;\n }\n\n /**\n * @return {Array|null} Resolutions.\n */\n getResolutions() {\n return this.resolutions_;\n }\n\n /**\n * @param {Array|null} resolutions Resolutions.\n */\n setResolutions(resolutions) {\n this.resolutions_ = resolutions;\n }\n\n /**\n * @protected\n * @param {number} resolution Resolution.\n * @return {number} Resolution.\n */\n findNearestResolution(resolution) {\n const resolutions = this.getResolutions();\n if (resolutions) {\n const idx = linearFindNearest(resolutions, resolution, 0);\n resolution = resolutions[idx];\n }\n return resolution;\n }\n\n /**\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @param {number} resolution Resolution.\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {import(\"../ImageBase.js\").default} Single image.\n */\n getImage(extent, resolution, pixelRatio, projection) {\n const sourceProjection = this.getProjection();\n if (\n !sourceProjection ||\n !projection ||\n equivalent(sourceProjection, projection)\n ) {\n if (sourceProjection) {\n projection = sourceProjection;\n }\n return this.getImageInternal(extent, resolution, pixelRatio, projection);\n }\n if (this.reprojectedImage_) {\n if (\n this.reprojectedRevision_ == this.getRevision() &&\n equivalent(this.reprojectedImage_.getProjection(), projection) &&\n this.reprojectedImage_.getResolution() == resolution &&\n equals(this.reprojectedImage_.getExtent(), extent)\n ) {\n return this.reprojectedImage_;\n }\n this.reprojectedImage_.dispose();\n this.reprojectedImage_ = null;\n }\n\n this.reprojectedImage_ = new ReprojImage(\n sourceProjection,\n projection,\n extent,\n resolution,\n pixelRatio,\n (extent, resolution, pixelRatio) =>\n this.getImageInternal(extent, resolution, pixelRatio, sourceProjection),\n this.getInterpolate()\n );\n this.reprojectedRevision_ = this.getRevision();\n\n return this.reprojectedImage_;\n }\n\n /**\n * @abstract\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @param {number} resolution Resolution.\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {import(\"../ImageBase.js\").default} Single image.\n * @protected\n */\n getImageInternal(extent, resolution, pixelRatio, projection) {\n return abstract();\n }\n\n /**\n * Handle image change events.\n * @param {import(\"../events/Event.js\").default} event Event.\n * @protected\n */\n handleImageChange(event) {\n const image = /** @type {import(\"../Image.js\").default} */ (event.target);\n let type;\n switch (image.getState()) {\n case ImageState.LOADING:\n this.loading = true;\n type = ImageSourceEventType.IMAGELOADSTART;\n break;\n case ImageState.LOADED:\n this.loading = false;\n type = ImageSourceEventType.IMAGELOADEND;\n break;\n case ImageState.ERROR:\n this.loading = false;\n type = ImageSourceEventType.IMAGELOADERROR;\n break;\n default:\n return;\n }\n if (this.hasListener(type)) {\n this.dispatchEvent(new ImageSourceEvent(type, image));\n }\n }\n}\n\n/**\n * Default image load function for image sources that use import(\"../Image.js\").Image image\n * instances.\n * @param {import(\"../Image.js\").default} image Image.\n * @param {string} src Source.\n */\nexport function defaultImageLoadFunction(image, src) {\n /** @type {HTMLImageElement|HTMLVideoElement} */ (image.getImage()).src = src;\n}\n\nexport default ImageSource;\n","/**\n * @module ol/uri\n */\n\n/**\n * Appends query parameters to a URI.\n *\n * @param {string} uri The original URI, which may already have query data.\n * @param {!Object} params An object where keys are URI-encoded parameter keys,\n * and the values are arbitrary types or arrays.\n * @return {string} The new URI.\n */\nexport function appendParams(uri, params) {\n const keyParams = [];\n // Skip any null or undefined parameter values\n Object.keys(params).forEach(function (k) {\n if (params[k] !== null && params[k] !== undefined) {\n keyParams.push(k + '=' + encodeURIComponent(params[k]));\n }\n });\n const qs = keyParams.join('&');\n // remove any trailing ? or &\n uri = uri.replace(/[?&]$/, '');\n // append ? or & depending on whether uri has existing parameters\n uri += uri.includes('?') ? '&' : '?';\n return uri + qs;\n}\n","/**\n * @module ol/source/ImageArcGISRest\n */\n\nimport EventType from '../events/EventType.js';\nimport ImageSource, {defaultImageLoadFunction} from './Image.js';\nimport ImageWrapper from '../Image.js';\nimport {appendParams} from '../uri.js';\nimport {assert} from '../asserts.js';\nimport {containsExtent, getHeight, getWidth} from '../extent.js';\nimport {createCanvasContext2D} from '../dom.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images. Note that\n * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.\n * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.\n * @property {boolean} [hidpi=true] Use the `ol/Map#pixelRatio` value when requesting the image from\n * the remote server.\n * @property {import(\"../Image.js\").LoadFunction} [imageLoadFunction] Optional function to load an image given\n * a URL.\n * @property {boolean} [interpolate=true] Use interpolated values when resampling. By default,\n * linear interpolation is used when resampling. Set to false to use the nearest neighbor instead.\n * @property {Object} [params] ArcGIS Rest parameters. This field is optional. Service\n * defaults will be used for any fields not specified. `FORMAT` is `PNG32` by default. `F` is\n * `IMAGE` by default. `TRANSPARENT` is `true` by default. `BBOX`, `SIZE`, `BBOXSR`, and `IMAGESR`\n * will be set dynamically. Set `LAYERS` to override the default service layer visibility. See\n * https://developers.arcgis.com/rest/services-reference/export-map.htm\n * for further reference.\n * @property {import(\"../proj.js\").ProjectionLike} [projection] Projection. Default is the view projection.\n * The projection code must contain a numeric end portion separated by :\n * or the entire code must form a valid ArcGIS SpatialReference definition.\n * @property {number} [ratio=1.5] Ratio. `1` means image requests are the size of the map viewport,\n * `2` means twice the size of the map viewport, and so on.\n * @property {Array} [resolutions] Resolutions. If specified, requests will be made for\n * these resolutions only.\n * @property {string} [url] ArcGIS Rest service URL for a Map Service or Image Service. The url\n * should include /MapServer or /ImageServer.\n */\n\n/**\n * @classdesc\n * Source for data from ArcGIS Rest services providing single, untiled images.\n * Useful when underlying map service has labels.\n *\n * If underlying map service is not using labels,\n * take advantage of ol image caching and use\n * {@link module:ol/source/TileArcGISRest~TileArcGISRest} data source.\n *\n * @fires module:ol/source/Image.ImageSourceEvent\n * @api\n */\nclass ImageArcGISRest extends ImageSource {\n /**\n * @param {Options} [options] Image ArcGIS Rest Options.\n */\n constructor(options) {\n options = options ? options : {};\n\n super({\n attributions: options.attributions,\n interpolate: options.interpolate,\n projection: options.projection,\n resolutions: options.resolutions,\n });\n\n /**\n * @private\n * @type {CanvasRenderingContext2D}\n */\n this.context_ = createCanvasContext2D(1, 1);\n\n /**\n * @private\n * @type {?string}\n */\n this.crossOrigin_ =\n options.crossOrigin !== undefined ? options.crossOrigin : null;\n\n /**\n * @private\n * @type {boolean}\n */\n this.hidpi_ = options.hidpi !== undefined ? options.hidpi : true;\n\n /**\n * @private\n * @type {string|undefined}\n */\n this.url_ = options.url;\n\n /**\n * @private\n * @type {import(\"../Image.js\").LoadFunction}\n */\n this.imageLoadFunction_ =\n options.imageLoadFunction !== undefined\n ? options.imageLoadFunction\n : defaultImageLoadFunction;\n\n /**\n * @private\n * @type {!Object}\n */\n this.params_ = options.params || {};\n\n /**\n * @private\n * @type {import(\"../Image.js\").default}\n */\n this.image_ = null;\n\n /**\n * @private\n * @type {import(\"../size.js\").Size}\n */\n this.imageSize_ = [0, 0];\n\n /**\n * @private\n * @type {number}\n */\n this.renderedRevision_ = 0;\n\n /**\n * @private\n * @type {number}\n */\n this.ratio_ = options.ratio !== undefined ? options.ratio : 1.5;\n }\n\n /**\n * Get the user-provided params, i.e. those passed to the constructor through\n * the \"params\" option, and possibly updated using the updateParams method.\n * @return {Object} Params.\n * @api\n */\n getParams() {\n return this.params_;\n }\n\n /**\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @param {number} resolution Resolution.\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {import(\"../Image.js\").default} Single image.\n */\n getImageInternal(extent, resolution, pixelRatio, projection) {\n if (this.url_ === undefined) {\n return null;\n }\n\n resolution = this.findNearestResolution(resolution);\n pixelRatio = this.hidpi_ ? pixelRatio : 1;\n\n const image = this.image_;\n if (\n image &&\n this.renderedRevision_ == this.getRevision() &&\n image.getResolution() == resolution &&\n image.getPixelRatio() == pixelRatio &&\n containsExtent(image.getExtent(), extent)\n ) {\n return image;\n }\n\n const params = {\n 'F': 'image',\n 'FORMAT': 'PNG32',\n 'TRANSPARENT': true,\n };\n Object.assign(params, this.params_);\n\n extent = extent.slice();\n const centerX = (extent[0] + extent[2]) / 2;\n const centerY = (extent[1] + extent[3]) / 2;\n if (this.ratio_ != 1) {\n const halfWidth = (this.ratio_ * getWidth(extent)) / 2;\n const halfHeight = (this.ratio_ * getHeight(extent)) / 2;\n extent[0] = centerX - halfWidth;\n extent[1] = centerY - halfHeight;\n extent[2] = centerX + halfWidth;\n extent[3] = centerY + halfHeight;\n }\n\n const imageResolution = resolution / pixelRatio;\n\n // Compute an integer width and height.\n const width = Math.ceil(getWidth(extent) / imageResolution);\n const height = Math.ceil(getHeight(extent) / imageResolution);\n\n // Modify the extent to match the integer width and height.\n extent[0] = centerX - (imageResolution * width) / 2;\n extent[2] = centerX + (imageResolution * width) / 2;\n extent[1] = centerY - (imageResolution * height) / 2;\n extent[3] = centerY + (imageResolution * height) / 2;\n\n this.imageSize_[0] = width;\n this.imageSize_[1] = height;\n\n const url = this.getRequestUrl_(\n extent,\n this.imageSize_,\n pixelRatio,\n projection,\n params\n );\n\n this.image_ = new ImageWrapper(\n extent,\n resolution,\n pixelRatio,\n url,\n this.crossOrigin_,\n this.imageLoadFunction_,\n this.context_\n );\n\n this.renderedRevision_ = this.getRevision();\n\n this.image_.addEventListener(\n EventType.CHANGE,\n this.handleImageChange.bind(this)\n );\n\n return this.image_;\n }\n\n /**\n * Return the image load function of the source.\n * @return {import(\"../Image.js\").LoadFunction} The image load function.\n * @api\n */\n getImageLoadFunction() {\n return this.imageLoadFunction_;\n }\n\n /**\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @param {import(\"../size.js\").Size} size Size.\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @param {Object} params Params.\n * @return {string} Request URL.\n * @private\n */\n getRequestUrl_(extent, size, pixelRatio, projection, params) {\n // ArcGIS Server only wants the numeric portion of the projection ID.\n // (if there is no numeric portion the entire projection code must\n // form a valid ArcGIS SpatialReference definition).\n const srid = projection\n .getCode()\n .split(/:(?=\\d+$)/)\n .pop();\n\n params['SIZE'] = size[0] + ',' + size[1];\n params['BBOX'] = extent.join(',');\n params['BBOXSR'] = srid;\n params['IMAGESR'] = srid;\n params['DPI'] = Math.round(90 * pixelRatio);\n\n const url = this.url_;\n\n const modifiedUrl = url\n .replace(/MapServer\\/?$/, 'MapServer/export')\n .replace(/ImageServer\\/?$/, 'ImageServer/exportImage');\n if (modifiedUrl == url) {\n assert(false, 50); // `options.featureTypes` should be an Array\n }\n return appendParams(modifiedUrl, params);\n }\n\n /**\n * Return the URL used for this ArcGIS source.\n * @return {string|undefined} URL.\n * @api\n */\n getUrl() {\n return this.url_;\n }\n\n /**\n * Set the image load function of the source.\n * @param {import(\"../Image.js\").LoadFunction} imageLoadFunction Image load function.\n * @api\n */\n setImageLoadFunction(imageLoadFunction) {\n this.image_ = null;\n this.imageLoadFunction_ = imageLoadFunction;\n this.changed();\n }\n\n /**\n * Set the URL to use for requests.\n * @param {string|undefined} url URL.\n * @api\n */\n setUrl(url) {\n if (url != this.url_) {\n this.url_ = url;\n this.image_ = null;\n this.changed();\n }\n }\n\n /**\n * Update the user-provided params.\n * @param {Object} params Params.\n * @api\n */\n updateParams(params) {\n Object.assign(this.params_, params);\n this.image_ = null;\n this.changed();\n }\n}\n\nexport default ImageArcGISRest;\n","/**\n * @module ol/source/ImageCanvas\n */\n\nimport ImageCanvas from '../ImageCanvas.js';\nimport ImageSource from './Image.js';\nimport {\n containsExtent,\n getHeight,\n getWidth,\n scaleFromCenter,\n} from '../extent.js';\n\n/**\n * A function returning the canvas element (`{HTMLCanvasElement}`)\n * used by the source as an image. The arguments passed to the function are:\n * {@link module:ol/extent~Extent} the image extent, `{number}` the image resolution,\n * `{number}` the pixel ratio of the map, {@link module:ol/size~Size} the image size,\n * and {@link module:ol/proj/Projection~Projection} the image projection. The canvas returned by\n * this function is cached by the source. The this keyword inside the function\n * references the {@link module:ol/source/ImageCanvas~ImageCanvasSource}.\n *\n * @typedef {function(this:import(\"../ImageCanvas.js\").default, import(\"../extent.js\").Extent, number,\n * number, import(\"../size.js\").Size, import(\"../proj/Projection.js\").default): HTMLCanvasElement} FunctionType\n */\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {FunctionType} [canvasFunction] Canvas function.\n * The function returning the canvas element used by the source\n * as an image. The arguments passed to the function are: {@link import(\"../extent.js\").Extent} the\n * image extent, `{number}` the image resolution, `{number}` the pixel ratio of the map,\n * {@link import(\"../size.js\").Size} the image size, and {@link import(\"../proj/Projection.js\").default} the image\n * projection. The canvas returned by this function is cached by the source. If\n * the value returned by the function is later changed then\n * `changed` should be called on the source for the source to\n * invalidate the current cached image. See: {@link module:ol/Observable~Observable#changed}\n * @property {boolean} [interpolate=true] Use interpolated values when resampling. By default,\n * linear interpolation is used when resampling. Set to false to use the nearest neighbor instead.\n * @property {import(\"../proj.js\").ProjectionLike} [projection] Projection. Default is the view projection.\n * @property {number} [ratio=1.5] Ratio. 1 means canvases are the size of the map viewport, 2 means twice the\n * width and height of the map viewport, and so on. Must be `1` or higher.\n * @property {Array} [resolutions] Resolutions.\n * If specified, new canvases will be created for these resolutions\n * @property {import(\"./Source.js\").State} [state] Source state.\n */\n\n/**\n * @classdesc\n * Base class for image sources where a canvas element is the image.\n * @api\n */\nclass ImageCanvasSource extends ImageSource {\n /**\n * @param {Options} [options] ImageCanvas options.\n */\n constructor(options) {\n options = options ? options : {};\n\n super({\n attributions: options.attributions,\n interpolate: options.interpolate,\n projection: options.projection,\n resolutions: options.resolutions,\n state: options.state,\n });\n\n /**\n * @private\n * @type {FunctionType}\n */\n this.canvasFunction_ = options.canvasFunction;\n\n /**\n * @private\n * @type {import(\"../ImageCanvas.js\").default}\n */\n this.canvas_ = null;\n\n /**\n * @private\n * @type {number}\n */\n this.renderedRevision_ = 0;\n\n /**\n * @private\n * @type {number}\n */\n this.ratio_ = options.ratio !== undefined ? options.ratio : 1.5;\n }\n\n /**\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @param {number} resolution Resolution.\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {import(\"../ImageCanvas.js\").default} Single image.\n */\n getImageInternal(extent, resolution, pixelRatio, projection) {\n resolution = this.findNearestResolution(resolution);\n\n let canvas = this.canvas_;\n if (\n canvas &&\n this.renderedRevision_ == this.getRevision() &&\n canvas.getResolution() == resolution &&\n canvas.getPixelRatio() == pixelRatio &&\n containsExtent(canvas.getExtent(), extent)\n ) {\n return canvas;\n }\n\n extent = extent.slice();\n scaleFromCenter(extent, this.ratio_);\n const width = getWidth(extent) / resolution;\n const height = getHeight(extent) / resolution;\n const size = [width * pixelRatio, height * pixelRatio];\n\n const canvasElement = this.canvasFunction_.call(\n this,\n extent,\n resolution,\n pixelRatio,\n size,\n projection\n );\n if (canvasElement) {\n canvas = new ImageCanvas(extent, resolution, pixelRatio, canvasElement);\n }\n this.canvas_ = canvas;\n this.renderedRevision_ = this.getRevision();\n\n return canvas;\n }\n}\n\nexport default ImageCanvasSource;\n","/**\n * @module ol/source/ImageMapGuide\n */\n\nimport EventType from '../events/EventType.js';\nimport ImageSource, {defaultImageLoadFunction} from './Image.js';\nimport ImageWrapper from '../Image.js';\nimport {appendParams} from '../uri.js';\nimport {\n containsExtent,\n getCenter,\n getHeight,\n getWidth,\n scaleFromCenter,\n} from '../extent.js';\nimport {createCanvasContext2D} from '../dom.js';\n\n/**\n * @typedef {Object} Options\n * @property {string} [url] The mapagent url.\n * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images. Note that\n * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.\n * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.\n * @property {number} [displayDpi=96] The display resolution.\n * @property {number} [metersPerUnit=1] The meters-per-unit value.\n * @property {boolean} [hidpi=true] Use the `ol/Map#pixelRatio` value when requesting\n * the image from the remote server.\n * @property {boolean} [useOverlay] If `true`, will use `GETDYNAMICMAPOVERLAYIMAGE`.\n * @property {import(\"../proj.js\").ProjectionLike} [projection] Projection. Default is the view projection.\n * @property {number} [ratio=1] Ratio. `1` means image requests are the size of the map viewport, `2` means\n * twice the width and height of the map viewport, and so on. Must be `1` or higher.\n * @property {Array} [resolutions] Resolutions.\n * If specified, requests will be made for these resolutions only.\n * @property {import(\"../Image.js\").LoadFunction} [imageLoadFunction] Optional function to load an image given a URL.\n * @property {boolean} [interpolate=true] Use interpolated values when resampling. By default,\n * linear interpolation is used when resampling. Set to false to use the nearest neighbor instead.\n * @property {Object} [params] Additional parameters.\n */\n\n/**\n * @classdesc\n * Source for images from Mapguide servers\n *\n * @fires module:ol/source/Image.ImageSourceEvent\n * @api\n */\nclass ImageMapGuide extends ImageSource {\n /**\n * @param {Options} options ImageMapGuide options.\n */\n constructor(options) {\n super({\n interpolate: options.interpolate,\n projection: options.projection,\n resolutions: options.resolutions,\n });\n\n /**\n * @private\n * @type {CanvasRenderingContext2D}\n */\n this.context_ = createCanvasContext2D(1, 1);\n\n /**\n * @private\n * @type {?string}\n */\n this.crossOrigin_ =\n options.crossOrigin !== undefined ? options.crossOrigin : null;\n\n /**\n * @private\n * @type {number}\n */\n this.displayDpi_ =\n options.displayDpi !== undefined ? options.displayDpi : 96;\n\n /**\n * @private\n * @type {!Object}\n */\n this.params_ = options.params || {};\n\n /**\n * @private\n * @type {string|undefined}\n */\n this.url_ = options.url;\n\n /**\n * @private\n * @type {import(\"../Image.js\").LoadFunction}\n */\n this.imageLoadFunction_ =\n options.imageLoadFunction !== undefined\n ? options.imageLoadFunction\n : defaultImageLoadFunction;\n\n /**\n * @private\n * @type {boolean}\n */\n this.hidpi_ = options.hidpi !== undefined ? options.hidpi : true;\n\n /**\n * @private\n * @type {number}\n */\n this.metersPerUnit_ =\n options.metersPerUnit !== undefined ? options.metersPerUnit : 1;\n\n /**\n * @private\n * @type {number}\n */\n this.ratio_ = options.ratio !== undefined ? options.ratio : 1;\n\n /**\n * @private\n * @type {boolean}\n */\n this.useOverlay_ =\n options.useOverlay !== undefined ? options.useOverlay : false;\n\n /**\n * @private\n * @type {import(\"../Image.js\").default}\n */\n this.image_ = null;\n\n /**\n * @private\n * @type {number}\n */\n this.renderedRevision_ = 0;\n }\n\n /**\n * Get the user-provided params, i.e. those passed to the constructor through\n * the \"params\" option, and possibly updated using the updateParams method.\n * @return {Object} Params.\n * @api\n */\n getParams() {\n return this.params_;\n }\n\n /**\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @param {number} resolution Resolution.\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {import(\"../Image.js\").default} Single image.\n */\n getImageInternal(extent, resolution, pixelRatio, projection) {\n resolution = this.findNearestResolution(resolution);\n pixelRatio = this.hidpi_ ? pixelRatio : 1;\n\n let image = this.image_;\n if (\n image &&\n this.renderedRevision_ == this.getRevision() &&\n image.getResolution() == resolution &&\n image.getPixelRatio() == pixelRatio &&\n containsExtent(image.getExtent(), extent)\n ) {\n return image;\n }\n\n if (this.ratio_ != 1) {\n extent = extent.slice();\n scaleFromCenter(extent, this.ratio_);\n }\n const width = getWidth(extent) / resolution;\n const height = getHeight(extent) / resolution;\n const size = [width * pixelRatio, height * pixelRatio];\n\n if (this.url_ !== undefined) {\n const imageUrl = this.getUrl(\n this.url_,\n this.params_,\n extent,\n size,\n projection\n );\n image = new ImageWrapper(\n extent,\n resolution,\n pixelRatio,\n imageUrl,\n this.crossOrigin_,\n this.imageLoadFunction_,\n this.context_\n );\n image.addEventListener(\n EventType.CHANGE,\n this.handleImageChange.bind(this)\n );\n } else {\n image = null;\n }\n this.image_ = image;\n this.renderedRevision_ = this.getRevision();\n\n return image;\n }\n\n /**\n * Return the image load function of the source.\n * @return {import(\"../Image.js\").LoadFunction} The image load function.\n * @api\n */\n getImageLoadFunction() {\n return this.imageLoadFunction_;\n }\n\n /**\n * Update the user-provided params.\n * @param {Object} params Params.\n * @api\n */\n updateParams(params) {\n Object.assign(this.params_, params);\n this.changed();\n }\n\n /**\n * @param {string} baseUrl The mapagent url.\n * @param {Object} params Request parameters.\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @param {import(\"../size.js\").Size} size Size.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {string} The mapagent map image request URL.\n */\n getUrl(baseUrl, params, extent, size, projection) {\n const scale = getScale(extent, size, this.metersPerUnit_, this.displayDpi_);\n const center = getCenter(extent);\n const baseParams = {\n 'OPERATION': this.useOverlay_\n ? 'GETDYNAMICMAPOVERLAYIMAGE'\n : 'GETMAPIMAGE',\n 'VERSION': '2.0.0',\n 'LOCALE': 'en',\n 'CLIENTAGENT': 'ol/source/ImageMapGuide source',\n 'CLIP': '1',\n 'SETDISPLAYDPI': this.displayDpi_,\n 'SETDISPLAYWIDTH': Math.round(size[0]),\n 'SETDISPLAYHEIGHT': Math.round(size[1]),\n 'SETVIEWSCALE': scale,\n 'SETVIEWCENTERX': center[0],\n 'SETVIEWCENTERY': center[1],\n };\n Object.assign(baseParams, params);\n return appendParams(baseUrl, baseParams);\n }\n\n /**\n * Set the image load function of the MapGuide source.\n * @param {import(\"../Image.js\").LoadFunction} imageLoadFunction Image load function.\n * @api\n */\n setImageLoadFunction(imageLoadFunction) {\n this.image_ = null;\n this.imageLoadFunction_ = imageLoadFunction;\n this.changed();\n }\n}\n\n/**\n * @param {import(\"../extent.js\").Extent} extent The map extents.\n * @param {import(\"../size.js\").Size} size The viewport size.\n * @param {number} metersPerUnit The meters-per-unit value.\n * @param {number} dpi The display resolution.\n * @return {number} The computed map scale.\n */\nfunction getScale(extent, size, metersPerUnit, dpi) {\n const mcsW = getWidth(extent);\n const mcsH = getHeight(extent);\n const devW = size[0];\n const devH = size[1];\n const mpp = 0.0254 / dpi;\n if (devH * mcsW > devW * mcsH) {\n return (mcsW * metersPerUnit) / (devW * mpp); // width limited\n }\n return (mcsH * metersPerUnit) / (devH * mpp); // height limited\n}\n\nexport default ImageMapGuide;\n","/**\n * @module ol/source/ImageStatic\n */\n\nimport EventType from '../events/EventType.js';\nimport ImageSource, {defaultImageLoadFunction} from './Image.js';\nimport ImageState from '../ImageState.js';\nimport ImageWrapper from '../Image.js';\nimport {createCanvasContext2D} from '../dom.js';\nimport {getHeight, getWidth, intersects} from '../extent.js';\nimport {get as getProjection} from '../proj.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images. Note that\n * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.\n * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.\n * @property {import(\"../extent.js\").Extent} [imageExtent] Extent of the image in map coordinates.\n * This is the [left, bottom, right, top] map coordinates of your image.\n * @property {import(\"../Image.js\").LoadFunction} [imageLoadFunction] Optional function to load an image given a URL.\n * @property {boolean} [interpolate=true] Use interpolated values when resampling. By default,\n * linear interpolation is used when resampling. Set to false to use the nearest neighbor instead.\n * @property {import(\"../proj.js\").ProjectionLike} [projection] Projection. Default is the view projection.\n * @property {import(\"../size.js\").Size} [imageSize] Size of the image in pixels. Usually the image size is auto-detected, so this\n * only needs to be set if auto-detection fails for some reason.\n * @property {string} url Image URL.\n */\n\n/**\n * @classdesc\n * A layer source for displaying a single, static image.\n * @api\n */\nclass Static extends ImageSource {\n /**\n * @param {Options} options ImageStatic options.\n */\n constructor(options) {\n const crossOrigin =\n options.crossOrigin !== undefined ? options.crossOrigin : null;\n\n const /** @type {import(\"../Image.js\").LoadFunction} */ imageLoadFunction =\n options.imageLoadFunction !== undefined\n ? options.imageLoadFunction\n : defaultImageLoadFunction;\n\n super({\n attributions: options.attributions,\n interpolate: options.interpolate,\n projection: getProjection(options.projection),\n });\n\n /**\n * @private\n * @type {string}\n */\n this.url_ = options.url;\n\n /**\n * @private\n * @type {import(\"../extent.js\").Extent}\n */\n this.imageExtent_ = options.imageExtent;\n\n /**\n * @private\n * @type {import(\"../Image.js\").default}\n */\n this.image_ = new ImageWrapper(\n this.imageExtent_,\n undefined,\n 1,\n this.url_,\n crossOrigin,\n imageLoadFunction,\n createCanvasContext2D(1, 1)\n );\n\n /**\n * @private\n * @type {import(\"../size.js\").Size|null}\n */\n this.imageSize_ = options.imageSize ? options.imageSize : null;\n\n this.image_.addEventListener(\n EventType.CHANGE,\n this.handleImageChange.bind(this)\n );\n }\n\n /**\n * Returns the image extent\n * @return {import(\"../extent.js\").Extent} image extent.\n * @api\n */\n getImageExtent() {\n return this.imageExtent_;\n }\n\n /**\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @param {number} resolution Resolution.\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {import(\"../Image.js\").default} Single image.\n */\n getImageInternal(extent, resolution, pixelRatio, projection) {\n if (intersects(extent, this.image_.getExtent())) {\n return this.image_;\n }\n return null;\n }\n\n /**\n * Return the URL used for this image source.\n * @return {string} URL.\n * @api\n */\n getUrl() {\n return this.url_;\n }\n\n /**\n * @param {import(\"../events/Event.js\").default} evt Event.\n */\n handleImageChange(evt) {\n if (this.image_.getState() == ImageState.LOADED) {\n const imageExtent = this.image_.getExtent();\n const image = this.image_.getImage();\n let imageWidth, imageHeight;\n if (this.imageSize_) {\n imageWidth = this.imageSize_[0];\n imageHeight = this.imageSize_[1];\n } else {\n imageWidth = image.width;\n imageHeight = image.height;\n }\n const extentWidth = getWidth(imageExtent);\n const extentHeight = getHeight(imageExtent);\n const xResolution = extentWidth / imageWidth;\n const yResolution = extentHeight / imageHeight;\n let targetWidth = imageWidth;\n let targetHeight = imageHeight;\n if (xResolution > yResolution) {\n targetWidth = Math.round(extentWidth / yResolution);\n } else {\n targetHeight = Math.round(extentHeight / xResolution);\n }\n if (targetWidth !== imageWidth || targetHeight !== imageHeight) {\n const context = createCanvasContext2D(targetWidth, targetHeight);\n if (!this.getInterpolate()) {\n context.imageSmoothingEnabled = false;\n }\n const canvas = context.canvas;\n context.drawImage(\n image,\n 0,\n 0,\n imageWidth,\n imageHeight,\n 0,\n 0,\n canvas.width,\n canvas.height\n );\n this.image_.setImage(canvas);\n }\n }\n super.handleImageChange(evt);\n }\n}\n\nexport default Static;\n","/**\n * @module ol/source/wms\n */\n\n/**\n * Default WMS version.\n * @type {string}\n */\nexport const DEFAULT_VERSION = '1.3.0';\n\n/**\n * @api\n * @typedef {'carmentaserver' | 'geoserver' | 'mapserver' | 'qgis'} ServerType\n * Set the server type to use implementation-specific parameters beyond the WMS specification.\n * - `'carmentaserver'`: HiDPI support for [Carmenta Server](https://www.carmenta.com/en/products/carmenta-server)\n * - `'geoserver'`: HiDPI support for [GeoServer](https://geoserver.org/)\n * - `'mapserver'`: HiDPI support for [MapServer](https://mapserver.org/)\n * - `'qgis'`: HiDPI support for [QGIS](https://qgis.org/)\n */\n","/**\n * @module ol/source/ImageWMS\n */\n\nimport EventType from '../events/EventType.js';\nimport ImageSource, {defaultImageLoadFunction} from './Image.js';\nimport ImageWrapper from '../Image.js';\nimport {DEFAULT_VERSION} from './wms.js';\nimport {appendParams} from '../uri.js';\nimport {assert} from '../asserts.js';\nimport {calculateSourceResolution} from '../reproj.js';\nimport {ceil, floor, round} from '../math.js';\nimport {compareVersions} from '../string.js';\nimport {\n containsExtent,\n getCenter,\n getForViewAndSize,\n getHeight,\n getWidth,\n} from '../extent.js';\nimport {createCanvasContext2D} from '../dom.js';\nimport {get as getProjection, transform} from '../proj.js';\n\n/**\n * Number of decimal digits to consider in integer values when rounding.\n * @type {number}\n */\nconst DECIMALS = 4;\n\n/**\n * @const\n * @type {import(\"../size.js\").Size}\n */\nconst GETFEATUREINFO_IMAGE_SIZE = [101, 101];\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images. Note that\n * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.\n * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.\n * @property {boolean} [hidpi=true] Use the `ol/Map#pixelRatio` value when requesting\n * the image from the remote server.\n * @property {import(\"./wms.js\").ServerType} [serverType] The type of\n * the remote WMS server: `mapserver`, `geoserver`, `carmentaserver`, or `qgis`.\n * Only needed if `hidpi` is `true`.\n * @property {import(\"../Image.js\").LoadFunction} [imageLoadFunction] Optional function to load an image given a URL.\n * @property {boolean} [interpolate=true] Use interpolated values when resampling. By default,\n * linear interpolation is used when resampling. Set to false to use the nearest neighbor instead.\n * @property {Object} [params] WMS request parameters.\n * At least a `LAYERS` param is required. `STYLES` is\n * `''` by default. `VERSION` is `1.3.0` by default. `WIDTH`, `HEIGHT`, `BBOX`\n * and `CRS` (`SRS` for WMS version < 1.3.0) will be set dynamically.\n * @property {import(\"../proj.js\").ProjectionLike} [projection] Projection. Default is the view projection.\n * @property {number} [ratio=1.5] Ratio. `1` means image requests are the size of the map viewport, `2` means\n * twice the width and height of the map viewport, and so on. Must be `1` or\n * higher.\n * @property {Array} [resolutions] Resolutions.\n * If specified, requests will be made for these resolutions only.\n * @property {string} [url] WMS service URL.\n */\n\n/**\n * @classdesc\n * Source for WMS servers providing single, untiled images.\n *\n * @fires module:ol/source/Image.ImageSourceEvent\n * @api\n */\nclass ImageWMS extends ImageSource {\n /**\n * @param {Options} [options] ImageWMS options.\n */\n constructor(options) {\n options = options ? options : {};\n\n super({\n attributions: options.attributions,\n interpolate: options.interpolate,\n projection: options.projection,\n resolutions: options.resolutions,\n });\n\n /**\n * @private\n * @type {CanvasRenderingContext2D}\n */\n this.context_ = createCanvasContext2D(1, 1);\n\n /**\n * @private\n * @type {?string}\n */\n this.crossOrigin_ =\n options.crossOrigin !== undefined ? options.crossOrigin : null;\n\n /**\n * @private\n * @type {string|undefined}\n */\n this.url_ = options.url;\n\n /**\n * @private\n * @type {import(\"../Image.js\").LoadFunction}\n */\n this.imageLoadFunction_ =\n options.imageLoadFunction !== undefined\n ? options.imageLoadFunction\n : defaultImageLoadFunction;\n\n /**\n * @private\n * @type {!Object}\n */\n this.params_ = Object.assign({}, options.params);\n\n /**\n * @private\n * @type {boolean}\n */\n this.v13_ = true;\n this.updateV13_();\n\n /**\n * @private\n * @type {import(\"./wms.js\").ServerType}\n */\n this.serverType_ = options.serverType;\n\n /**\n * @private\n * @type {boolean}\n */\n this.hidpi_ = options.hidpi !== undefined ? options.hidpi : true;\n\n /**\n * @private\n * @type {import(\"../Image.js\").default}\n */\n this.image_ = null;\n\n /**\n * @private\n * @type {import(\"../size.js\").Size}\n */\n this.imageSize_ = [0, 0];\n\n /**\n * @private\n * @type {number}\n */\n this.renderedRevision_ = 0;\n\n /**\n * @private\n * @type {number}\n */\n this.ratio_ = options.ratio !== undefined ? options.ratio : 1.5;\n }\n\n /**\n * Return the GetFeatureInfo URL for the passed coordinate, resolution, and\n * projection. Return `undefined` if the GetFeatureInfo URL cannot be\n * constructed.\n * @param {import(\"../coordinate.js\").Coordinate} coordinate Coordinate.\n * @param {number} resolution Resolution.\n * @param {import(\"../proj.js\").ProjectionLike} projection Projection.\n * @param {!Object} params GetFeatureInfo params. `INFO_FORMAT` at least should\n * be provided. If `QUERY_LAYERS` is not provided then the layers specified\n * in the `LAYERS` parameter will be used. `VERSION` should not be\n * specified here.\n * @return {string|undefined} GetFeatureInfo URL.\n * @api\n */\n getFeatureInfoUrl(coordinate, resolution, projection, params) {\n if (this.url_ === undefined) {\n return undefined;\n }\n const projectionObj = getProjection(projection);\n const sourceProjectionObj = this.getProjection();\n\n if (sourceProjectionObj && sourceProjectionObj !== projectionObj) {\n resolution = calculateSourceResolution(\n sourceProjectionObj,\n projectionObj,\n coordinate,\n resolution\n );\n coordinate = transform(coordinate, projectionObj, sourceProjectionObj);\n }\n\n const extent = getForViewAndSize(\n coordinate,\n resolution,\n 0,\n GETFEATUREINFO_IMAGE_SIZE\n );\n\n const baseParams = {\n 'SERVICE': 'WMS',\n 'VERSION': DEFAULT_VERSION,\n 'REQUEST': 'GetFeatureInfo',\n 'FORMAT': 'image/png',\n 'TRANSPARENT': true,\n 'QUERY_LAYERS': this.params_['LAYERS'],\n };\n Object.assign(baseParams, this.params_, params);\n\n const x = floor((coordinate[0] - extent[0]) / resolution, DECIMALS);\n const y = floor((extent[3] - coordinate[1]) / resolution, DECIMALS);\n baseParams[this.v13_ ? 'I' : 'X'] = x;\n baseParams[this.v13_ ? 'J' : 'Y'] = y;\n\n return this.getRequestUrl_(\n extent,\n GETFEATUREINFO_IMAGE_SIZE,\n 1,\n sourceProjectionObj || projectionObj,\n baseParams\n );\n }\n\n /**\n * Return the GetLegendGraphic URL, optionally optimized for the passed\n * resolution and possibly including any passed specific parameters. Returns\n * `undefined` if the GetLegendGraphic URL cannot be constructed.\n *\n * @param {number} [resolution] Resolution. If set to undefined, `SCALE`\n * will not be calculated and included in URL.\n * @param {Object} [params] GetLegendGraphic params. If `LAYER` is set, the\n * request is generated for this wms layer, else it will try to use the\n * configured wms layer. Default `FORMAT` is `image/png`.\n * `VERSION` should not be specified here.\n * @return {string|undefined} GetLegendGraphic URL.\n * @api\n */\n getLegendUrl(resolution, params) {\n if (this.url_ === undefined) {\n return undefined;\n }\n\n const baseParams = {\n 'SERVICE': 'WMS',\n 'VERSION': DEFAULT_VERSION,\n 'REQUEST': 'GetLegendGraphic',\n 'FORMAT': 'image/png',\n };\n\n if (params === undefined || params['LAYER'] === undefined) {\n const layers = this.params_.LAYERS;\n const isSingleLayer = !Array.isArray(layers) || layers.length === 1;\n if (!isSingleLayer) {\n return undefined;\n }\n baseParams['LAYER'] = layers;\n }\n\n if (resolution !== undefined) {\n const mpu = this.getProjection()\n ? this.getProjection().getMetersPerUnit()\n : 1;\n const pixelSize = 0.00028;\n baseParams['SCALE'] = (resolution * mpu) / pixelSize;\n }\n\n Object.assign(baseParams, params);\n\n return appendParams(/** @type {string} */ (this.url_), baseParams);\n }\n\n /**\n * Get the user-provided params, i.e. those passed to the constructor through\n * the \"params\" option, and possibly updated using the updateParams method.\n * @return {Object} Params.\n * @api\n */\n getParams() {\n return this.params_;\n }\n\n /**\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @param {number} resolution Resolution.\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {import(\"../Image.js\").default} Single image.\n */\n getImageInternal(extent, resolution, pixelRatio, projection) {\n if (this.url_ === undefined) {\n return null;\n }\n\n resolution = this.findNearestResolution(resolution);\n\n if (pixelRatio != 1 && (!this.hidpi_ || this.serverType_ === undefined)) {\n pixelRatio = 1;\n }\n\n const imageResolution = resolution / pixelRatio;\n\n const center = getCenter(extent);\n const viewWidth = ceil(getWidth(extent) / imageResolution, DECIMALS);\n const viewHeight = ceil(getHeight(extent) / imageResolution, DECIMALS);\n const viewExtent = getForViewAndSize(center, imageResolution, 0, [\n viewWidth,\n viewHeight,\n ]);\n const marginWidth = ceil(((this.ratio_ - 1) * viewWidth) / 2, DECIMALS);\n const requestWidth = viewWidth + 2 * marginWidth;\n const marginHeight = ceil(((this.ratio_ - 1) * viewHeight) / 2, DECIMALS);\n const requestHeight = viewHeight + 2 * marginHeight;\n const requestExtent = getForViewAndSize(center, imageResolution, 0, [\n requestWidth,\n requestHeight,\n ]);\n\n const image = this.image_;\n if (\n image &&\n this.renderedRevision_ == this.getRevision() &&\n image.getResolution() == resolution &&\n image.getPixelRatio() == pixelRatio &&\n containsExtent(image.getExtent(), viewExtent)\n ) {\n return image;\n }\n\n const params = {\n 'SERVICE': 'WMS',\n 'VERSION': DEFAULT_VERSION,\n 'REQUEST': 'GetMap',\n 'FORMAT': 'image/png',\n 'TRANSPARENT': true,\n };\n Object.assign(params, this.params_);\n\n this.imageSize_[0] = round(\n getWidth(requestExtent) / imageResolution,\n DECIMALS\n );\n this.imageSize_[1] = round(\n getHeight(requestExtent) / imageResolution,\n DECIMALS\n );\n\n const url = this.getRequestUrl_(\n requestExtent,\n this.imageSize_,\n pixelRatio,\n projection,\n params\n );\n\n this.image_ = new ImageWrapper(\n requestExtent,\n resolution,\n pixelRatio,\n url,\n this.crossOrigin_,\n this.imageLoadFunction_,\n this.context_\n );\n\n this.renderedRevision_ = this.getRevision();\n\n this.image_.addEventListener(\n EventType.CHANGE,\n this.handleImageChange.bind(this)\n );\n\n return this.image_;\n }\n\n /**\n * Return the image load function of the source.\n * @return {import(\"../Image.js\").LoadFunction} The image load function.\n * @api\n */\n getImageLoadFunction() {\n return this.imageLoadFunction_;\n }\n\n /**\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @param {import(\"../size.js\").Size} size Size.\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @param {Object} params Params.\n * @return {string} Request URL.\n * @private\n */\n getRequestUrl_(extent, size, pixelRatio, projection, params) {\n assert(this.url_ !== undefined, 9); // `url` must be configured or set using `#setUrl()`\n\n params[this.v13_ ? 'CRS' : 'SRS'] = projection.getCode();\n\n if (!('STYLES' in this.params_)) {\n params['STYLES'] = '';\n }\n\n if (pixelRatio != 1) {\n switch (this.serverType_) {\n case 'geoserver':\n const dpi = (90 * pixelRatio + 0.5) | 0;\n if ('FORMAT_OPTIONS' in params) {\n params['FORMAT_OPTIONS'] += ';dpi:' + dpi;\n } else {\n params['FORMAT_OPTIONS'] = 'dpi:' + dpi;\n }\n break;\n case 'mapserver':\n params['MAP_RESOLUTION'] = 90 * pixelRatio;\n break;\n case 'carmentaserver':\n case 'qgis':\n params['DPI'] = 90 * pixelRatio;\n break;\n default: // Unknown `serverType` configured\n assert(false, 8);\n break;\n }\n }\n\n params['WIDTH'] = size[0];\n params['HEIGHT'] = size[1];\n\n const axisOrientation = projection.getAxisOrientation();\n let bbox;\n if (this.v13_ && axisOrientation.substr(0, 2) == 'ne') {\n bbox = [extent[1], extent[0], extent[3], extent[2]];\n } else {\n bbox = extent;\n }\n params['BBOX'] = bbox.join(',');\n\n return appendParams(/** @type {string} */ (this.url_), params);\n }\n\n /**\n * Return the URL used for this WMS source.\n * @return {string|undefined} URL.\n * @api\n */\n getUrl() {\n return this.url_;\n }\n\n /**\n * Set the image load function of the source.\n * @param {import(\"../Image.js\").LoadFunction} imageLoadFunction Image load function.\n * @api\n */\n setImageLoadFunction(imageLoadFunction) {\n this.image_ = null;\n this.imageLoadFunction_ = imageLoadFunction;\n this.changed();\n }\n\n /**\n * Set the URL to use for requests.\n * @param {string|undefined} url URL.\n * @api\n */\n setUrl(url) {\n if (url != this.url_) {\n this.url_ = url;\n this.image_ = null;\n this.changed();\n }\n }\n\n /**\n * Update the user-provided params.\n * @param {Object} params Params.\n * @api\n */\n updateParams(params) {\n Object.assign(this.params_, params);\n this.updateV13_();\n this.image_ = null;\n this.changed();\n }\n\n /**\n * @private\n */\n updateV13_() {\n const version = this.params_['VERSION'] || DEFAULT_VERSION;\n this.v13_ = compareVersions(version, '1.3') >= 0;\n }\n}\n\nexport default ImageWMS;\n","/**\n * @module ol/source/ogcTileUtil\n */\n\nimport TileGrid from '../tilegrid/TileGrid.js';\nimport {getJSON, resolveUrl} from '../net.js';\nimport {get as getProjection} from '../proj.js';\nimport {getIntersection as intersectExtents} from '../extent.js';\n\n/**\n * See https://ogcapi.ogc.org/tiles/.\n */\n\n/**\n * @typedef {'map' | 'vector'} TileType\n */\n\n/**\n * @typedef {'topLeft' | 'bottomLeft'} CornerOfOrigin\n */\n\n/**\n * @typedef {Object} TileSet\n * @property {TileType} dataType Type of data represented in the tileset.\n * @property {string} [tileMatrixSetDefinition] Reference to a tile matrix set definition.\n * @property {TileMatrixSet} [tileMatrixSet] Tile matrix set definition.\n * @property {Array} [tileMatrixSetLimits] Tile matrix set limits.\n * @property {Array} links Tileset links.\n */\n\n/**\n * @typedef {Object} Link\n * @property {string} rel The link rel attribute.\n * @property {string} href The link URL.\n * @property {string} type The link type.\n */\n\n/**\n * @typedef {Object} TileMatrixSetLimit\n * @property {string} tileMatrix The tile matrix id.\n * @property {number} minTileRow The minimum tile row.\n * @property {number} maxTileRow The maximum tile row.\n * @property {number} minTileCol The minimum tile column.\n * @property {number} maxTileCol The maximum tile column.\n */\n\n/**\n * @typedef {Object} TileMatrixSet\n * @property {string} id The tile matrix set identifier.\n * @property {string} crs The coordinate reference system.\n * @property {Array} tileMatrices Array of tile matrices.\n */\n\n/**\n * @typedef {Object} TileMatrix\n * @property {string} id The tile matrix identifier.\n * @property {number} cellSize The pixel resolution (map units per pixel).\n * @property {Array} pointOfOrigin The map location of the matrix origin.\n * @property {CornerOfOrigin} [cornerOfOrigin='topLeft'] The corner of the matrix that represents the origin ('topLeft' or 'bottomLeft').\n * @property {number} matrixWidth The number of columns.\n * @property {number} matrixHeight The number of rows.\n * @property {number} tileWidth The pixel width of a tile.\n * @property {number} tileHeight The pixel height of a tile.\n */\n\n/**\n * @type {Object}\n */\nconst knownMapMediaTypes = {\n 'image/png': true,\n 'image/jpeg': true,\n 'image/gif': true,\n 'image/webp': true,\n};\n\n/**\n * @type {Object}\n */\nconst knownVectorMediaTypes = {\n 'application/vnd.mapbox-vector-tile': true,\n 'application/geo+json': true,\n};\n\n/**\n * @typedef {Object} TileSetInfo\n * @property {string} urlTemplate The tile URL template.\n * @property {import(\"../tilegrid/TileGrid.js\").default} grid The tile grid.\n * @property {import(\"../Tile.js\").UrlFunction} urlFunction The tile URL function.\n */\n\n/**\n * @typedef {Object} SourceInfo\n * @property {string} url The tile set URL.\n * @property {string} mediaType The preferred tile media type.\n * @property {Array} [supportedMediaTypes] The supported media types.\n * @property {import(\"../proj/Projection.js\").default} projection The source projection.\n * @property {Object} [context] Optional context for constructing the URL.\n */\n\n/**\n * @param {Array} links Tileset links.\n * @param {string} [mediaType] The preferred media type.\n * @return {string} The tile URL template.\n */\nexport function getMapTileUrlTemplate(links, mediaType) {\n let tileUrlTemplate;\n let fallbackUrlTemplate;\n for (let i = 0; i < links.length; ++i) {\n const link = links[i];\n if (link.rel === 'item') {\n if (link.type === mediaType) {\n tileUrlTemplate = link.href;\n break;\n }\n if (knownMapMediaTypes[link.type]) {\n fallbackUrlTemplate = link.href;\n } else if (!fallbackUrlTemplate && link.type.startsWith('image/')) {\n fallbackUrlTemplate = link.href;\n }\n }\n }\n\n if (!tileUrlTemplate) {\n if (fallbackUrlTemplate) {\n tileUrlTemplate = fallbackUrlTemplate;\n } else {\n throw new Error('Could not find \"item\" link');\n }\n }\n\n return tileUrlTemplate;\n}\n\n/**\n * @param {Array} links Tileset links.\n * @param {string} [mediaType] The preferred media type.\n * @param {Array} [supportedMediaTypes] The media types supported by the parser.\n * @return {string} The tile URL template.\n */\nexport function getVectorTileUrlTemplate(\n links,\n mediaType,\n supportedMediaTypes\n) {\n let tileUrlTemplate;\n let fallbackUrlTemplate;\n\n /**\n * Lookup of URL by media type.\n * @type {Object}\n */\n const hrefLookup = {};\n\n for (let i = 0; i < links.length; ++i) {\n const link = links[i];\n hrefLookup[link.type] = link.href;\n if (link.rel === 'item') {\n if (link.type === mediaType) {\n tileUrlTemplate = link.href;\n break;\n }\n if (knownVectorMediaTypes[link.type]) {\n fallbackUrlTemplate = link.href;\n }\n }\n }\n\n if (!tileUrlTemplate && supportedMediaTypes) {\n for (let i = 0; i < supportedMediaTypes.length; ++i) {\n const supportedMediaType = supportedMediaTypes[i];\n if (hrefLookup[supportedMediaType]) {\n tileUrlTemplate = hrefLookup[supportedMediaType];\n break;\n }\n }\n }\n\n if (!tileUrlTemplate) {\n if (fallbackUrlTemplate) {\n tileUrlTemplate = fallbackUrlTemplate;\n } else {\n throw new Error('Could not find \"item\" link');\n }\n }\n\n return tileUrlTemplate;\n}\n\n/**\n * @param {SourceInfo} sourceInfo The source info.\n * @param {TileMatrixSet} tileMatrixSet Tile matrix set.\n * @param {string} tileUrlTemplate Tile URL template.\n * @param {Array} [tileMatrixSetLimits] Tile matrix set limits.\n * @return {TileSetInfo} Tile set info.\n */\nfunction parseTileMatrixSet(\n sourceInfo,\n tileMatrixSet,\n tileUrlTemplate,\n tileMatrixSetLimits\n) {\n let projection = sourceInfo.projection;\n if (!projection) {\n projection = getProjection(tileMatrixSet.crs);\n if (!projection) {\n throw new Error(`Unsupported CRS: ${tileMatrixSet.crs}`);\n }\n }\n const backwards = projection.getAxisOrientation().substr(0, 2) !== 'en';\n\n const matrices = tileMatrixSet.tileMatrices;\n\n /**\n * @type {Object}\n */\n const matrixLookup = {};\n for (let i = 0; i < matrices.length; ++i) {\n const matrix = matrices[i];\n matrixLookup[matrix.id] = matrix;\n }\n\n /**\n * @type {Object}\n */\n const limitLookup = {};\n\n /**\n * @type {Array}\n */\n const matrixIds = [];\n\n if (tileMatrixSetLimits) {\n for (let i = 0; i < tileMatrixSetLimits.length; ++i) {\n const limit = tileMatrixSetLimits[i];\n const id = limit.tileMatrix;\n matrixIds.push(id);\n limitLookup[id] = limit;\n }\n } else {\n for (let i = 0; i < matrices.length; ++i) {\n const id = matrices[i].id;\n matrixIds.push(id);\n }\n }\n\n const length = matrixIds.length;\n const origins = new Array(length);\n const resolutions = new Array(length);\n const sizes = new Array(length);\n const tileSizes = new Array(length);\n const extent = [-Infinity, -Infinity, Infinity, Infinity];\n\n for (let i = 0; i < length; ++i) {\n const id = matrixIds[i];\n const matrix = matrixLookup[id];\n const origin = matrix.pointOfOrigin;\n if (backwards) {\n origins[i] = [origin[1], origin[0]];\n } else {\n origins[i] = origin;\n }\n resolutions[i] = matrix.cellSize;\n sizes[i] = [matrix.matrixWidth, matrix.matrixHeight];\n tileSizes[i] = [matrix.tileWidth, matrix.tileHeight];\n const limit = limitLookup[id];\n if (limit) {\n const tileMapWidth = matrix.cellSize * matrix.tileWidth;\n const minX = origins[i][0] + limit.minTileCol * tileMapWidth;\n const maxX = origins[i][0] + (limit.maxTileCol + 1) * tileMapWidth;\n\n const tileMapHeight = matrix.cellSize * matrix.tileHeight;\n const upsideDown = matrix.cornerOfOrigin === 'bottomLeft';\n\n let minY;\n let maxY;\n if (upsideDown) {\n minY = origins[i][1] + limit.minTileRow * tileMapHeight;\n maxY = origins[i][1] + (limit.maxTileRow + 1) * tileMapHeight;\n } else {\n minY = origins[i][1] - (limit.maxTileRow + 1) * tileMapHeight;\n maxY = origins[i][1] - limit.minTileRow * tileMapHeight;\n }\n\n intersectExtents(extent, [minX, minY, maxX, maxY], extent);\n }\n }\n\n const tileGrid = new TileGrid({\n origins: origins,\n resolutions: resolutions,\n sizes: sizes,\n tileSizes: tileSizes,\n extent: tileMatrixSetLimits ? extent : undefined,\n });\n\n const context = sourceInfo.context;\n const base = sourceInfo.url;\n\n function tileUrlFunction(tileCoord, pixelRatio, projection) {\n if (!tileCoord) {\n return undefined;\n }\n\n const id = matrixIds[tileCoord[0]];\n const matrix = matrixLookup[id];\n const upsideDown = matrix.cornerOfOrigin === 'bottomLeft';\n\n const localContext = {\n tileMatrix: id,\n tileCol: tileCoord[1],\n tileRow: upsideDown ? -tileCoord[2] - 1 : tileCoord[2],\n };\n\n if (tileMatrixSetLimits) {\n const limit = limitLookup[matrix.id];\n if (\n localContext.tileCol < limit.minTileCol ||\n localContext.tileCol > limit.maxTileCol ||\n localContext.tileRow < limit.minTileRow ||\n localContext.tileRow > limit.maxTileRow\n ) {\n return undefined;\n }\n }\n\n Object.assign(localContext, context);\n\n const url = tileUrlTemplate.replace(/\\{(\\w+?)\\}/g, function (m, p) {\n return localContext[p];\n });\n\n return resolveUrl(base, url);\n }\n\n return {\n grid: tileGrid,\n urlTemplate: tileUrlTemplate,\n urlFunction: tileUrlFunction,\n };\n}\n\n/**\n * @param {SourceInfo} sourceInfo The source info.\n * @param {TileSet} tileSet Tile set.\n * @return {TileSetInfo|Promise} Tile set info.\n */\nfunction parseTileSetMetadata(sourceInfo, tileSet) {\n const tileMatrixSetLimits = tileSet.tileMatrixSetLimits;\n let tileUrlTemplate;\n\n if (tileSet.dataType === 'map') {\n tileUrlTemplate = getMapTileUrlTemplate(\n tileSet.links,\n sourceInfo.mediaType\n );\n } else if (tileSet.dataType === 'vector') {\n tileUrlTemplate = getVectorTileUrlTemplate(\n tileSet.links,\n sourceInfo.mediaType,\n sourceInfo.supportedMediaTypes\n );\n } else {\n throw new Error('Expected tileset data type to be \"map\" or \"vector\"');\n }\n\n if (tileSet.tileMatrixSet) {\n return parseTileMatrixSet(\n sourceInfo,\n tileSet.tileMatrixSet,\n tileUrlTemplate,\n tileMatrixSetLimits\n );\n }\n\n const tileMatrixSetLink = tileSet.links.find(\n (link) =>\n link.rel === 'http://www.opengis.net/def/rel/ogc/1.0/tiling-scheme'\n );\n if (!tileMatrixSetLink) {\n throw new Error(\n 'Expected http://www.opengis.net/def/rel/ogc/1.0/tiling-scheme link or tileMatrixSet'\n );\n }\n const tileMatrixSetDefinition = tileMatrixSetLink.href;\n\n const url = resolveUrl(sourceInfo.url, tileMatrixSetDefinition);\n return getJSON(url).then(function (tileMatrixSet) {\n return parseTileMatrixSet(\n sourceInfo,\n tileMatrixSet,\n tileUrlTemplate,\n tileMatrixSetLimits\n );\n });\n}\n\n/**\n * @param {SourceInfo} sourceInfo Source info.\n * @return {Promise} Tile set info.\n */\nexport function getTileSetInfo(sourceInfo) {\n return getJSON(sourceInfo.url).then(function (tileSet) {\n return parseTileSetMetadata(sourceInfo, tileSet);\n });\n}\n","/**\n * @module ol/source/OGCMapTile\n */\nimport TileImage from './TileImage.js';\nimport {getTileSetInfo} from './ogcTileUtil.js';\nimport {error as logError} from '../console.js';\n\n/**\n * @typedef {Object} Options\n * @property {string} url URL to the OGC Map Tileset endpoint.\n * @property {Object} [context] A lookup of values to use in the tile URL template. The `{tileMatrix}`\n * (zoom level), `{tileRow}`, and `{tileCol}` variables in the URL will always be provided by the source.\n * @property {string} [mediaType] The content type for the tiles (e.g. \"image/png\"). If not provided,\n * the source will try to find a link with rel=\"item\" that uses a supported image type.\n * @property {import(\"../proj.js\").ProjectionLike} [projection] Projection. By default, the projection\n * will be derived from the `crs` of the `tileMatrixSet`. You can override this by supplying\n * a projection to the constructor.\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {number} [cacheSize] Tile cache size. The default depends on the screen size. Will be ignored if too small.\n * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images. Note that\n * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.\n * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.\n * @property {boolean} [interpolate=true] Use interpolated values when resampling. By default,\n * linear interpolation is used when resampling. Set to false to use the nearest neighbor instead.\n * @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).\n * Higher values can increase reprojection performance, but decrease precision.\n * @property {import(\"../Tile.js\").LoadFunction} [tileLoadFunction] Optional function to load a tile given a URL. The default is\n * ```js\n * function(tile, src) {\n * tile.getImage().src = src;\n * };\n * ```\n * @property {boolean} [wrapX=true] Whether to wrap the world horizontally.\n * @property {number} [transition] Duration of the opacity transition for rendering.\n * To disable the opacity transition, pass `transition: 0`.\n */\n\n/**\n * @classdesc\n * Layer source for map tiles from an [OGC API - Tiles](https://ogcapi.ogc.org/tiles/) service that provides \"map\" type tiles.\n * The service must conform to at least the core (http://www.opengis.net/spec/ogcapi-tiles-1/1.0/conf/core)\n * and tileset (http://www.opengis.net/spec/ogcapi-tiles-1/1.0/conf/tileset) conformance classes.\n * @api\n */\nclass OGCMapTile extends TileImage {\n /**\n * @param {Options} options OGC map tile options.\n */\n constructor(options) {\n super({\n attributions: options.attributions,\n cacheSize: options.cacheSize,\n crossOrigin: options.crossOrigin,\n interpolate: options.interpolate,\n projection: options.projection,\n reprojectionErrorThreshold: options.reprojectionErrorThreshold,\n state: 'loading',\n tileLoadFunction: options.tileLoadFunction,\n wrapX: options.wrapX !== undefined ? options.wrapX : true,\n transition: options.transition,\n });\n\n const sourceInfo = {\n url: options.url,\n projection: this.getProjection(),\n mediaType: options.mediaType,\n context: options.context || null,\n };\n\n getTileSetInfo(sourceInfo)\n .then(this.handleTileSetInfo_.bind(this))\n .catch(this.handleError_.bind(this));\n }\n\n /**\n * @param {import(\"./ogcTileUtil.js\").TileSetInfo} tileSetInfo Tile set info.\n * @private\n */\n handleTileSetInfo_(tileSetInfo) {\n this.tileGrid = tileSetInfo.grid;\n this.setTileUrlFunction(tileSetInfo.urlFunction, tileSetInfo.urlTemplate);\n this.setState('ready');\n }\n\n /**\n * @private\n * @param {Error} error The error.\n */\n handleError_(error) {\n logError(error);\n this.setState('error');\n }\n}\n\nexport default OGCMapTile;\n","/**\n * @module ol/source/VectorTile\n */\n\nimport EventType from '../events/EventType.js';\nimport Tile from '../VectorTile.js';\nimport TileCache from '../TileCache.js';\nimport TileGrid from '../tilegrid/TileGrid.js';\nimport TileState from '../TileState.js';\nimport UrlTile from './UrlTile.js';\nimport VectorRenderTile from '../VectorRenderTile.js';\nimport {DEFAULT_MAX_ZOOM} from '../tilegrid/common.js';\nimport {\n buffer as bufferExtent,\n getIntersection,\n intersects,\n} from '../extent.js';\nimport {createXYZ, extentFromProjection} from '../tilegrid.js';\nimport {fromKey, getCacheKeyForTileKey, getKeyZXY} from '../tilecoord.js';\nimport {isEmpty} from '../obj.js';\nimport {loadFeaturesXhr} from '../featureloader.js';\nimport {toSize} from '../size.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.\n * @property {number} [cacheSize] Initial tile cache size. Will auto-grow to hold at least twice the number of tiles in the viewport.\n * @property {import(\"../extent.js\").Extent} [extent] Extent.\n * @property {import(\"../format/Feature.js\").default} [format] Feature format for tiles. Used and required by the default.\n * @property {boolean} [overlaps=true] This source may have overlapping geometries. Setting this\n * to `false` (e.g. for sources with polygons that represent administrative\n * boundaries or TopoJSON sources) allows the renderer to optimise fill and\n * stroke operations.\n * @property {import(\"../proj.js\").ProjectionLike} [projection='EPSG:3857'] Projection of the tile grid.\n * @property {import(\"./Source.js\").State} [state] Source state.\n * @property {typeof import(\"../VectorTile.js\").default} [tileClass] Class used to instantiate image tiles.\n * Default is {@link module:ol/VectorTile~VectorTile}.\n * @property {number} [maxZoom=22] Optional max zoom level. Not used if `tileGrid` is provided.\n * @property {number} [minZoom] Optional min zoom level. Not used if `tileGrid` is provided.\n * @property {number|import(\"../size.js\").Size} [tileSize=512] Optional tile size. Not used if `tileGrid` is provided.\n * @property {number} [maxResolution] Optional tile grid resolution at level zero. Not used if `tileGrid` is provided.\n * @property {import(\"../tilegrid/TileGrid.js\").default} [tileGrid] Tile grid.\n * @property {import(\"../Tile.js\").LoadFunction} [tileLoadFunction]\n * Optional function to load a tile given a URL. Could look like this for pbf tiles:\n * ```js\n * function(tile, url) {\n * tile.setLoader(function(extent, resolution, projection) {\n * fetch(url).then(function(response) {\n * response.arrayBuffer().then(function(data) {\n * const format = tile.getFormat() // ol/format/MVT configured as source format\n * const features = format.readFeatures(data, {\n * extent: extent,\n * featureProjection: projection\n * });\n * tile.setFeatures(features);\n * });\n * });\n * });\n * }\n * ```\n * If you do not need extent, resolution and projection to get the features for a tile (e.g.\n * for GeoJSON tiles), your `tileLoadFunction` does not need a `setLoader()` call. Only make sure\n * to call `setFeatures()` on the tile:\n * ```js\n * const format = new GeoJSON({featureProjection: map.getView().getProjection()});\n * async function tileLoadFunction(tile, url) {\n * const response = await fetch(url);\n * const data = await response.json();\n * tile.setFeatures(format.readFeatures(data));\n * }\n * ```\n * @property {import(\"../Tile.js\").UrlFunction} [tileUrlFunction] Optional function to get tile URL given a tile coordinate and the projection.\n * @property {string} [url] URL template. Must include `{x}`, `{y}` or `{-y}`, and `{z}` placeholders.\n * A `{?-?}` template pattern, for example `subdomain{a-f}.domain.com`, may be\n * used instead of defining each one separately in the `urls` option.\n * @property {number} [transition] A duration for tile opacity\n * transitions in milliseconds. A duration of 0 disables the opacity transition.\n * @property {Array} [urls] An array of URL templates.\n * @property {boolean} [wrapX=true] Whether to wrap the world horizontally.\n * When set to `false`, only one world\n * will be rendered. When set to `true`, tiles will be wrapped horizontally to\n * render multiple worlds.\n * @property {number|import(\"../array.js\").NearestDirectionFunction} [zDirection=1]\n * Choose whether to use tiles with a higher or lower zoom level when between integer\n * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.\n */\n\n/**\n * @classdesc\n * Class for layer sources providing vector data divided into a tile grid, to be\n * used with {@link module:ol/layer/VectorTile~VectorTileLayer}. Although this source receives tiles\n * with vector features from the server, it is not meant for feature editing.\n * Features are optimized for rendering, their geometries are clipped at or near\n * tile boundaries and simplified for a view resolution. See\n * {@link module:ol/source/Vector~VectorSource} for vector sources that are suitable for feature\n * editing.\n *\n * @fires import(\"./Tile.js\").TileSourceEvent\n * @api\n */\nclass VectorTile extends UrlTile {\n /**\n * @param {!Options} options Vector tile options.\n */\n constructor(options) {\n const projection = options.projection || 'EPSG:3857';\n\n const extent = options.extent || extentFromProjection(projection);\n\n const tileGrid =\n options.tileGrid ||\n createXYZ({\n extent: extent,\n maxResolution: options.maxResolution,\n maxZoom: options.maxZoom !== undefined ? options.maxZoom : 22,\n minZoom: options.minZoom,\n tileSize: options.tileSize || 512,\n });\n\n super({\n attributions: options.attributions,\n attributionsCollapsible: options.attributionsCollapsible,\n cacheSize: options.cacheSize,\n interpolate: true,\n opaque: false,\n projection: projection,\n state: options.state,\n tileGrid: tileGrid,\n tileLoadFunction: options.tileLoadFunction\n ? options.tileLoadFunction\n : defaultLoadFunction,\n tileUrlFunction: options.tileUrlFunction,\n url: options.url,\n urls: options.urls,\n wrapX: options.wrapX === undefined ? true : options.wrapX,\n transition: options.transition,\n zDirection: options.zDirection === undefined ? 1 : options.zDirection,\n });\n\n /**\n * @private\n * @type {import(\"../format/Feature.js\").default|null}\n */\n this.format_ = options.format ? options.format : null;\n\n /**\n * @private\n * @type {TileCache}\n */\n this.sourceTileCache = new TileCache(this.tileCache.highWaterMark);\n\n /**\n * @private\n * @type {boolean}\n */\n this.overlaps_ = options.overlaps == undefined ? true : options.overlaps;\n\n /**\n * @protected\n * @type {typeof import(\"../VectorTile.js\").default}\n */\n this.tileClass = options.tileClass ? options.tileClass : Tile;\n\n /**\n * @private\n * @type {Object}\n */\n this.tileGrids_ = {};\n }\n\n /**\n * Get features whose bounding box intersects the provided extent. Only features for cached\n * tiles for the last rendered zoom level are available in the source. So this method is only\n * suitable for requesting tiles for extents that are currently rendered.\n *\n * Features are returned in random tile order and as they are included in the tiles. This means\n * they can be clipped, duplicated across tiles, and simplified to the render resolution.\n *\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @return {Array} Features.\n * @api\n */\n getFeaturesInExtent(extent) {\n const features = [];\n const tileCache = this.tileCache;\n if (tileCache.getCount() === 0) {\n return features;\n }\n const z = fromKey(tileCache.peekFirstKey())[0];\n const tileGrid = this.tileGrid;\n tileCache.forEach(function (tile) {\n if (tile.tileCoord[0] !== z || tile.getState() !== TileState.LOADED) {\n return;\n }\n const sourceTiles = tile.getSourceTiles();\n for (let i = 0, ii = sourceTiles.length; i < ii; ++i) {\n const sourceTile = sourceTiles[i];\n const tileCoord = sourceTile.tileCoord;\n if (intersects(extent, tileGrid.getTileCoordExtent(tileCoord))) {\n const tileFeatures = sourceTile.getFeatures();\n if (tileFeatures) {\n for (let j = 0, jj = tileFeatures.length; j < jj; ++j) {\n const candidate = tileFeatures[j];\n const geometry = candidate.getGeometry();\n if (intersects(extent, geometry.getExtent())) {\n features.push(candidate);\n }\n }\n }\n }\n }\n });\n return features;\n }\n\n /**\n * @return {boolean} The source can have overlapping geometries.\n */\n getOverlaps() {\n return this.overlaps_;\n }\n\n /**\n * clear {@link module:ol/TileCache~TileCache} and delete all source tiles\n * @api\n */\n clear() {\n this.tileCache.clear();\n this.sourceTileCache.clear();\n }\n\n /**\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @param {!Object} usedTiles Used tiles.\n */\n expireCache(projection, usedTiles) {\n const tileCache = this.getTileCacheForProjection(projection);\n const usedSourceTiles = Object.keys(usedTiles).reduce((acc, key) => {\n const cacheKey = getCacheKeyForTileKey(key);\n const tile = tileCache.peek(cacheKey);\n if (tile) {\n const sourceTiles = tile.sourceTiles;\n for (let i = 0, ii = sourceTiles.length; i < ii; ++i) {\n acc[sourceTiles[i].getKey()] = true;\n }\n }\n return acc;\n }, {});\n super.expireCache(projection, usedTiles);\n this.sourceTileCache.expireCache(usedSourceTiles);\n }\n\n /**\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"../proj/Projection\").default} projection Projection.\n * @param {VectorRenderTile} tile Vector image tile.\n * @return {Array} Tile keys.\n */\n getSourceTiles(pixelRatio, projection, tile) {\n if (tile.getState() === TileState.IDLE) {\n tile.setState(TileState.LOADING);\n const urlTileCoord = tile.wrappedTileCoord;\n const tileGrid = this.getTileGridForProjection(projection);\n const extent = tileGrid.getTileCoordExtent(urlTileCoord);\n const z = urlTileCoord[0];\n const resolution = tileGrid.getResolution(z);\n // make extent 1 pixel smaller so we don't load tiles for < 0.5 pixel render space\n bufferExtent(extent, -resolution, extent);\n const sourceTileGrid = this.tileGrid;\n const sourceExtent = sourceTileGrid.getExtent();\n if (sourceExtent) {\n getIntersection(extent, sourceExtent, extent);\n }\n const sourceZ = sourceTileGrid.getZForResolution(\n resolution,\n this.zDirection\n );\n\n sourceTileGrid.forEachTileCoord(extent, sourceZ, (sourceTileCoord) => {\n const tileUrl = this.tileUrlFunction(\n sourceTileCoord,\n pixelRatio,\n projection\n );\n const sourceTile = this.sourceTileCache.containsKey(tileUrl)\n ? this.sourceTileCache.get(tileUrl)\n : new this.tileClass(\n sourceTileCoord,\n tileUrl ? TileState.IDLE : TileState.EMPTY,\n tileUrl,\n this.format_,\n this.tileLoadFunction\n );\n tile.sourceTiles.push(sourceTile);\n const sourceTileState = sourceTile.getState();\n if (sourceTileState < TileState.LOADED) {\n const listenChange = (event) => {\n this.handleTileChange(event);\n const state = sourceTile.getState();\n if (state === TileState.LOADED || state === TileState.ERROR) {\n const sourceTileKey = sourceTile.getKey();\n if (sourceTileKey in tile.errorTileKeys) {\n if (sourceTile.getState() === TileState.LOADED) {\n delete tile.errorTileKeys[sourceTileKey];\n }\n } else {\n tile.loadingSourceTiles--;\n }\n if (state === TileState.ERROR) {\n tile.errorTileKeys[sourceTileKey] = true;\n } else {\n sourceTile.removeEventListener(EventType.CHANGE, listenChange);\n }\n if (tile.loadingSourceTiles === 0) {\n tile.setState(\n isEmpty(tile.errorTileKeys)\n ? TileState.LOADED\n : TileState.ERROR\n );\n }\n }\n };\n sourceTile.addEventListener(EventType.CHANGE, listenChange);\n tile.loadingSourceTiles++;\n }\n if (sourceTileState === TileState.IDLE) {\n sourceTile.extent =\n sourceTileGrid.getTileCoordExtent(sourceTileCoord);\n sourceTile.projection = projection;\n sourceTile.resolution = sourceTileGrid.getResolution(\n sourceTileCoord[0]\n );\n this.sourceTileCache.set(tileUrl, sourceTile);\n sourceTile.load();\n }\n });\n if (!tile.loadingSourceTiles) {\n tile.setState(\n tile.sourceTiles.some(\n (sourceTile) => sourceTile.getState() === TileState.ERROR\n )\n ? TileState.ERROR\n : TileState.LOADED\n );\n }\n }\n\n return tile.sourceTiles;\n }\n\n /**\n * @param {number} z Tile coordinate z.\n * @param {number} x Tile coordinate x.\n * @param {number} y Tile coordinate y.\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {!VectorRenderTile} Tile.\n */\n getTile(z, x, y, pixelRatio, projection) {\n const coordKey = getKeyZXY(z, x, y);\n const key = this.getKey();\n let tile;\n if (this.tileCache.containsKey(coordKey)) {\n tile = this.tileCache.get(coordKey);\n if (tile.key === key) {\n return tile;\n }\n }\n const tileCoord = [z, x, y];\n let urlTileCoord = this.getTileCoordForTileUrlFunction(\n tileCoord,\n projection\n );\n const sourceExtent = this.getTileGrid().getExtent();\n const tileGrid = this.getTileGridForProjection(projection);\n if (urlTileCoord && sourceExtent) {\n const tileExtent = tileGrid.getTileCoordExtent(urlTileCoord);\n // make extent 1 pixel smaller so we don't load tiles for < 0.5 pixel render space\n bufferExtent(tileExtent, -tileGrid.getResolution(z), tileExtent);\n if (!intersects(sourceExtent, tileExtent)) {\n urlTileCoord = null;\n }\n }\n let empty = true;\n if (urlTileCoord !== null) {\n const sourceTileGrid = this.tileGrid;\n const resolution = tileGrid.getResolution(z);\n const sourceZ = sourceTileGrid.getZForResolution(resolution, 1);\n // make extent 1 pixel smaller so we don't load tiles for < 0.5 pixel render space\n const extent = tileGrid.getTileCoordExtent(urlTileCoord);\n bufferExtent(extent, -resolution, extent);\n sourceTileGrid.forEachTileCoord(extent, sourceZ, (sourceTileCoord) => {\n empty =\n empty &&\n !this.tileUrlFunction(sourceTileCoord, pixelRatio, projection);\n });\n }\n const newTile = new VectorRenderTile(\n tileCoord,\n empty ? TileState.EMPTY : TileState.IDLE,\n urlTileCoord,\n this.getSourceTiles.bind(this, pixelRatio, projection)\n );\n\n newTile.key = key;\n if (tile) {\n newTile.interimTile = tile;\n newTile.refreshInterimChain();\n this.tileCache.replace(coordKey, newTile);\n } else {\n this.tileCache.set(coordKey, newTile);\n }\n return newTile;\n }\n\n /**\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {!import(\"../tilegrid/TileGrid.js\").default} Tile grid.\n */\n getTileGridForProjection(projection) {\n const code = projection.getCode();\n let tileGrid = this.tileGrids_[code];\n if (!tileGrid) {\n // A tile grid that matches the tile size of the source tile grid is more\n // likely to have 1:1 relationships between source tiles and rendered tiles.\n const sourceTileGrid = this.tileGrid;\n const resolutions = sourceTileGrid.getResolutions().slice();\n const origins = resolutions.map(function (resolution, z) {\n return sourceTileGrid.getOrigin(z);\n });\n const tileSizes = resolutions.map(function (resolution, z) {\n return sourceTileGrid.getTileSize(z);\n });\n const length = DEFAULT_MAX_ZOOM + 1;\n for (let z = resolutions.length; z < length; ++z) {\n resolutions.push(resolutions[z - 1] / 2);\n origins.push(origins[z - 1]);\n tileSizes.push(tileSizes[z - 1]);\n }\n tileGrid = new TileGrid({\n extent: sourceTileGrid.getExtent(),\n origins: origins,\n resolutions: resolutions,\n tileSizes: tileSizes,\n });\n this.tileGrids_[code] = tileGrid;\n }\n return tileGrid;\n }\n\n /**\n * Get the tile pixel ratio for this source.\n * @param {number} pixelRatio Pixel ratio.\n * @return {number} Tile pixel ratio.\n */\n getTilePixelRatio(pixelRatio) {\n return pixelRatio;\n }\n\n /**\n * @param {number} z Z.\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {import(\"../size.js\").Size} Tile size.\n */\n getTilePixelSize(z, pixelRatio, projection) {\n const tileGrid = this.getTileGridForProjection(projection);\n const tileSize = toSize(tileGrid.getTileSize(z), this.tmpSize);\n return [\n Math.round(tileSize[0] * pixelRatio),\n Math.round(tileSize[1] * pixelRatio),\n ];\n }\n\n /**\n * Increases the cache size if needed\n * @param {number} tileCount Minimum number of tiles needed.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n */\n updateCacheSize(tileCount, projection) {\n super.updateCacheSize(tileCount * 2, projection);\n this.sourceTileCache.highWaterMark =\n this.getTileCacheForProjection(projection).highWaterMark;\n }\n}\n\nexport default VectorTile;\n\n/**\n * Sets the loader for a tile.\n * @param {import(\"../VectorTile.js\").default} tile Vector tile.\n * @param {string} url URL.\n */\nexport function defaultLoadFunction(tile, url) {\n tile.setLoader(\n /**\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @param {number} resolution Resolution.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n */\n function (extent, resolution, projection) {\n loadFeaturesXhr(\n url,\n tile.getFormat(),\n extent,\n resolution,\n projection,\n tile.onLoad.bind(tile),\n tile.onError.bind(tile)\n );\n }\n );\n}\n","/**\n * @module ol/source/OGCVectorTile\n */\n\nimport VectorTileSource from './VectorTile.js';\nimport {getTileSetInfo} from './ogcTileUtil.js';\nimport {error as logError} from '../console.js';\n\n/**\n * @typedef {Object} Options\n * @property {string} url URL to the OGC Vector Tileset endpoint.\n * @property {Object} [context] A lookup of values to use in the tile URL template. The `{tileMatrix}`\n * (zoom level), `{tileRow}`, and `{tileCol}` variables in the URL will always be provided by the source.\n * @property {import(\"../format/Feature.js\").default} format Feature parser for tiles.\n * @property {string} [mediaType] The content type for the tiles (e.g. \"application/vnd.mapbox-vector-tile\"). If not provided,\n * the source will try to find a link with rel=\"item\" that uses a vector type supported by the configured format.\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.\n * @property {number} [cacheSize] Initial tile cache size. Will auto-grow to hold at least twice the number of tiles in the viewport.\n * @property {boolean} [overlaps=true] This source may have overlapping geometries. Setting this\n * to `false` (e.g. for sources with polygons that represent administrative\n * boundaries or TopoJSON sources) allows the renderer to optimise fill and\n * stroke operations.\n * @property {import(\"../proj.js\").ProjectionLike} [projection='EPSG:3857'] Projection of the tile grid.\n * @property {typeof import(\"../VectorTile.js\").default} [tileClass] Class used to instantiate image tiles.\n * Default is {@link module:ol/VectorTile~VectorTile}.\n * @property {number} [transition] A duration for tile opacity\n * transitions in milliseconds. A duration of 0 disables the opacity transition.\n * @property {boolean} [wrapX=true] Whether to wrap the world horizontally.\n * When set to `false`, only one world\n * will be rendered. When set to `true`, tiles will be wrapped horizontally to\n * render multiple worlds.\n * @property {number|import(\"../array.js\").NearestDirectionFunction} [zDirection=1]\n * Choose whether to use tiles with a higher or lower zoom level when between integer\n * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.\n */\n\n/**\n * @classdesc\n * Layer source for map tiles from an [OGC API - Tiles](https://ogcapi.ogc.org/tiles/) service that provides \"vector\" type tiles.\n * The service must conform to at least the core (http://www.opengis.net/spec/ogcapi-tiles-1/1.0/conf/core)\n * and tileset (http://www.opengis.net/spec/ogcapi-tiles-1/1.0/conf/tileset) conformance classes.\n *\n * Vector tile sets may come in a variety of formats (e.g. GeoJSON, MVT). The `format` option is used to determine\n * which of the advertised media types is used. If you need to force the use of a particular media type, you can\n * provide the `mediaType` option.\n * @api\n */\nclass OGCVectorTile extends VectorTileSource {\n /**\n * @param {Options} options OGC vector tile options.\n */\n constructor(options) {\n super({\n attributions: options.attributions,\n attributionsCollapsible: options.attributionsCollapsible,\n cacheSize: options.cacheSize,\n format: options.format,\n overlaps: options.overlaps,\n projection: options.projection,\n tileClass: options.tileClass,\n transition: options.transition,\n wrapX: options.wrapX,\n zDirection: options.zDirection,\n state: 'loading',\n });\n\n const sourceInfo = {\n url: options.url,\n projection: this.getProjection(),\n mediaType: options.mediaType,\n supportedMediaTypes: options.format.supportedMediaTypes,\n context: options.context || null,\n };\n\n getTileSetInfo(sourceInfo)\n .then(this.handleTileSetInfo_.bind(this))\n .catch(this.handleError_.bind(this));\n }\n\n /**\n * @param {import(\"./ogcTileUtil.js\").TileSetInfo} tileSetInfo Tile set info.\n * @private\n */\n handleTileSetInfo_(tileSetInfo) {\n this.tileGrid = tileSetInfo.grid;\n this.setTileUrlFunction(tileSetInfo.urlFunction, tileSetInfo.urlTemplate);\n this.setState('ready');\n }\n\n /**\n * @private\n * @param {Error} error The error.\n */\n handleError_(error) {\n logError(error);\n this.setState('error');\n }\n}\n\nexport default OGCVectorTile;\n","/**\n * @module ol/source/OSM\n */\n\nimport XYZ from './XYZ.js';\n\n/**\n * The attribution containing a link to the OpenStreetMap Copyright and License\n * page.\n * @const\n * @type {string}\n * @api\n */\nexport const ATTRIBUTION =\n '© ' +\n 'OpenStreetMap ' +\n 'contributors.';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {number} [cacheSize] Initial tile cache size. Will auto-grow to hold at least the number of tiles in the viewport.\n * @property {null|string} [crossOrigin='anonymous'] The `crossOrigin` attribute for loaded images. Note that\n * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.\n * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.\n * @property {boolean} [interpolate=true] Use interpolated values when resampling. By default,\n * linear interpolation is used when resampling. Set to false to use the nearest neighbor instead.\n * @property {number} [maxZoom=19] Max zoom.\n * @property {boolean} [opaque=true] Whether the layer is opaque.\n * @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).\n * Higher values can increase reprojection performance, but decrease precision.\n * @property {import(\"../Tile.js\").LoadFunction} [tileLoadFunction] Optional function to load a tile given a URL. The default is\n * ```js\n * function(imageTile, src) {\n * imageTile.getImage().src = src;\n * };\n * ```\n * @property {number} [transition=250] Duration of the opacity transition for rendering.\n * To disable the opacity transition, pass `transition: 0`.\n * @property {string} [url='https://tile.openstreetmap.org/{z}/{x}/{y}.png'] URL template.\n * Must include `{x}`, `{y}` or `{-y}`, and `{z}` placeholders.\n * @property {boolean} [wrapX=true] Whether to wrap the world horizontally.\n * @property {number|import(\"../array.js\").NearestDirectionFunction} [zDirection=0]\n * Choose whether to use tiles with a higher or lower zoom level when between integer\n * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.\n */\n\n/**\n * @classdesc\n * Layer source for the OpenStreetMap tile server.\n * @api\n */\nclass OSM extends XYZ {\n /**\n * @param {Options} [options] Open Street Map options.\n */\n constructor(options) {\n options = options || {};\n\n let attributions;\n if (options.attributions !== undefined) {\n attributions = options.attributions;\n } else {\n attributions = [ATTRIBUTION];\n }\n\n const crossOrigin =\n options.crossOrigin !== undefined ? options.crossOrigin : 'anonymous';\n\n const url =\n options.url !== undefined\n ? options.url\n : 'https://tile.openstreetmap.org/{z}/{x}/{y}.png';\n\n super({\n attributions: attributions,\n attributionsCollapsible: false,\n cacheSize: options.cacheSize,\n crossOrigin: crossOrigin,\n interpolate: options.interpolate,\n maxZoom: options.maxZoom !== undefined ? options.maxZoom : 19,\n opaque: options.opaque !== undefined ? options.opaque : true,\n reprojectionErrorThreshold: options.reprojectionErrorThreshold,\n tileLoadFunction: options.tileLoadFunction,\n transition: options.transition,\n url: url,\n wrapX: options.wrapX,\n zDirection: options.zDirection,\n });\n }\n}\n\nexport default OSM;\n","/**\n * @module ol/layer/BaseImage\n */\nimport Layer from './Layer.js';\n\n/**\n * @template {import(\"../source/Image.js\").default} ImageSourceType\n * @typedef {Object} Options\n * @property {string} [className='ol-layer'] A CSS class name to set to the layer element.\n * @property {number} [opacity=1] Opacity (0, 1).\n * @property {boolean} [visible=true] Visibility.\n * @property {import(\"../extent.js\").Extent} [extent] The bounding extent for layer rendering. The layer will not be\n * rendered outside of this extent.\n * @property {number} [zIndex] The z-index for layer rendering. At rendering time, the layers\n * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed\n * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`\n * method was used.\n * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be\n * visible.\n * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will\n * be visible.\n * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be\n * visible.\n * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will\n * be visible.\n * @property {import(\"../Map.js\").default} [map] Sets the layer as overlay on a map. The map will not manage\n * this layer in its layers collection, and the layer will be rendered on top. This is useful for\n * temporary layers. The standard way to add a layer to a map and have it managed by the map is to\n * use {@link import(\"../Map.js\").default#addLayer map.addLayer()}.\n * @property {ImageSourceType} [source] Source for this layer.\n * @property {Object} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.\n */\n\n/**\n * @classdesc\n * Server-rendered images that are available for arbitrary extents and\n * resolutions.\n * Note that any property set in the options is set as a {@link module:ol/Object~BaseObject}\n * property on the layer object; for example, setting `title: 'My Title'` in the\n * options means that `title` is observable, and has get/set accessors.\n *\n * @template {import(\"../source/Image.js\").default} ImageSourceType\n * @template {import(\"../renderer/Layer.js\").default} RendererType\n * @extends {Layer}\n * @api\n */\nclass BaseImageLayer extends Layer {\n /**\n * @param {Options} [options] Layer options.\n */\n constructor(options) {\n options = options ? options : {};\n super(options);\n }\n}\n\nexport default BaseImageLayer;\n","/**\n * @module ol/renderer/Layer\n */\nimport EventType from '../events/EventType.js';\nimport ImageState from '../ImageState.js';\nimport Observable from '../Observable.js';\nimport {abstract} from '../util.js';\n\n/**\n * @template {import(\"../layer/Layer.js\").default} LayerType\n */\nclass LayerRenderer extends Observable {\n /**\n * @param {LayerType} layer Layer.\n */\n constructor(layer) {\n super();\n\n /**\n * The renderer is initialized and ready to render.\n * @type {boolean}\n */\n this.ready = true;\n\n /** @private */\n this.boundHandleImageChange_ = this.handleImageChange_.bind(this);\n\n /**\n * @protected\n * @type {LayerType}\n */\n this.layer_ = layer;\n\n /**\n * @type {import(\"../render/canvas/ExecutorGroup\").default}\n */\n this.declutterExecutorGroup = null;\n }\n\n /**\n * Asynchronous layer level hit detection.\n * @param {import(\"../pixel.js\").Pixel} pixel Pixel.\n * @return {Promise>} Promise that resolves with\n * an array of features.\n */\n getFeatures(pixel) {\n return abstract();\n }\n\n /**\n * @param {import(\"../pixel.js\").Pixel} pixel Pixel.\n * @return {Uint8ClampedArray|Uint8Array|Float32Array|DataView|null} Pixel data.\n */\n getData(pixel) {\n return null;\n }\n\n /**\n * Determine whether render should be called.\n * @abstract\n * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n * @return {boolean} Layer is ready to be rendered.\n */\n prepareFrame(frameState) {\n return abstract();\n }\n\n /**\n * Render the layer.\n * @abstract\n * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n * @param {HTMLElement|null} target Target that may be used to render content to.\n * @return {HTMLElement|null} The rendered element.\n */\n renderFrame(frameState, target) {\n return abstract();\n }\n\n /**\n * @param {Object>} tiles Lookup of loaded tiles by zoom level.\n * @param {number} zoom Zoom level.\n * @param {import(\"../Tile.js\").default} tile Tile.\n * @return {boolean|void} If `false`, the tile will not be considered loaded.\n */\n loadedTileCallback(tiles, zoom, tile) {\n if (!tiles[zoom]) {\n tiles[zoom] = {};\n }\n tiles[zoom][tile.tileCoord.toString()] = tile;\n return undefined;\n }\n\n /**\n * Create a function that adds loaded tiles to the tile lookup.\n * @param {import(\"../source/Tile.js\").default} source Tile source.\n * @param {import(\"../proj/Projection.js\").default} projection Projection of the tiles.\n * @param {Object>} tiles Lookup of loaded tiles by zoom level.\n * @return {function(number, import(\"../TileRange.js\").default):boolean} A function that can be\n * called with a zoom level and a tile range to add loaded tiles to the lookup.\n * @protected\n */\n createLoadedTileFinder(source, projection, tiles) {\n return (\n /**\n * @param {number} zoom Zoom level.\n * @param {import(\"../TileRange.js\").default} tileRange Tile range.\n * @return {boolean} The tile range is fully loaded.\n */\n (zoom, tileRange) => {\n const callback = this.loadedTileCallback.bind(this, tiles, zoom);\n return source.forEachLoadedTile(projection, zoom, tileRange, callback);\n }\n );\n }\n /**\n * @abstract\n * @param {import(\"../coordinate.js\").Coordinate} coordinate Coordinate.\n * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n * @param {number} hitTolerance Hit tolerance in pixels.\n * @param {import(\"./vector.js\").FeatureCallback} callback Feature callback.\n * @param {Array>} matches The hit detected matches with tolerance.\n * @return {T|undefined} Callback result.\n * @template T\n */\n forEachFeatureAtCoordinate(\n coordinate,\n frameState,\n hitTolerance,\n callback,\n matches\n ) {\n return undefined;\n }\n\n /**\n * @return {LayerType} Layer.\n */\n getLayer() {\n return this.layer_;\n }\n\n /**\n * Perform action necessary to get the layer rendered after new fonts have loaded\n * @abstract\n */\n handleFontsChanged() {}\n\n /**\n * Handle changes in image state.\n * @param {import(\"../events/Event.js\").default} event Image change event.\n * @private\n */\n handleImageChange_(event) {\n const image = /** @type {import(\"../Image.js\").default} */ (event.target);\n if (\n image.getState() === ImageState.LOADED ||\n image.getState() === ImageState.ERROR\n ) {\n this.renderIfReadyAndVisible();\n }\n }\n\n /**\n * Load the image if not already loaded, and register the image change\n * listener if needed.\n * @param {import(\"../ImageBase.js\").default} image Image.\n * @return {boolean} `true` if the image is already loaded, `false` otherwise.\n * @protected\n */\n loadImage(image) {\n let imageState = image.getState();\n if (imageState != ImageState.LOADED && imageState != ImageState.ERROR) {\n image.addEventListener(EventType.CHANGE, this.boundHandleImageChange_);\n }\n if (imageState == ImageState.IDLE) {\n image.load();\n imageState = image.getState();\n }\n return imageState == ImageState.LOADED;\n }\n\n /**\n * @protected\n */\n renderIfReadyAndVisible() {\n const layer = this.getLayer();\n if (layer && layer.getVisible() && layer.getSourceState() === 'ready') {\n layer.changed();\n }\n }\n\n /**\n * Clean up.\n */\n disposeInternal() {\n delete this.layer_;\n super.disposeInternal();\n }\n}\n\nexport default LayerRenderer;\n","/**\n * @module ol/renderer/canvas/Layer\n */\nimport LayerRenderer from '../Layer.js';\nimport RenderEvent from '../../render/Event.js';\nimport RenderEventType from '../../render/EventType.js';\nimport {\n apply as applyTransform,\n compose as composeTransform,\n create as createTransform,\n} from '../../transform.js';\nimport {asArray} from '../../color.js';\nimport {createCanvasContext2D} from '../../dom.js';\nimport {equals} from '../../array.js';\nimport {\n getBottomLeft,\n getBottomRight,\n getTopLeft,\n getTopRight,\n} from '../../extent.js';\n\n/**\n * @type {Array}\n */\nexport const canvasPool = [];\n\n/**\n * @type {CanvasRenderingContext2D}\n */\nlet pixelContext = null;\n\nfunction createPixelContext() {\n pixelContext = createCanvasContext2D(1, 1, undefined, {\n willReadFrequently: true,\n });\n}\n\n/**\n * @abstract\n * @template {import(\"../../layer/Layer.js\").default} LayerType\n * @extends {LayerRenderer}\n */\nclass CanvasLayerRenderer extends LayerRenderer {\n /**\n * @param {LayerType} layer Layer.\n */\n constructor(layer) {\n super(layer);\n\n /**\n * @protected\n * @type {HTMLElement}\n */\n this.container = null;\n\n /**\n * @protected\n * @type {number}\n */\n this.renderedResolution;\n\n /**\n * A temporary transform. The values in this transform should only be used in a\n * function that sets the values.\n * @protected\n * @type {import(\"../../transform.js\").Transform}\n */\n this.tempTransform = createTransform();\n\n /**\n * The transform for rendered pixels to viewport CSS pixels. This transform must\n * be set when rendering a frame and may be used by other functions after rendering.\n * @protected\n * @type {import(\"../../transform.js\").Transform}\n */\n this.pixelTransform = createTransform();\n\n /**\n * The transform for viewport CSS pixels to rendered pixels. This transform must\n * be set when rendering a frame and may be used by other functions after rendering.\n * @protected\n * @type {import(\"../../transform.js\").Transform}\n */\n this.inversePixelTransform = createTransform();\n\n /**\n * @type {CanvasRenderingContext2D}\n */\n this.context = null;\n\n /**\n * @type {boolean}\n */\n this.containerReused = false;\n\n /**\n * @private\n * @type {CanvasRenderingContext2D}\n */\n this.pixelContext_ = null;\n\n /**\n * @protected\n * @type {import(\"../../Map.js\").FrameState|null}\n */\n this.frameState = null;\n }\n\n /**\n * @param {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} image Image.\n * @param {number} col The column index.\n * @param {number} row The row index.\n * @return {Uint8ClampedArray|null} The image data.\n */\n getImageData(image, col, row) {\n if (!pixelContext) {\n createPixelContext();\n }\n pixelContext.clearRect(0, 0, 1, 1);\n\n let data;\n try {\n pixelContext.drawImage(image, col, row, 1, 1, 0, 0, 1, 1);\n data = pixelContext.getImageData(0, 0, 1, 1).data;\n } catch (err) {\n pixelContext = null;\n return null;\n }\n return data;\n }\n\n /**\n * @param {import('../../Map.js').FrameState} frameState Frame state.\n * @return {string} Background color.\n */\n getBackground(frameState) {\n const layer = this.getLayer();\n let background = layer.getBackground();\n if (typeof background === 'function') {\n background = background(frameState.viewState.resolution);\n }\n return background || undefined;\n }\n\n /**\n * Get a rendering container from an existing target, if compatible.\n * @param {HTMLElement} target Potential render target.\n * @param {string} transform CSS Transform.\n * @param {string} [backgroundColor] Background color.\n */\n useContainer(target, transform, backgroundColor) {\n const layerClassName = this.getLayer().getClassName();\n let container, context;\n if (\n target &&\n target.className === layerClassName &&\n (!backgroundColor ||\n (target &&\n target.style.backgroundColor &&\n equals(\n asArray(target.style.backgroundColor),\n asArray(backgroundColor)\n )))\n ) {\n const canvas = target.firstElementChild;\n if (canvas instanceof HTMLCanvasElement) {\n context = canvas.getContext('2d');\n }\n }\n if (context && context.canvas.style.transform === transform) {\n // Container of the previous layer renderer can be used.\n this.container = target;\n this.context = context;\n this.containerReused = true;\n } else if (this.containerReused) {\n // Previously reused container cannot be used any more.\n this.container = null;\n this.context = null;\n this.containerReused = false;\n } else if (this.container) {\n this.container.style.backgroundColor = null;\n }\n if (!this.container) {\n container = document.createElement('div');\n container.className = layerClassName;\n let style = container.style;\n style.position = 'absolute';\n style.width = '100%';\n style.height = '100%';\n context = createCanvasContext2D();\n const canvas = context.canvas;\n container.appendChild(canvas);\n style = canvas.style;\n style.position = 'absolute';\n style.left = '0';\n style.transformOrigin = 'top left';\n this.container = container;\n this.context = context;\n }\n if (\n !this.containerReused &&\n backgroundColor &&\n !this.container.style.backgroundColor\n ) {\n this.container.style.backgroundColor = backgroundColor;\n }\n }\n\n /**\n * @param {CanvasRenderingContext2D} context Context.\n * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n * @param {import(\"../../extent.js\").Extent} extent Clip extent.\n * @protected\n */\n clipUnrotated(context, frameState, extent) {\n const topLeft = getTopLeft(extent);\n const topRight = getTopRight(extent);\n const bottomRight = getBottomRight(extent);\n const bottomLeft = getBottomLeft(extent);\n\n applyTransform(frameState.coordinateToPixelTransform, topLeft);\n applyTransform(frameState.coordinateToPixelTransform, topRight);\n applyTransform(frameState.coordinateToPixelTransform, bottomRight);\n applyTransform(frameState.coordinateToPixelTransform, bottomLeft);\n\n const inverted = this.inversePixelTransform;\n applyTransform(inverted, topLeft);\n applyTransform(inverted, topRight);\n applyTransform(inverted, bottomRight);\n applyTransform(inverted, bottomLeft);\n\n context.save();\n context.beginPath();\n context.moveTo(Math.round(topLeft[0]), Math.round(topLeft[1]));\n context.lineTo(Math.round(topRight[0]), Math.round(topRight[1]));\n context.lineTo(Math.round(bottomRight[0]), Math.round(bottomRight[1]));\n context.lineTo(Math.round(bottomLeft[0]), Math.round(bottomLeft[1]));\n context.clip();\n }\n\n /**\n * @param {import(\"../../render/EventType.js\").default} type Event type.\n * @param {CanvasRenderingContext2D} context Context.\n * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n * @private\n */\n dispatchRenderEvent_(type, context, frameState) {\n const layer = this.getLayer();\n if (layer.hasListener(type)) {\n const event = new RenderEvent(\n type,\n this.inversePixelTransform,\n frameState,\n context\n );\n layer.dispatchEvent(event);\n }\n }\n\n /**\n * @param {CanvasRenderingContext2D} context Context.\n * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n * @protected\n */\n preRender(context, frameState) {\n this.frameState = frameState;\n this.dispatchRenderEvent_(RenderEventType.PRERENDER, context, frameState);\n }\n\n /**\n * @param {CanvasRenderingContext2D} context Context.\n * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n * @protected\n */\n postRender(context, frameState) {\n this.dispatchRenderEvent_(RenderEventType.POSTRENDER, context, frameState);\n }\n\n /**\n * Creates a transform for rendering to an element that will be rotated after rendering.\n * @param {import(\"../../coordinate.js\").Coordinate} center Center.\n * @param {number} resolution Resolution.\n * @param {number} rotation Rotation.\n * @param {number} pixelRatio Pixel ratio.\n * @param {number} width Width of the rendered element (in pixels).\n * @param {number} height Height of the rendered element (in pixels).\n * @param {number} offsetX Offset on the x-axis in view coordinates.\n * @protected\n * @return {!import(\"../../transform.js\").Transform} Transform.\n */\n getRenderTransform(\n center,\n resolution,\n rotation,\n pixelRatio,\n width,\n height,\n offsetX\n ) {\n const dx1 = width / 2;\n const dy1 = height / 2;\n const sx = pixelRatio / resolution;\n const sy = -sx;\n const dx2 = -center[0] + offsetX;\n const dy2 = -center[1];\n return composeTransform(\n this.tempTransform,\n dx1,\n dy1,\n sx,\n sy,\n -rotation,\n dx2,\n dy2\n );\n }\n\n /**\n * Clean up.\n */\n disposeInternal() {\n delete this.frameState;\n super.disposeInternal();\n }\n}\n\nexport default CanvasLayerRenderer;\n","/**\n * @module ol/renderer/canvas/ImageLayer\n */\nimport CanvasLayerRenderer from './Layer.js';\nimport ImageState from '../../ImageState.js';\nimport ViewHint from '../../ViewHint.js';\nimport {\n apply as applyTransform,\n compose as composeTransform,\n makeInverse,\n toString as toTransformString,\n} from '../../transform.js';\nimport {\n containsCoordinate,\n containsExtent,\n getHeight,\n getIntersection,\n getWidth,\n intersects as intersectsExtent,\n isEmpty,\n} from '../../extent.js';\nimport {fromUserExtent} from '../../proj.js';\n\n/**\n * @classdesc\n * Canvas renderer for image layers.\n * @api\n */\nclass CanvasImageLayerRenderer extends CanvasLayerRenderer {\n /**\n * @param {import(\"../../layer/Image.js\").default} imageLayer Image layer.\n */\n constructor(imageLayer) {\n super(imageLayer);\n\n /**\n * @protected\n * @type {?import(\"../../ImageBase.js\").default}\n */\n this.image_ = null;\n }\n\n /**\n * @return {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} Image.\n */\n getImage() {\n return this.image_ ? this.image_.getImage() : null;\n }\n\n /**\n * Determine whether render should be called.\n * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n * @return {boolean} Layer is ready to be rendered.\n */\n prepareFrame(frameState) {\n const layerState = frameState.layerStatesArray[frameState.layerIndex];\n const pixelRatio = frameState.pixelRatio;\n const viewState = frameState.viewState;\n const viewResolution = viewState.resolution;\n\n const imageSource = this.getLayer().getSource();\n\n const hints = frameState.viewHints;\n\n let renderedExtent = frameState.extent;\n if (layerState.extent !== undefined) {\n renderedExtent = getIntersection(\n renderedExtent,\n fromUserExtent(layerState.extent, viewState.projection)\n );\n }\n\n if (\n !hints[ViewHint.ANIMATING] &&\n !hints[ViewHint.INTERACTING] &&\n !isEmpty(renderedExtent)\n ) {\n if (imageSource) {\n const projection = viewState.projection;\n const image = imageSource.getImage(\n renderedExtent,\n viewResolution,\n pixelRatio,\n projection\n );\n if (image) {\n if (this.loadImage(image)) {\n this.image_ = image;\n } else if (image.getState() === ImageState.EMPTY) {\n this.image_ = null;\n }\n }\n } else {\n this.image_ = null;\n }\n }\n\n return !!this.image_;\n }\n\n /**\n * @param {import(\"../../pixel.js\").Pixel} pixel Pixel.\n * @return {Uint8ClampedArray} Data at the pixel location.\n */\n getData(pixel) {\n const frameState = this.frameState;\n if (!frameState) {\n return null;\n }\n\n const layer = this.getLayer();\n const coordinate = applyTransform(\n frameState.pixelToCoordinateTransform,\n pixel.slice()\n );\n\n const layerExtent = layer.getExtent();\n if (layerExtent) {\n if (!containsCoordinate(layerExtent, coordinate)) {\n return null;\n }\n }\n\n const imageExtent = this.image_.getExtent();\n const img = this.getImage();\n\n const imageMapWidth = getWidth(imageExtent);\n const col = Math.floor(\n img.width * ((coordinate[0] - imageExtent[0]) / imageMapWidth)\n );\n if (col < 0 || col >= img.width) {\n return null;\n }\n\n const imageMapHeight = getHeight(imageExtent);\n const row = Math.floor(\n img.height * ((imageExtent[3] - coordinate[1]) / imageMapHeight)\n );\n if (row < 0 || row >= img.height) {\n return null;\n }\n\n return this.getImageData(img, col, row);\n }\n\n /**\n * Render the layer.\n * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n * @param {HTMLElement} target Target that may be used to render content to.\n * @return {HTMLElement} The rendered element.\n */\n renderFrame(frameState, target) {\n const image = this.image_;\n const imageExtent = image.getExtent();\n const imageResolution = image.getResolution();\n const imagePixelRatio = image.getPixelRatio();\n const layerState = frameState.layerStatesArray[frameState.layerIndex];\n const pixelRatio = frameState.pixelRatio;\n const viewState = frameState.viewState;\n const viewCenter = viewState.center;\n const viewResolution = viewState.resolution;\n const scale =\n (pixelRatio * imageResolution) / (viewResolution * imagePixelRatio);\n\n const extent = frameState.extent;\n const resolution = viewState.resolution;\n const rotation = viewState.rotation;\n // desired dimensions of the canvas in pixels\n const width = Math.round((getWidth(extent) / resolution) * pixelRatio);\n const height = Math.round((getHeight(extent) / resolution) * pixelRatio);\n\n // set forward and inverse pixel transforms\n composeTransform(\n this.pixelTransform,\n frameState.size[0] / 2,\n frameState.size[1] / 2,\n 1 / pixelRatio,\n 1 / pixelRatio,\n rotation,\n -width / 2,\n -height / 2\n );\n makeInverse(this.inversePixelTransform, this.pixelTransform);\n\n const canvasTransform = toTransformString(this.pixelTransform);\n\n this.useContainer(target, canvasTransform, this.getBackground(frameState));\n\n const context = this.context;\n const canvas = context.canvas;\n\n if (canvas.width != width || canvas.height != height) {\n canvas.width = width;\n canvas.height = height;\n } else if (!this.containerReused) {\n context.clearRect(0, 0, width, height);\n }\n\n // clipped rendering if layer extent is set\n let clipped = false;\n let render = true;\n if (layerState.extent) {\n const layerExtent = fromUserExtent(\n layerState.extent,\n viewState.projection\n );\n render = intersectsExtent(layerExtent, frameState.extent);\n clipped = render && !containsExtent(layerExtent, frameState.extent);\n if (clipped) {\n this.clipUnrotated(context, frameState, layerExtent);\n }\n }\n\n const img = this.getImage();\n\n const transform = composeTransform(\n this.tempTransform,\n width / 2,\n height / 2,\n scale,\n scale,\n 0,\n (imagePixelRatio * (imageExtent[0] - viewCenter[0])) / imageResolution,\n (imagePixelRatio * (viewCenter[1] - imageExtent[3])) / imageResolution\n );\n\n this.renderedResolution = (imageResolution * pixelRatio) / imagePixelRatio;\n\n const dw = img.width * transform[0];\n const dh = img.height * transform[3];\n\n if (!this.getLayer().getSource().getInterpolate()) {\n context.imageSmoothingEnabled = false;\n }\n\n this.preRender(context, frameState);\n if (render && dw >= 0.5 && dh >= 0.5) {\n const dx = transform[4];\n const dy = transform[5];\n const opacity = layerState.opacity;\n let previousAlpha;\n if (opacity !== 1) {\n previousAlpha = context.globalAlpha;\n context.globalAlpha = opacity;\n }\n context.drawImage(img, 0, 0, +img.width, +img.height, dx, dy, dw, dh);\n if (opacity !== 1) {\n context.globalAlpha = previousAlpha;\n }\n }\n this.postRender(context, frameState);\n\n if (clipped) {\n context.restore();\n }\n context.imageSmoothingEnabled = true;\n\n if (canvasTransform !== canvas.style.transform) {\n canvas.style.transform = canvasTransform;\n }\n\n return this.container;\n }\n}\n\nexport default CanvasImageLayerRenderer;\n","/**\n * @module ol/layer/Image\n */\nimport BaseImageLayer from './BaseImage.js';\nimport CanvasImageLayerRenderer from '../renderer/canvas/ImageLayer.js';\n\n/**\n * @classdesc\n * Server-rendered images that are available for arbitrary extents and\n * resolutions.\n * Note that any property set in the options is set as a {@link module:ol/Object~BaseObject}\n * property on the layer object; for example, setting `title: 'My Title'` in the\n * options means that `title` is observable, and has get/set accessors.\n *\n * @template {import(\"../source/Image.js\").default} ImageSourceType\n * @extends {BaseImageLayer}\n * @api\n */\nclass ImageLayer extends BaseImageLayer {\n /**\n * @param {import(\"./BaseImage.js\").Options} [options] Layer options.\n */\n constructor(options) {\n super(options);\n }\n\n createRenderer() {\n return new CanvasImageLayerRenderer(this);\n }\n\n /**\n * Get data for a pixel location. A four element RGBA array will be returned. For requests outside the\n * layer extent, `null` will be returned. Data for an image can only be retrieved if the\n * source's `crossOrigin` property is set.\n *\n * ```js\n * // display layer data on every pointer move\n * map.on('pointermove', (event) => {\n * console.log(layer.getData(event.pixel));\n * });\n * ```\n * @param {import(\"../pixel\").Pixel} pixel Pixel.\n * @return {Uint8ClampedArray|Uint8Array|Float32Array|DataView|null} Pixel data.\n * @api\n */\n getData(pixel) {\n return super.getData(pixel);\n }\n}\n\nexport default ImageLayer;\n","/**\n * @module ol/layer/TileProperty\n */\n\n/**\n * @enum {string}\n */\nexport default {\n PRELOAD: 'preload',\n USE_INTERIM_TILES_ON_ERROR: 'useInterimTilesOnError',\n};\n","/**\n * @module ol/layer/BaseTile\n */\nimport Layer from './Layer.js';\nimport TileProperty from './TileProperty.js';\n\n/***\n * @template Return\n * @typedef {import(\"../Observable\").OnSignature &\n * import(\"../Observable\").OnSignature &\n * import(\"../Observable\").OnSignature &\n * import(\"../Observable\").CombinedOnSignature} BaseTileLayerOnSignature\n */\n\n/**\n * @template {import(\"../source/Tile.js\").default} TileSourceType\n * @typedef {Object} Options\n * @property {string} [className='ol-layer'] A CSS class name to set to the layer element.\n * @property {number} [opacity=1] Opacity (0, 1).\n * @property {boolean} [visible=true] Visibility.\n * @property {import(\"../extent.js\").Extent} [extent] The bounding extent for layer rendering. The layer will not be\n * rendered outside of this extent.\n * @property {number} [zIndex] The z-index for layer rendering. At rendering time, the layers\n * will be ordered, first by Z-index and then by position. When `undefined`, a `zIndex` of 0 is assumed\n * for layers that are added to the map's `layers` collection, or `Infinity` when the layer's `setMap()`\n * method was used.\n * @property {number} [minResolution] The minimum resolution (inclusive) at which this layer will be\n * visible.\n * @property {number} [maxResolution] The maximum resolution (exclusive) below which this layer will\n * be visible.\n * @property {number} [minZoom] The minimum view zoom level (exclusive) above which this layer will be\n * visible.\n * @property {number} [maxZoom] The maximum view zoom level (inclusive) at which this layer will\n * be visible.\n * @property {number} [preload=0] Preload. Load low-resolution tiles up to `preload` levels. `0`\n * means no preloading.\n * @property {TileSourceType} [source] Source for this layer.\n * @property {import(\"../Map.js\").default} [map] Sets the layer as overlay on a map. The map will not manage\n * this layer in its layers collection, and the layer will be rendered on top. This is useful for\n * temporary layers. The standard way to add a layer to a map and have it managed by the map is to\n * use {@link import(\"../Map.js\").default#addLayer map.addLayer()}.\n * @property {boolean} [useInterimTilesOnError=true] Use interim tiles on error.\n * @property {Object} [properties] Arbitrary observable properties. Can be accessed with `#get()` and `#set()`.\n */\n\n/**\n * @classdesc\n * For layer sources that provide pre-rendered, tiled images in grids that are\n * organized by zoom levels for specific resolutions.\n * Note that any property set in the options is set as a {@link module:ol/Object~BaseObject}\n * property on the layer object; for example, setting `title: 'My Title'` in the\n * options means that `title` is observable, and has get/set accessors.\n *\n * @template {import(\"../source/Tile.js\").default} TileSourceType\n * @template {import(\"../renderer/Layer.js\").default} RendererType\n * @extends {Layer}\n * @api\n */\nclass BaseTileLayer extends Layer {\n /**\n * @param {Options} [options] Tile layer options.\n */\n constructor(options) {\n options = options ? options : {};\n\n const baseOptions = Object.assign({}, options);\n\n delete baseOptions.preload;\n delete baseOptions.useInterimTilesOnError;\n super(baseOptions);\n\n /***\n * @type {BaseTileLayerOnSignature}\n */\n this.on;\n\n /***\n * @type {BaseTileLayerOnSignature}\n */\n this.once;\n\n /***\n * @type {BaseTileLayerOnSignature}\n */\n this.un;\n\n this.setPreload(options.preload !== undefined ? options.preload : 0);\n this.setUseInterimTilesOnError(\n options.useInterimTilesOnError !== undefined\n ? options.useInterimTilesOnError\n : true\n );\n }\n\n /**\n * Return the level as number to which we will preload tiles up to.\n * @return {number} The level to preload tiles up to.\n * @observable\n * @api\n */\n getPreload() {\n return /** @type {number} */ (this.get(TileProperty.PRELOAD));\n }\n\n /**\n * Set the level as number to which we will preload tiles up to.\n * @param {number} preload The level to preload tiles up to.\n * @observable\n * @api\n */\n setPreload(preload) {\n this.set(TileProperty.PRELOAD, preload);\n }\n\n /**\n * Whether we use interim tiles on error.\n * @return {boolean} Use interim tiles on error.\n * @observable\n * @api\n */\n getUseInterimTilesOnError() {\n return /** @type {boolean} */ (\n this.get(TileProperty.USE_INTERIM_TILES_ON_ERROR)\n );\n }\n\n /**\n * Set whether we use interim tiles on error.\n * @param {boolean} useInterimTilesOnError Use interim tiles on error.\n * @observable\n * @api\n */\n setUseInterimTilesOnError(useInterimTilesOnError) {\n this.set(TileProperty.USE_INTERIM_TILES_ON_ERROR, useInterimTilesOnError);\n }\n\n /**\n * Get data for a pixel location. The return type depends on the source data. For image tiles,\n * a four element RGBA array will be returned. For data tiles, the array length will match the\n * number of bands in the dataset. For requests outside the layer extent, `null` will be returned.\n * Data for a image tiles can only be retrieved if the source's `crossOrigin` property is set.\n *\n * ```js\n * // display layer data on every pointer move\n * map.on('pointermove', (event) => {\n * console.log(layer.getData(event.pixel));\n * });\n * ```\n * @param {import(\"../pixel\").Pixel} pixel Pixel.\n * @return {Uint8ClampedArray|Uint8Array|Float32Array|DataView|null} Pixel data.\n * @api\n */\n getData(pixel) {\n return super.getData(pixel);\n }\n}\n\nexport default BaseTileLayer;\n","/**\n * @module ol/renderer/canvas/TileLayer\n */\nimport CanvasLayerRenderer from './Layer.js';\nimport ImageTile from '../../ImageTile.js';\nimport ReprojTile from '../../reproj/Tile.js';\nimport TileRange from '../../TileRange.js';\nimport TileState from '../../TileState.js';\nimport {\n apply as applyTransform,\n compose as composeTransform,\n makeInverse,\n toString as toTransformString,\n} from '../../transform.js';\nimport {ascending} from '../../array.js';\nimport {\n containsCoordinate,\n createEmpty,\n equals,\n getHeight,\n getIntersection,\n getRotatedViewport,\n getTopLeft,\n getWidth,\n intersects,\n} from '../../extent.js';\nimport {fromUserExtent} from '../../proj.js';\nimport {getUid} from '../../util.js';\nimport {toSize} from '../../size.js';\n\n/**\n * @classdesc\n * Canvas renderer for tile layers.\n * @api\n * @template {import(\"../../layer/Tile.js\").default|import(\"../../layer/VectorTile.js\").default} [LayerType=import(\"../../layer/Tile.js\").default|import(\"../../layer/VectorTile.js\").default]\n * @extends {CanvasLayerRenderer}\n */\nclass CanvasTileLayerRenderer extends CanvasLayerRenderer {\n /**\n * @param {LayerType} tileLayer Tile layer.\n */\n constructor(tileLayer) {\n super(tileLayer);\n\n /**\n * Rendered extent has changed since the previous `renderFrame()` call\n * @type {boolean}\n */\n this.extentChanged = true;\n\n /**\n * @private\n * @type {?import(\"../../extent.js\").Extent}\n */\n this.renderedExtent_ = null;\n\n /**\n * @protected\n * @type {number}\n */\n this.renderedPixelRatio;\n\n /**\n * @protected\n * @type {import(\"../../proj/Projection.js\").default}\n */\n this.renderedProjection = null;\n\n /**\n * @protected\n * @type {number}\n */\n this.renderedRevision;\n\n /**\n * @protected\n * @type {!Array}\n */\n this.renderedTiles = [];\n\n /**\n * @private\n * @type {boolean}\n */\n this.newTiles_ = false;\n\n /**\n * @protected\n * @type {import(\"../../extent.js\").Extent}\n */\n this.tmpExtent = createEmpty();\n\n /**\n * @private\n * @type {import(\"../../TileRange.js\").default}\n */\n this.tmpTileRange_ = new TileRange(0, 0, 0, 0);\n }\n\n /**\n * @protected\n * @param {import(\"../../Tile.js\").default} tile Tile.\n * @return {boolean} Tile is drawable.\n */\n isDrawableTile(tile) {\n const tileLayer = this.getLayer();\n const tileState = tile.getState();\n const useInterimTilesOnError = tileLayer.getUseInterimTilesOnError();\n return (\n tileState == TileState.LOADED ||\n tileState == TileState.EMPTY ||\n (tileState == TileState.ERROR && !useInterimTilesOnError)\n );\n }\n\n /**\n * @param {number} z Tile coordinate z.\n * @param {number} x Tile coordinate x.\n * @param {number} y Tile coordinate y.\n * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n * @return {!import(\"../../Tile.js\").default} Tile.\n */\n getTile(z, x, y, frameState) {\n const pixelRatio = frameState.pixelRatio;\n const projection = frameState.viewState.projection;\n const tileLayer = this.getLayer();\n const tileSource = tileLayer.getSource();\n let tile = tileSource.getTile(z, x, y, pixelRatio, projection);\n if (tile.getState() == TileState.ERROR) {\n if (tileLayer.getUseInterimTilesOnError() && tileLayer.getPreload() > 0) {\n // Preloaded tiles for lower resolutions might have finished loading.\n this.newTiles_ = true;\n }\n }\n if (!this.isDrawableTile(tile)) {\n tile = tile.getInterimTile();\n }\n return tile;\n }\n\n /**\n * @param {import(\"../../pixel.js\").Pixel} pixel Pixel.\n * @return {Uint8ClampedArray} Data at the pixel location.\n */\n getData(pixel) {\n const frameState = this.frameState;\n if (!frameState) {\n return null;\n }\n\n const layer = this.getLayer();\n const coordinate = applyTransform(\n frameState.pixelToCoordinateTransform,\n pixel.slice()\n );\n\n const layerExtent = layer.getExtent();\n if (layerExtent) {\n if (!containsCoordinate(layerExtent, coordinate)) {\n return null;\n }\n }\n\n const pixelRatio = frameState.pixelRatio;\n const projection = frameState.viewState.projection;\n const viewState = frameState.viewState;\n const source = layer.getRenderSource();\n const tileGrid = source.getTileGridForProjection(viewState.projection);\n const tilePixelRatio = source.getTilePixelRatio(frameState.pixelRatio);\n\n for (\n let z = tileGrid.getZForResolution(viewState.resolution);\n z >= tileGrid.getMinZoom();\n --z\n ) {\n const tileCoord = tileGrid.getTileCoordForCoordAndZ(coordinate, z);\n const tile = source.getTile(\n z,\n tileCoord[1],\n tileCoord[2],\n pixelRatio,\n projection\n );\n if (\n !(tile instanceof ImageTile || tile instanceof ReprojTile) ||\n (tile instanceof ReprojTile && tile.getState() === TileState.EMPTY)\n ) {\n return null;\n }\n\n if (tile.getState() !== TileState.LOADED) {\n continue;\n }\n\n const tileOrigin = tileGrid.getOrigin(z);\n const tileSize = toSize(tileGrid.getTileSize(z));\n const tileResolution = tileGrid.getResolution(z);\n\n const col = Math.floor(\n tilePixelRatio *\n ((coordinate[0] - tileOrigin[0]) / tileResolution -\n tileCoord[1] * tileSize[0])\n );\n\n const row = Math.floor(\n tilePixelRatio *\n ((tileOrigin[1] - coordinate[1]) / tileResolution -\n tileCoord[2] * tileSize[1])\n );\n\n const gutter = Math.round(\n tilePixelRatio * source.getGutterForProjection(viewState.projection)\n );\n\n return this.getImageData(tile.getImage(), col + gutter, row + gutter);\n }\n\n return null;\n }\n\n /**\n * @param {Object>} tiles Lookup of loaded tiles by zoom level.\n * @param {number} zoom Zoom level.\n * @param {import(\"../../Tile.js\").default} tile Tile.\n * @return {boolean|void} If `false`, the tile will not be considered loaded.\n */\n loadedTileCallback(tiles, zoom, tile) {\n if (this.isDrawableTile(tile)) {\n return super.loadedTileCallback(tiles, zoom, tile);\n }\n return false;\n }\n\n /**\n * Determine whether render should be called.\n * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n * @return {boolean} Layer is ready to be rendered.\n */\n prepareFrame(frameState) {\n return !!this.getLayer().getSource();\n }\n\n /**\n * Render the layer.\n * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n * @param {HTMLElement} target Target that may be used to render content to.\n * @return {HTMLElement} The rendered element.\n */\n renderFrame(frameState, target) {\n const layerState = frameState.layerStatesArray[frameState.layerIndex];\n const viewState = frameState.viewState;\n const projection = viewState.projection;\n const viewResolution = viewState.resolution;\n const viewCenter = viewState.center;\n const rotation = viewState.rotation;\n const pixelRatio = frameState.pixelRatio;\n\n const tileLayer = this.getLayer();\n const tileSource = tileLayer.getSource();\n const sourceRevision = tileSource.getRevision();\n const tileGrid = tileSource.getTileGridForProjection(projection);\n const z = tileGrid.getZForResolution(viewResolution, tileSource.zDirection);\n const tileResolution = tileGrid.getResolution(z);\n\n let extent = frameState.extent;\n const resolution = frameState.viewState.resolution;\n const tilePixelRatio = tileSource.getTilePixelRatio(pixelRatio);\n // desired dimensions of the canvas in pixels\n const width = Math.round((getWidth(extent) / resolution) * pixelRatio);\n const height = Math.round((getHeight(extent) / resolution) * pixelRatio);\n\n const layerExtent =\n layerState.extent && fromUserExtent(layerState.extent, projection);\n if (layerExtent) {\n extent = getIntersection(\n extent,\n fromUserExtent(layerState.extent, projection)\n );\n }\n\n const dx = (tileResolution * width) / 2 / tilePixelRatio;\n const dy = (tileResolution * height) / 2 / tilePixelRatio;\n const canvasExtent = [\n viewCenter[0] - dx,\n viewCenter[1] - dy,\n viewCenter[0] + dx,\n viewCenter[1] + dy,\n ];\n\n const tileRange = tileGrid.getTileRangeForExtentAndZ(extent, z);\n\n /**\n * @type {Object>}\n */\n const tilesToDrawByZ = {};\n tilesToDrawByZ[z] = {};\n\n const findLoadedTiles = this.createLoadedTileFinder(\n tileSource,\n projection,\n tilesToDrawByZ\n );\n\n const tmpExtent = this.tmpExtent;\n const tmpTileRange = this.tmpTileRange_;\n this.newTiles_ = false;\n const viewport = rotation\n ? getRotatedViewport(\n viewState.center,\n resolution,\n rotation,\n frameState.size\n )\n : undefined;\n for (let x = tileRange.minX; x <= tileRange.maxX; ++x) {\n for (let y = tileRange.minY; y <= tileRange.maxY; ++y) {\n if (\n rotation &&\n !tileGrid.tileCoordIntersectsViewport([z, x, y], viewport)\n ) {\n continue;\n }\n const tile = this.getTile(z, x, y, frameState);\n if (this.isDrawableTile(tile)) {\n const uid = getUid(this);\n if (tile.getState() == TileState.LOADED) {\n tilesToDrawByZ[z][tile.tileCoord.toString()] = tile;\n let inTransition = tile.inTransition(uid);\n if (inTransition && layerState.opacity !== 1) {\n // Skipping transition when layer is not fully opaque avoids visual artifacts.\n tile.endTransition(uid);\n inTransition = false;\n }\n if (\n !this.newTiles_ &&\n (inTransition || !this.renderedTiles.includes(tile))\n ) {\n this.newTiles_ = true;\n }\n }\n if (tile.getAlpha(uid, frameState.time) === 1) {\n // don't look for alt tiles if alpha is 1\n continue;\n }\n }\n\n const childTileRange = tileGrid.getTileCoordChildTileRange(\n tile.tileCoord,\n tmpTileRange,\n tmpExtent\n );\n\n let covered = false;\n if (childTileRange) {\n covered = findLoadedTiles(z + 1, childTileRange);\n }\n if (!covered) {\n tileGrid.forEachTileCoordParentTileRange(\n tile.tileCoord,\n findLoadedTiles,\n tmpTileRange,\n tmpExtent\n );\n }\n }\n }\n\n const canvasScale =\n ((tileResolution / viewResolution) * pixelRatio) / tilePixelRatio;\n\n // set forward and inverse pixel transforms\n composeTransform(\n this.pixelTransform,\n frameState.size[0] / 2,\n frameState.size[1] / 2,\n 1 / pixelRatio,\n 1 / pixelRatio,\n rotation,\n -width / 2,\n -height / 2\n );\n\n const canvasTransform = toTransformString(this.pixelTransform);\n\n this.useContainer(target, canvasTransform, this.getBackground(frameState));\n const context = this.context;\n const canvas = context.canvas;\n\n makeInverse(this.inversePixelTransform, this.pixelTransform);\n\n // set scale transform for calculating tile positions on the canvas\n composeTransform(\n this.tempTransform,\n width / 2,\n height / 2,\n canvasScale,\n canvasScale,\n 0,\n -width / 2,\n -height / 2\n );\n\n if (canvas.width != width || canvas.height != height) {\n canvas.width = width;\n canvas.height = height;\n } else if (!this.containerReused) {\n context.clearRect(0, 0, width, height);\n }\n\n if (layerExtent) {\n this.clipUnrotated(context, frameState, layerExtent);\n }\n\n if (!tileSource.getInterpolate()) {\n context.imageSmoothingEnabled = false;\n }\n\n this.preRender(context, frameState);\n\n this.renderedTiles.length = 0;\n /** @type {Array} */\n let zs = Object.keys(tilesToDrawByZ).map(Number);\n zs.sort(ascending);\n\n let clips, clipZs, currentClip;\n if (\n layerState.opacity === 1 &&\n (!this.containerReused ||\n tileSource.getOpaque(frameState.viewState.projection))\n ) {\n zs = zs.reverse();\n } else {\n clips = [];\n clipZs = [];\n }\n for (let i = zs.length - 1; i >= 0; --i) {\n const currentZ = zs[i];\n const currentTilePixelSize = tileSource.getTilePixelSize(\n currentZ,\n pixelRatio,\n projection\n );\n const currentResolution = tileGrid.getResolution(currentZ);\n const currentScale = currentResolution / tileResolution;\n const dx = currentTilePixelSize[0] * currentScale * canvasScale;\n const dy = currentTilePixelSize[1] * currentScale * canvasScale;\n const originTileCoord = tileGrid.getTileCoordForCoordAndZ(\n getTopLeft(canvasExtent),\n currentZ\n );\n const originTileExtent = tileGrid.getTileCoordExtent(originTileCoord);\n const origin = applyTransform(this.tempTransform, [\n (tilePixelRatio * (originTileExtent[0] - canvasExtent[0])) /\n tileResolution,\n (tilePixelRatio * (canvasExtent[3] - originTileExtent[3])) /\n tileResolution,\n ]);\n const tileGutter =\n tilePixelRatio * tileSource.getGutterForProjection(projection);\n const tilesToDraw = tilesToDrawByZ[currentZ];\n for (const tileCoordKey in tilesToDraw) {\n const tile = /** @type {import(\"../../ImageTile.js\").default} */ (\n tilesToDraw[tileCoordKey]\n );\n const tileCoord = tile.tileCoord;\n\n // Calculate integer positions and sizes so that tiles align\n const xIndex = originTileCoord[1] - tileCoord[1];\n const nextX = Math.round(origin[0] - (xIndex - 1) * dx);\n const yIndex = originTileCoord[2] - tileCoord[2];\n const nextY = Math.round(origin[1] - (yIndex - 1) * dy);\n const x = Math.round(origin[0] - xIndex * dx);\n const y = Math.round(origin[1] - yIndex * dy);\n const w = nextX - x;\n const h = nextY - y;\n const transition = z === currentZ;\n\n const inTransition =\n transition && tile.getAlpha(getUid(this), frameState.time) !== 1;\n let contextSaved = false;\n if (!inTransition) {\n if (clips) {\n // Clip mask for regions in this tile that already filled by a higher z tile\n currentClip = [x, y, x + w, y, x + w, y + h, x, y + h];\n for (let i = 0, ii = clips.length; i < ii; ++i) {\n if (z !== currentZ && currentZ < clipZs[i]) {\n const clip = clips[i];\n if (\n intersects(\n [x, y, x + w, y + h],\n [clip[0], clip[3], clip[4], clip[7]]\n )\n ) {\n if (!contextSaved) {\n context.save();\n contextSaved = true;\n }\n context.beginPath();\n // counter-clockwise (outer ring) for current tile\n context.moveTo(currentClip[0], currentClip[1]);\n context.lineTo(currentClip[2], currentClip[3]);\n context.lineTo(currentClip[4], currentClip[5]);\n context.lineTo(currentClip[6], currentClip[7]);\n // clockwise (inner ring) for higher z tile\n context.moveTo(clip[6], clip[7]);\n context.lineTo(clip[4], clip[5]);\n context.lineTo(clip[2], clip[3]);\n context.lineTo(clip[0], clip[1]);\n context.clip();\n }\n }\n }\n clips.push(currentClip);\n clipZs.push(currentZ);\n } else {\n context.clearRect(x, y, w, h);\n }\n }\n this.drawTileImage(\n tile,\n frameState,\n x,\n y,\n w,\n h,\n tileGutter,\n transition\n );\n if (clips && !inTransition) {\n if (contextSaved) {\n context.restore();\n }\n this.renderedTiles.unshift(tile);\n } else {\n this.renderedTiles.push(tile);\n }\n this.updateUsedTiles(frameState.usedTiles, tileSource, tile);\n }\n }\n\n this.renderedRevision = sourceRevision;\n this.renderedResolution = tileResolution;\n this.extentChanged =\n !this.renderedExtent_ || !equals(this.renderedExtent_, canvasExtent);\n this.renderedExtent_ = canvasExtent;\n this.renderedPixelRatio = pixelRatio;\n this.renderedProjection = projection;\n\n this.manageTilePyramid(\n frameState,\n tileSource,\n tileGrid,\n pixelRatio,\n projection,\n extent,\n z,\n tileLayer.getPreload()\n );\n this.scheduleExpireCache(frameState, tileSource);\n\n this.postRender(context, frameState);\n\n if (layerState.extent) {\n context.restore();\n }\n context.imageSmoothingEnabled = true;\n\n if (canvasTransform !== canvas.style.transform) {\n canvas.style.transform = canvasTransform;\n }\n\n return this.container;\n }\n\n /**\n * @param {import(\"../../ImageTile.js\").default} tile Tile.\n * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n * @param {number} x Left of the tile.\n * @param {number} y Top of the tile.\n * @param {number} w Width of the tile.\n * @param {number} h Height of the tile.\n * @param {number} gutter Tile gutter.\n * @param {boolean} transition Apply an alpha transition.\n */\n drawTileImage(tile, frameState, x, y, w, h, gutter, transition) {\n const image = this.getTileImage(tile);\n if (!image) {\n return;\n }\n const uid = getUid(this);\n const layerState = frameState.layerStatesArray[frameState.layerIndex];\n const alpha =\n layerState.opacity *\n (transition ? tile.getAlpha(uid, frameState.time) : 1);\n const alphaChanged = alpha !== this.context.globalAlpha;\n if (alphaChanged) {\n this.context.save();\n this.context.globalAlpha = alpha;\n }\n this.context.drawImage(\n image,\n gutter,\n gutter,\n image.width - 2 * gutter,\n image.height - 2 * gutter,\n x,\n y,\n w,\n h\n );\n\n if (alphaChanged) {\n this.context.restore();\n }\n if (alpha !== layerState.opacity) {\n frameState.animate = true;\n } else if (transition) {\n tile.endTransition(uid);\n }\n }\n\n /**\n * @return {HTMLCanvasElement} Image\n */\n getImage() {\n const context = this.context;\n return context ? context.canvas : null;\n }\n\n /**\n * Get the image from a tile.\n * @param {import(\"../../ImageTile.js\").default} tile Tile.\n * @return {HTMLCanvasElement|HTMLImageElement|HTMLVideoElement} Image.\n * @protected\n */\n getTileImage(tile) {\n return tile.getImage();\n }\n\n /**\n * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n * @param {import(\"../../source/Tile.js\").default} tileSource Tile source.\n * @protected\n */\n scheduleExpireCache(frameState, tileSource) {\n if (tileSource.canExpireCache()) {\n /**\n * @param {import(\"../../source/Tile.js\").default} tileSource Tile source.\n * @param {import(\"../../Map.js\").default} map Map.\n * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n */\n const postRenderFunction = function (tileSource, map, frameState) {\n const tileSourceKey = getUid(tileSource);\n if (tileSourceKey in frameState.usedTiles) {\n tileSource.expireCache(\n frameState.viewState.projection,\n frameState.usedTiles[tileSourceKey]\n );\n }\n }.bind(null, tileSource);\n\n frameState.postRenderFunctions.push(\n /** @type {import(\"../../Map.js\").PostRenderFunction} */ (\n postRenderFunction\n )\n );\n }\n }\n\n /**\n * @param {!Object>} usedTiles Used tiles.\n * @param {import(\"../../source/Tile.js\").default} tileSource Tile source.\n * @param {import('../../Tile.js').default} tile Tile.\n * @protected\n */\n updateUsedTiles(usedTiles, tileSource, tile) {\n // FIXME should we use tilesToDrawByZ instead?\n const tileSourceKey = getUid(tileSource);\n if (!(tileSourceKey in usedTiles)) {\n usedTiles[tileSourceKey] = {};\n }\n usedTiles[tileSourceKey][tile.getKey()] = true;\n }\n\n /**\n * Manage tile pyramid.\n * This function performs a number of functions related to the tiles at the\n * current zoom and lower zoom levels:\n * - registers idle tiles in frameState.wantedTiles so that they are not\n * discarded by the tile queue\n * - enqueues missing tiles\n * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n * @param {import(\"../../source/Tile.js\").default} tileSource Tile source.\n * @param {import(\"../../tilegrid/TileGrid.js\").default} tileGrid Tile grid.\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"../../proj/Projection.js\").default} projection Projection.\n * @param {import(\"../../extent.js\").Extent} extent Extent.\n * @param {number} currentZ Current Z.\n * @param {number} preload Load low resolution tiles up to `preload` levels.\n * @param {function(import(\"../../Tile.js\").default):void} [tileCallback] Tile callback.\n * @protected\n */\n manageTilePyramid(\n frameState,\n tileSource,\n tileGrid,\n pixelRatio,\n projection,\n extent,\n currentZ,\n preload,\n tileCallback\n ) {\n const tileSourceKey = getUid(tileSource);\n if (!(tileSourceKey in frameState.wantedTiles)) {\n frameState.wantedTiles[tileSourceKey] = {};\n }\n const wantedTiles = frameState.wantedTiles[tileSourceKey];\n const tileQueue = frameState.tileQueue;\n const minZoom = tileGrid.getMinZoom();\n const rotation = frameState.viewState.rotation;\n const viewport = rotation\n ? getRotatedViewport(\n frameState.viewState.center,\n frameState.viewState.resolution,\n rotation,\n frameState.size\n )\n : undefined;\n let tileCount = 0;\n let tile, tileRange, tileResolution, x, y, z;\n for (z = minZoom; z <= currentZ; ++z) {\n tileRange = tileGrid.getTileRangeForExtentAndZ(extent, z, tileRange);\n tileResolution = tileGrid.getResolution(z);\n for (x = tileRange.minX; x <= tileRange.maxX; ++x) {\n for (y = tileRange.minY; y <= tileRange.maxY; ++y) {\n if (\n rotation &&\n !tileGrid.tileCoordIntersectsViewport([z, x, y], viewport)\n ) {\n continue;\n }\n if (currentZ - z <= preload) {\n ++tileCount;\n tile = tileSource.getTile(z, x, y, pixelRatio, projection);\n if (tile.getState() == TileState.IDLE) {\n wantedTiles[tile.getKey()] = true;\n if (!tileQueue.isKeyQueued(tile.getKey())) {\n tileQueue.enqueue([\n tile,\n tileSourceKey,\n tileGrid.getTileCoordCenter(tile.tileCoord),\n tileResolution,\n ]);\n }\n }\n if (tileCallback !== undefined) {\n tileCallback(tile);\n }\n } else {\n tileSource.useTile(z, x, y, projection);\n }\n }\n }\n }\n tileSource.updateCacheSize(tileCount, projection);\n }\n}\n\nexport default CanvasTileLayerRenderer;\n","/**\n * @module ol/layer/Tile\n */\nimport BaseTileLayer from './BaseTile.js';\nimport CanvasTileLayerRenderer from '../renderer/canvas/TileLayer.js';\n\n/**\n * @classdesc\n * For layer sources that provide pre-rendered, tiled images in grids that are\n * organized by zoom levels for specific resolutions.\n * Note that any property set in the options is set as a {@link module:ol/Object~BaseObject}\n * property on the layer object; for example, setting `title: 'My Title'` in the\n * options means that `title` is observable, and has get/set accessors.\n *\n * @template {import(\"../source/Tile.js\").default} TileSourceType\n * @extends BaseTileLayer\n * @api\n */\nclass TileLayer extends BaseTileLayer {\n /**\n * @param {import(\"./BaseTile.js\").Options} [options] Tile layer options.\n */\n constructor(options) {\n super(options);\n }\n\n createRenderer() {\n return new CanvasTileLayerRenderer(this);\n }\n}\n\nexport default TileLayer;\n","/**\n * @module ol/source/Raster\n */\nimport Disposable from '../Disposable.js';\nimport Event from '../events/Event.js';\nimport EventType from '../events/EventType.js';\nimport ImageCanvas from '../ImageCanvas.js';\nimport ImageLayer from '../layer/Image.js';\nimport ImageSource from './Image.js';\nimport Source from './Source.js';\nimport TileLayer from '../layer/Tile.js';\nimport TileQueue from '../TileQueue.js';\nimport TileSource from './Tile.js';\nimport {createCanvasContext2D} from '../dom.js';\nimport {create as createTransform} from '../transform.js';\nimport {equals, getCenter, getHeight, getWidth} from '../extent.js';\nimport {getUid} from '../util.js';\n\nlet hasImageData = true;\ntry {\n new ImageData(10, 10);\n} catch (_) {\n hasImageData = false;\n}\n\n/** @type {CanvasRenderingContext2D} */\nlet context;\n\n/**\n * @param {Uint8ClampedArray} data Image data.\n * @param {number} width Number of columns.\n * @param {number} height Number of rows.\n * @return {ImageData} Image data.\n */\nexport function newImageData(data, width, height) {\n if (hasImageData) {\n return new ImageData(data, width, height);\n }\n\n if (!context) {\n context = document.createElement('canvas').getContext('2d');\n }\n const imageData = context.createImageData(width, height);\n imageData.data.set(data);\n return imageData;\n}\n\n/**\n * @typedef {Object} MinionData\n * @property {Array} buffers Array of buffers.\n * @property {Object} meta Operation metadata.\n * @property {boolean} imageOps The operation is an image operation.\n * @property {number} width The width of the image.\n * @property {number} height The height of the image.\n */\n\n/* istanbul ignore next */\n/**\n * Create a function for running operations. This function is serialized for\n * use in a worker.\n * @param {function(Array, Object):*} operation The operation.\n * @return {function(MinionData):ArrayBuffer} A function that takes an object with\n * buffers, meta, imageOps, width, and height properties and returns an array\n * buffer.\n */\nfunction createMinion(operation) {\n let workerHasImageData = true;\n try {\n new ImageData(10, 10);\n } catch (_) {\n workerHasImageData = false;\n }\n\n function newWorkerImageData(data, width, height) {\n if (workerHasImageData) {\n return new ImageData(data, width, height);\n }\n return {data: data, width: width, height: height};\n }\n\n return function (data) {\n // bracket notation for minification support\n const buffers = data['buffers'];\n const meta = data['meta'];\n const imageOps = data['imageOps'];\n const width = data['width'];\n const height = data['height'];\n\n const numBuffers = buffers.length;\n const numBytes = buffers[0].byteLength;\n\n if (imageOps) {\n const images = new Array(numBuffers);\n for (let b = 0; b < numBuffers; ++b) {\n images[b] = newWorkerImageData(\n new Uint8ClampedArray(buffers[b]),\n width,\n height\n );\n }\n const output = operation(images, meta).data;\n return output.buffer;\n }\n\n const output = new Uint8ClampedArray(numBytes);\n const arrays = new Array(numBuffers);\n const pixels = new Array(numBuffers);\n for (let b = 0; b < numBuffers; ++b) {\n arrays[b] = new Uint8ClampedArray(buffers[b]);\n pixels[b] = [0, 0, 0, 0];\n }\n for (let i = 0; i < numBytes; i += 4) {\n for (let j = 0; j < numBuffers; ++j) {\n const array = arrays[j];\n pixels[j][0] = array[i];\n pixels[j][1] = array[i + 1];\n pixels[j][2] = array[i + 2];\n pixels[j][3] = array[i + 3];\n }\n const pixel = operation(pixels, meta);\n output[i] = pixel[0];\n output[i + 1] = pixel[1];\n output[i + 2] = pixel[2];\n output[i + 3] = pixel[3];\n }\n return output.buffer;\n };\n}\n\n/**\n * Create a worker for running operations.\n * @param {ProcessorOptions} config Processor options.\n * @param {function(MessageEvent): void} onMessage Called with a message event.\n * @return {Worker} The worker.\n */\nfunction createWorker(config, onMessage) {\n const lib = Object.keys(config.lib || {}).map(function (name) {\n return 'const ' + name + ' = ' + config.lib[name].toString() + ';';\n });\n\n const lines = lib.concat([\n 'const __minion__ = (' + createMinion.toString() + ')(',\n config.operation.toString(),\n ');',\n 'self.addEventListener(\"message\", function(event) {',\n ' const buffer = __minion__(event.data);',\n ' self.postMessage({buffer: buffer, meta: event.data.meta}, [buffer]);',\n '});',\n ]);\n\n const worker = new Worker(\n typeof Blob === 'undefined'\n ? 'data:text/javascript;base64,' +\n Buffer.from(lines.join('\\n'), 'binary').toString('base64')\n : URL.createObjectURL(new Blob(lines, {type: 'text/javascript'}))\n );\n worker.addEventListener('message', onMessage);\n return worker;\n}\n\n/**\n * @typedef {Object} FauxMessageEvent\n * @property {Object} data Message data.\n */\n\n/**\n * Create a faux worker for running operations.\n * @param {ProcessorOptions} config Configuration.\n * @param {function(FauxMessageEvent): void} onMessage Called with a message event.\n * @return {Object} The faux worker.\n */\nfunction createFauxWorker(config, onMessage) {\n const minion = createMinion(config.operation);\n let terminated = false;\n return {\n postMessage: function (data) {\n setTimeout(function () {\n if (terminated) {\n return;\n }\n onMessage({data: {buffer: minion(data), meta: data['meta']}});\n }, 0);\n },\n terminate: function () {\n terminated = true;\n },\n };\n}\n\n/**\n * @typedef {function(Error, ImageData, (Object|Array)): void} JobCallback\n */\n\n/**\n * @typedef {Object} Job\n * @property {Object} meta Job metadata.\n * @property {Array} inputs Array of input data.\n * @property {JobCallback} callback Called when the job is complete.\n */\n\n/**\n * @typedef {Object} ProcessorOptions\n * @property {number} threads Number of workers to spawn.\n * @property {Operation} operation The operation.\n * @property {Object} [lib] Functions that will be made available to operations run in a worker.\n * @property {number} queue The number of queued jobs to allow.\n * @property {boolean} [imageOps=false] Pass all the image data to the operation instead of a single pixel.\n */\n\n/**\n * @classdesc\n * A processor runs pixel or image operations in workers.\n */\nexport class Processor extends Disposable {\n /**\n * @param {ProcessorOptions} config Configuration.\n */\n constructor(config) {\n super();\n\n this._imageOps = !!config.imageOps;\n let threads;\n if (config.threads === 0) {\n threads = 0;\n } else if (this._imageOps) {\n threads = 1;\n } else {\n threads = config.threads || 1;\n }\n\n /**\n * @type {Array}\n */\n const workers = new Array(threads);\n if (threads) {\n for (let i = 0; i < threads; ++i) {\n workers[i] = createWorker(config, this._onWorkerMessage.bind(this, i));\n }\n } else {\n workers[0] = createFauxWorker(\n config,\n this._onWorkerMessage.bind(this, 0)\n );\n }\n this._workers = workers;\n\n /**\n * @type {Array}\n * @private\n */\n this._queue = [];\n\n this._maxQueueLength = config.queue || Infinity;\n this._running = 0;\n\n /**\n * @type {Object}\n * @private\n */\n this._dataLookup = {};\n\n /**\n * @type {Job}\n * @private\n */\n this._job = null;\n }\n\n /**\n * Run operation on input data.\n * @param {Array} inputs Array of image data.\n * @param {Object} meta A user data object. This is passed to all operations\n * and must be serializable.\n * @param {function(Error, ImageData, Object): void} callback Called when work\n * completes. The first argument is any error. The second is the ImageData\n * generated by operations. The third is the user data object.\n */\n process(inputs, meta, callback) {\n this._enqueue({\n inputs: inputs,\n meta: meta,\n callback: callback,\n });\n this._dispatch();\n }\n\n /**\n * Add a job to the queue.\n * @param {Job} job The job.\n */\n _enqueue(job) {\n this._queue.push(job);\n while (this._queue.length > this._maxQueueLength) {\n this._queue.shift().callback(null, null);\n }\n }\n\n /**\n * Dispatch a job.\n */\n _dispatch() {\n if (this._running || this._queue.length === 0) {\n return;\n }\n\n const job = this._queue.shift();\n this._job = job;\n const width = job.inputs[0].width;\n const height = job.inputs[0].height;\n const buffers = job.inputs.map(function (input) {\n return input.data.buffer;\n });\n const threads = this._workers.length;\n this._running = threads;\n if (threads === 1) {\n this._workers[0].postMessage(\n {\n buffers: buffers,\n meta: job.meta,\n imageOps: this._imageOps,\n width: width,\n height: height,\n },\n buffers\n );\n return;\n }\n\n const length = job.inputs[0].data.length;\n const segmentLength = 4 * Math.ceil(length / 4 / threads);\n for (let i = 0; i < threads; ++i) {\n const offset = i * segmentLength;\n const slices = [];\n for (let j = 0, jj = buffers.length; j < jj; ++j) {\n slices.push(buffers[j].slice(offset, offset + segmentLength));\n }\n this._workers[i].postMessage(\n {\n buffers: slices,\n meta: job.meta,\n imageOps: this._imageOps,\n width: width,\n height: height,\n },\n slices\n );\n }\n }\n\n /**\n * Handle messages from the worker.\n * @param {number} index The worker index.\n * @param {MessageEvent} event The message event.\n */\n _onWorkerMessage(index, event) {\n if (this.disposed) {\n return;\n }\n this._dataLookup[index] = event.data;\n --this._running;\n if (this._running === 0) {\n this._resolveJob();\n }\n }\n\n /**\n * Resolve a job. If there are no more worker threads, the processor callback\n * will be called.\n */\n _resolveJob() {\n const job = this._job;\n const threads = this._workers.length;\n let data, meta;\n if (threads === 1) {\n data = new Uint8ClampedArray(this._dataLookup[0]['buffer']);\n meta = this._dataLookup[0]['meta'];\n } else {\n const length = job.inputs[0].data.length;\n data = new Uint8ClampedArray(length);\n meta = new Array(threads);\n const segmentLength = 4 * Math.ceil(length / 4 / threads);\n for (let i = 0; i < threads; ++i) {\n const buffer = this._dataLookup[i]['buffer'];\n const offset = i * segmentLength;\n data.set(new Uint8ClampedArray(buffer), offset);\n meta[i] = this._dataLookup[i]['meta'];\n }\n }\n this._job = null;\n this._dataLookup = {};\n job.callback(\n null,\n newImageData(data, job.inputs[0].width, job.inputs[0].height),\n meta\n );\n this._dispatch();\n }\n\n /**\n * Terminate all workers associated with the processor.\n */\n disposeInternal() {\n for (let i = 0; i < this._workers.length; ++i) {\n this._workers[i].terminate();\n }\n this._workers.length = 0;\n }\n}\n\n/**\n * A function that takes an array of input data, performs some operation, and\n * returns an array of output data.\n * For `pixel` type operations, the function will be called with an array of\n * pixels, where each pixel is an array of four numbers (`[r, g, b, a]`) in the\n * range of 0 - 255. It should return a single pixel array.\n * For `'image'` type operations, functions will be called with an array of\n * [ImageData](https://developer.mozilla.org/en-US/docs/Web/API/ImageData)\n * and should return a single\n * [ImageData](https://developer.mozilla.org/en-US/docs/Web/API/ImageData).\n * The operations\n * are called with a second \"data\" argument, which can be used for storage. The\n * data object is accessible from raster events, where it can be initialized in\n * \"beforeoperations\" and accessed again in \"afteroperations\".\n *\n * @typedef {function((Array>|Array), Object):\n * (Array|ImageData)} Operation\n */\n\n/**\n * @enum {string}\n */\nconst RasterEventType = {\n /**\n * Triggered before operations are run. Listeners will receive an event object with\n * a `data` property that can be used to make data available to operations.\n * @event module:ol/source/Raster.RasterSourceEvent#beforeoperations\n * @api\n */\n BEFOREOPERATIONS: 'beforeoperations',\n\n /**\n * Triggered after operations are run. Listeners will receive an event object with\n * a `data` property. If more than one thread is used, `data` will be an array of\n * objects. If a single thread is used, `data` will be a single object.\n * @event module:ol/source/Raster.RasterSourceEvent#afteroperations\n * @api\n */\n AFTEROPERATIONS: 'afteroperations',\n};\n\n/**\n * @typedef {'pixel' | 'image'} RasterOperationType\n * Raster operation type. Supported values are `'pixel'` and `'image'`.\n */\n\n/**\n * @typedef {import(\"./Image.js\").ImageSourceEventTypes|'beforeoperations'|'afteroperations'} RasterSourceEventTypes\n */\n\n/**\n * @classdesc\n * Events emitted by {@link module:ol/source/Raster~RasterSource} instances are instances of this\n * type.\n */\nexport class RasterSourceEvent extends Event {\n /**\n * @param {string} type Type.\n * @param {import(\"../Map.js\").FrameState} frameState The frame state.\n * @param {Object|Array} data An object made available to operations. For \"afteroperations\" evenets\n * this will be an array of objects if more than one thread is used.\n */\n constructor(type, frameState, data) {\n super(type);\n\n /**\n * The raster extent.\n * @type {import(\"../extent.js\").Extent}\n * @api\n */\n this.extent = frameState.extent;\n\n /**\n * The pixel resolution (map units per pixel).\n * @type {number}\n * @api\n */\n this.resolution = frameState.viewState.resolution / frameState.pixelRatio;\n\n /**\n * An object made available to all operations. This can be used by operations\n * as a storage object (e.g. for calculating statistics).\n * @type {Object}\n * @api\n */\n this.data = data;\n }\n}\n\n/**\n * @typedef {Object} Options\n * @property {Array} sources Input\n * sources or layers. For vector data, use an VectorImage layer.\n * @property {Operation} [operation] Raster operation.\n * The operation will be called with data from input sources\n * and the output will be assigned to the raster source.\n * @property {Object} [lib] Functions that will be made available to operations run in a worker.\n * @property {number} [threads] By default, operations will be run in a single worker thread.\n * To avoid using workers altogether, set `threads: 0`. For pixel operations, operations can\n * be run in multiple worker threads. Note that there is additional overhead in\n * transferring data to multiple workers, and that depending on the user's\n * system, it may not be possible to parallelize the work.\n * @property {RasterOperationType} [operationType='pixel'] Operation type.\n * Supported values are `'pixel'` and `'image'`. By default,\n * `'pixel'` operations are assumed, and operations will be called with an\n * array of pixels from input sources. If set to `'image'`, operations will\n * be called with an array of ImageData objects from input sources.\n * @property {Array|null} [resolutions] Resolutions. If specified, raster operations will only\n * be run at the given resolutions. By default, the resolutions of the first source with resolutions\n * specified will be used, if any. Set to `null` to use any view resolution instead.\n */\n\n/***\n * @template Return\n * @typedef {import(\"../Observable\").OnSignature &\n * import(\"../Observable\").OnSignature &\n * import(\"../Observable\").OnSignature &\n * import(\"../Observable\").OnSignature &\n * import(\"../Observable\").CombinedOnSignature} RasterSourceOnSignature\n */\n\n/**\n * @classdesc\n * A source that transforms data from any number of input sources using an\n * {@link module:ol/source/Raster~Operation} function to transform input pixel values into\n * output pixel values.\n *\n * @fires module:ol/source/Raster.RasterSourceEvent\n * @api\n */\nclass RasterSource extends ImageSource {\n /**\n * @param {Options} options Options.\n */\n constructor(options) {\n super({\n projection: null,\n });\n\n /***\n * @type {RasterSourceOnSignature}\n */\n this.on;\n\n /***\n * @type {RasterSourceOnSignature}\n */\n this.once;\n\n /***\n * @type {RasterSourceOnSignature}\n */\n this.un;\n\n /**\n * @private\n * @type {Processor}\n */\n this.processor_ = null;\n\n /**\n * @private\n * @type {RasterOperationType}\n */\n this.operationType_ =\n options.operationType !== undefined ? options.operationType : 'pixel';\n\n /**\n * @private\n * @type {number}\n */\n this.threads_ = options.threads !== undefined ? options.threads : 1;\n\n /**\n * @private\n * @type {Array}\n */\n this.layers_ = createLayers(options.sources);\n\n const changed = this.changed.bind(this);\n for (let i = 0, ii = this.layers_.length; i < ii; ++i) {\n this.layers_[i].addEventListener(EventType.CHANGE, changed);\n }\n\n /** @type {boolean} */\n this.useResolutions_ = options.resolutions !== null;\n\n /**\n * @private\n * @type {import(\"../TileQueue.js\").default}\n */\n this.tileQueue_ = new TileQueue(function () {\n return 1;\n }, this.processSources_.bind(this));\n\n /**\n * The most recently requested frame state.\n * @type {import(\"../Map.js\").FrameState}\n * @private\n */\n this.requestedFrameState_;\n\n /**\n * The most recently rendered image canvas.\n * @type {import(\"../ImageCanvas.js\").default}\n * @private\n */\n this.renderedImageCanvas_ = null;\n\n /**\n * The most recently rendered revision.\n * @type {number}\n */\n this.renderedRevision_;\n\n /**\n * @private\n * @type {import(\"../Map.js\").FrameState}\n */\n this.frameState_ = {\n animate: false,\n coordinateToPixelTransform: createTransform(),\n declutterTree: null,\n extent: null,\n index: 0,\n layerIndex: 0,\n layerStatesArray: getLayerStatesArray(this.layers_),\n pixelRatio: 1,\n pixelToCoordinateTransform: createTransform(),\n postRenderFunctions: [],\n size: [0, 0],\n tileQueue: this.tileQueue_,\n time: Date.now(),\n usedTiles: {},\n viewState: /** @type {import(\"../View.js\").State} */ ({\n rotation: 0,\n }),\n viewHints: [],\n wantedTiles: {},\n mapId: getUid(this),\n renderTargets: {},\n };\n\n this.setAttributions(function (frameState) {\n const attributions = [];\n for (\n let index = 0, iMax = options.sources.length;\n index < iMax;\n ++index\n ) {\n const sourceOrLayer = options.sources[index];\n const source =\n sourceOrLayer instanceof Source\n ? sourceOrLayer\n : sourceOrLayer.getSource();\n if (!source) {\n continue;\n }\n const attributionGetter = source.getAttributions();\n if (typeof attributionGetter === 'function') {\n const sourceAttribution = attributionGetter(frameState);\n attributions.push.apply(attributions, sourceAttribution);\n }\n }\n return attributions.length !== 0 ? attributions : null;\n });\n\n if (options.operation !== undefined) {\n this.setOperation(options.operation, options.lib);\n }\n }\n\n /**\n * Set the operation.\n * @param {Operation} operation New operation.\n * @param {Object} [lib] Functions that will be available to operations run\n * in a worker.\n * @api\n */\n setOperation(operation, lib) {\n if (this.processor_) {\n this.processor_.dispose();\n }\n\n this.processor_ = new Processor({\n operation: operation,\n imageOps: this.operationType_ === 'image',\n queue: 1,\n lib: lib,\n threads: this.threads_,\n });\n this.changed();\n }\n\n /**\n * Update the stored frame state.\n * @param {import(\"../extent.js\").Extent} extent The view extent (in map units).\n * @param {number} resolution The view resolution.\n * @param {import(\"../proj/Projection.js\").default} projection The view projection.\n * @return {import(\"../Map.js\").FrameState} The updated frame state.\n * @private\n */\n updateFrameState_(extent, resolution, projection) {\n const frameState = /** @type {import(\"../Map.js\").FrameState} */ (\n Object.assign({}, this.frameState_)\n );\n\n frameState.viewState = /** @type {import(\"../View.js\").State} */ (\n Object.assign({}, frameState.viewState)\n );\n\n const center = getCenter(extent);\n\n frameState.size[0] = Math.ceil(getWidth(extent) / resolution);\n frameState.size[1] = Math.ceil(getHeight(extent) / resolution);\n frameState.extent = [\n center[0] - (frameState.size[0] * resolution) / 2,\n center[1] - (frameState.size[1] * resolution) / 2,\n center[0] + (frameState.size[0] * resolution) / 2,\n center[1] + (frameState.size[1] * resolution) / 2,\n ];\n frameState.time = Date.now();\n\n const viewState = frameState.viewState;\n viewState.center = center;\n viewState.projection = projection;\n viewState.resolution = resolution;\n return frameState;\n }\n\n /**\n * Determine if all sources are ready.\n * @return {boolean} All sources are ready.\n * @private\n */\n allSourcesReady_() {\n let ready = true;\n let source;\n for (let i = 0, ii = this.layers_.length; i < ii; ++i) {\n source = this.layers_[i].getSource();\n if (!source || source.getState() !== 'ready') {\n ready = false;\n break;\n }\n }\n return ready;\n }\n\n /**\n * @param {import(\"../extent.js\").Extent} extent Extent.\n * @param {number} resolution Resolution.\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {import(\"../ImageCanvas.js\").default} Single image.\n */\n getImage(extent, resolution, pixelRatio, projection) {\n if (!this.allSourcesReady_()) {\n return null;\n }\n\n this.tileQueue_.loadMoreTiles(16, 16);\n\n resolution = this.findNearestResolution(resolution);\n const frameState = this.updateFrameState_(extent, resolution, projection);\n this.requestedFrameState_ = frameState;\n\n // check if we can't reuse the existing ol/ImageCanvas\n if (this.renderedImageCanvas_) {\n const renderedResolution = this.renderedImageCanvas_.getResolution();\n const renderedExtent = this.renderedImageCanvas_.getExtent();\n if (\n resolution !== renderedResolution ||\n !equals(frameState.extent, renderedExtent)\n ) {\n this.renderedImageCanvas_ = null;\n }\n }\n\n if (\n !this.renderedImageCanvas_ ||\n this.getRevision() !== this.renderedRevision_\n ) {\n this.processSources_();\n }\n\n if (frameState.animate) {\n requestAnimationFrame(this.changed.bind(this));\n }\n\n return this.renderedImageCanvas_;\n }\n\n /**\n * Start processing source data.\n * @private\n */\n processSources_() {\n const frameState = this.requestedFrameState_;\n const len = this.layers_.length;\n const imageDatas = new Array(len);\n for (let i = 0; i < len; ++i) {\n frameState.layerIndex = i;\n frameState.renderTargets = {};\n const imageData = getImageData(this.layers_[i], frameState);\n if (imageData) {\n imageDatas[i] = imageData;\n } else {\n return;\n }\n }\n\n const data = {};\n this.dispatchEvent(\n new RasterSourceEvent(RasterEventType.BEFOREOPERATIONS, frameState, data)\n );\n this.processor_.process(\n imageDatas,\n data,\n this.onWorkerComplete_.bind(this, frameState)\n );\n }\n\n /**\n * Called when pixel processing is complete.\n * @param {import(\"../Map.js\").FrameState} frameState The frame state.\n * @param {Error} err Any error during processing.\n * @param {ImageData} output The output image data.\n * @param {Object|Array} data The user data (or an array if more than one thread).\n * @private\n */\n onWorkerComplete_(frameState, err, output, data) {\n if (err || !output) {\n return;\n }\n\n // do nothing if extent or resolution changed\n const extent = frameState.extent;\n const resolution = frameState.viewState.resolution;\n if (\n resolution !== this.requestedFrameState_.viewState.resolution ||\n !equals(extent, this.requestedFrameState_.extent)\n ) {\n return;\n }\n\n let context;\n if (this.renderedImageCanvas_) {\n context = this.renderedImageCanvas_.getImage().getContext('2d');\n } else {\n const width = Math.round(getWidth(extent) / resolution);\n const height = Math.round(getHeight(extent) / resolution);\n context = createCanvasContext2D(width, height);\n this.renderedImageCanvas_ = new ImageCanvas(\n extent,\n resolution,\n 1,\n context.canvas\n );\n }\n context.putImageData(output, 0, 0);\n\n if (frameState.animate) {\n requestAnimationFrame(this.changed.bind(this));\n } else {\n this.changed();\n }\n this.renderedRevision_ = this.getRevision();\n\n this.dispatchEvent(\n new RasterSourceEvent(RasterEventType.AFTEROPERATIONS, frameState, data)\n );\n }\n\n /**\n * @param {import(\"../proj/Projection\").default} [projection] Projection.\n * @return {Array|null} Resolutions.\n */\n getResolutions(projection) {\n if (!this.useResolutions_) {\n return null;\n }\n let resolutions = super.getResolutions();\n if (!resolutions) {\n for (let i = 0, ii = this.layers_.length; i < ii; ++i) {\n const source = this.layers_[i].getSource();\n resolutions = source.getResolutions(projection);\n if (resolutions) {\n break;\n }\n }\n }\n return resolutions;\n }\n\n disposeInternal() {\n if (this.processor_) {\n this.processor_.dispose();\n }\n super.disposeInternal();\n }\n}\n\n/**\n * Clean up and unregister the worker.\n * @function\n * @api\n */\nRasterSource.prototype.dispose;\n\n/**\n * A reusable canvas context.\n * @type {CanvasRenderingContext2D}\n * @private\n */\nlet sharedContext = null;\n\n/**\n * Get image data from a layer.\n * @param {import(\"../layer/Layer.js\").default} layer Layer to render.\n * @param {import(\"../Map.js\").FrameState} frameState The frame state.\n * @return {ImageData} The image data.\n */\nfunction getImageData(layer, frameState) {\n const renderer = layer.getRenderer();\n if (!renderer) {\n throw new Error('Unsupported layer type: ' + layer);\n }\n\n if (!renderer.prepareFrame(frameState)) {\n return null;\n }\n const width = frameState.size[0];\n const height = frameState.size[1];\n if (width === 0 || height === 0) {\n return null;\n }\n const container = renderer.renderFrame(frameState, null);\n let element;\n if (container instanceof HTMLCanvasElement) {\n element = container;\n } else {\n if (container) {\n element = container.firstElementChild;\n }\n if (!(element instanceof HTMLCanvasElement)) {\n throw new Error('Unsupported rendered element: ' + element);\n }\n if (element.width === width && element.height === height) {\n const context = element.getContext('2d');\n return context.getImageData(0, 0, width, height);\n }\n }\n\n if (!sharedContext) {\n sharedContext = createCanvasContext2D(width, height, undefined, {\n willReadFrequently: true,\n });\n } else {\n const canvas = sharedContext.canvas;\n if (canvas.width !== width || canvas.height !== height) {\n sharedContext = createCanvasContext2D(width, height, undefined, {\n willReadFrequently: true,\n });\n } else {\n sharedContext.clearRect(0, 0, width, height);\n }\n }\n sharedContext.drawImage(element, 0, 0, width, height);\n return sharedContext.getImageData(0, 0, width, height);\n}\n\n/**\n * Get a list of layer states from a list of layers.\n * @param {Array} layers Layers.\n * @return {Array} The layer states.\n */\nfunction getLayerStatesArray(layers) {\n return layers.map(function (layer) {\n return layer.getLayerState();\n });\n}\n\n/**\n * Create layers for all sources.\n * @param {Array} sources The sources.\n * @return {Array} Array of layers.\n */\nfunction createLayers(sources) {\n const len = sources.length;\n const layers = new Array(len);\n for (let i = 0; i < len; ++i) {\n layers[i] = createLayer(sources[i]);\n }\n return layers;\n}\n\n/**\n * Create a layer for the provided source.\n * @param {import(\"./Source.js\").default|import(\"../layer/Layer.js\").default} layerOrSource The layer or source.\n * @return {import(\"../layer/Layer.js\").default} The layer.\n */\nfunction createLayer(layerOrSource) {\n // @type {import(\"../layer/Layer.js\").default}\n let layer;\n if (layerOrSource instanceof Source) {\n if (layerOrSource instanceof TileSource) {\n layer = new TileLayer({source: layerOrSource});\n } else if (layerOrSource instanceof ImageSource) {\n layer = new ImageLayer({source: layerOrSource});\n }\n } else {\n layer = layerOrSource;\n }\n return layer;\n}\n\nexport default RasterSource;\n","/**\n * @module ol/source/Stamen\n */\n\nimport XYZ from './XYZ.js';\nimport {ATTRIBUTION as OSM_ATTRIBUTION} from './OSM.js';\n\n/**\n * @const\n * @type {Array}\n */\nconst ATTRIBUTIONS = [\n 'Map tiles by Stamen Design, ' +\n 'under CC BY' +\n ' 3.0.',\n OSM_ATTRIBUTION,\n];\n\n/**\n * @type {Object}\n */\nconst LayerConfig = {\n 'terrain': {\n extension: 'png',\n opaque: true,\n },\n 'terrain-background': {\n extension: 'png',\n opaque: true,\n },\n 'terrain-labels': {\n extension: 'png',\n opaque: false,\n },\n 'terrain-lines': {\n extension: 'png',\n opaque: false,\n },\n 'toner-background': {\n extension: 'png',\n opaque: true,\n },\n 'toner': {\n extension: 'png',\n opaque: true,\n },\n 'toner-hybrid': {\n extension: 'png',\n opaque: false,\n },\n 'toner-labels': {\n extension: 'png',\n opaque: false,\n },\n 'toner-lines': {\n extension: 'png',\n opaque: false,\n },\n 'toner-lite': {\n extension: 'png',\n opaque: true,\n },\n 'watercolor': {\n extension: 'jpg',\n opaque: true,\n },\n};\n\n/**\n * @type {Object}\n */\nconst ProviderConfig = {\n 'terrain': {\n minZoom: 0,\n maxZoom: 18,\n },\n 'toner': {\n minZoom: 0,\n maxZoom: 20,\n },\n 'watercolor': {\n minZoom: 0,\n maxZoom: 18,\n },\n};\n\n/**\n * @typedef {Object} Options\n * @property {number} [cacheSize] Initial tile cache size. Will auto-grow to hold at least the number of tiles in the viewport.\n * @property {boolean} [interpolate=true] Use interpolated values when resampling. By default,\n * linear interpolation is used when resampling. Set to false to use the nearest neighbor instead.\n * @property {string} layer Layer name.\n * @property {number} [minZoom] Minimum zoom.\n * @property {number} [maxZoom] Maximum zoom.\n * @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).\n * Higher values can increase reprojection performance, but decrease precision.\n * @property {import(\"../Tile.js\").LoadFunction} [tileLoadFunction]\n * Optional function to load a tile given a URL. The default is\n * ```js\n * function(imageTile, src) {\n * imageTile.getImage().src = src;\n * };\n * ```\n * @property {number} [transition=250] Duration of the opacity transition for rendering.\n * To disable the opacity transition, pass `transition: 0`.\n * @property {string} [url] URL template. Must include `{x}`, `{y}` or `{-y}`, and `{z}` placeholders.\n * @property {boolean} [wrapX=true] Whether to wrap the world horizontally.\n * @property {number|import(\"../array.js\").NearestDirectionFunction} [zDirection=0]\n * Choose whether to use tiles with a higher or lower zoom level when between integer\n * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.\n */\n\n/**\n * @classdesc\n * Layer source for the Stamen tile server.\n * @api\n */\nclass Stamen extends XYZ {\n /**\n * @param {Options} options Stamen options.\n */\n constructor(options) {\n const i = options.layer.indexOf('-');\n const provider = i == -1 ? options.layer : options.layer.slice(0, i);\n const providerConfig = ProviderConfig[provider];\n\n const layerConfig = LayerConfig[options.layer];\n\n const url =\n options.url !== undefined\n ? options.url\n : 'https://stamen-tiles-{a-d}.a.ssl.fastly.net/' +\n options.layer +\n '/{z}/{x}/{y}.' +\n layerConfig.extension;\n\n super({\n attributions: ATTRIBUTIONS,\n cacheSize: options.cacheSize,\n crossOrigin: 'anonymous',\n interpolate: options.interpolate,\n maxZoom:\n options.maxZoom != undefined ? options.maxZoom : providerConfig.maxZoom,\n minZoom:\n options.minZoom != undefined ? options.minZoom : providerConfig.minZoom,\n opaque: layerConfig.opaque,\n reprojectionErrorThreshold: options.reprojectionErrorThreshold,\n tileLoadFunction: options.tileLoadFunction,\n transition: options.transition,\n url: url,\n wrapX: options.wrapX,\n zDirection: options.zDirection,\n });\n }\n}\n\nexport default Stamen;\n","/**\n * @module ol/source/TileArcGISRest\n */\n\nimport TileImage from './TileImage.js';\nimport {appendParams} from '../uri.js';\nimport {createEmpty} from '../extent.js';\nimport {modulo} from '../math.js';\nimport {scale as scaleSize, toSize} from '../size.js';\nimport {hash as tileCoordHash} from '../tilecoord.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {number} [cacheSize] Initial tile cache size. Will auto-grow to hold at least the number of tiles in the viewport.\n * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images. Note that\n * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.\n * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.\n * @property {boolean} [interpolate=true] Use interpolated values when resampling. By default,\n * linear interpolation is used when resampling. Set to false to use the nearest neighbor instead.\n * @property {Object} [params] ArcGIS Rest parameters. This field is optional. Service defaults will be\n * used for any fields not specified. `FORMAT` is `PNG32` by default. `F` is `IMAGE` by\n * default. `TRANSPARENT` is `true` by default. `BBOX`, `SIZE`, `BBOXSR`,\n * and `IMAGESR` will be set dynamically. Set `LAYERS` to\n * override the default service layer visibility. See\n * https://developers.arcgis.com/rest/services-reference/export-map.htm\n * for further reference.\n * @property {boolean} [hidpi=true] Use the `ol/Map#pixelRatio` value when requesting\n * the image from the remote server.\n * @property {import(\"../tilegrid/TileGrid.js\").default} [tileGrid] Tile grid. Base this on the resolutions,\n * tilesize and extent supported by the server.\n * If this is not defined, a default grid will be used: if there is a projection\n * extent, the grid will be based on that; if not, a grid based on a global\n * extent with origin at 0,0 will be used.\n * @property {import(\"../proj.js\").ProjectionLike} [projection] Projection. Default is the view projection.\n * The projection code must contain a numeric end portion separated by :\n * or the entire code must form a valid ArcGIS SpatialReference definition.\n * @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).\n * Higher values can increase reprojection performance, but decrease precision.\n * @property {import(\"../Tile.js\").LoadFunction} [tileLoadFunction] Optional function to load a tile given a URL.\n * The default is\n * ```js\n * function(imageTile, src) {\n * imageTile.getImage().src = src;\n * };\n * ```\n * @property {string} [url] ArcGIS Rest service URL for a Map Service or Image Service. The\n * url should include /MapServer or /ImageServer.\n * @property {boolean} [wrapX=true] Whether to wrap the world horizontally.\n * @property {number} [transition] Duration of the opacity transition for rendering. To disable the opacity\n * transition, pass `transition: 0`.\n * @property {Array} [urls] ArcGIS Rest service urls. Use this instead of `url` when the ArcGIS\n * Service supports multiple urls for export requests.\n * @property {number|import(\"../array.js\").NearestDirectionFunction} [zDirection=0]\n * Choose whether to use tiles with a higher or lower zoom level when between integer\n * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.\n */\n\n/**\n * @classdesc\n * Layer source for tile data from ArcGIS Rest services. Map and Image\n * Services are supported.\n *\n * For cached ArcGIS services, better performance is available using the\n * {@link module:ol/source/XYZ~XYZ} data source.\n * @api\n */\nclass TileArcGISRest extends TileImage {\n /**\n * @param {Options} [options] Tile ArcGIS Rest options.\n */\n constructor(options) {\n options = options ? options : {};\n\n super({\n attributions: options.attributions,\n cacheSize: options.cacheSize,\n crossOrigin: options.crossOrigin,\n interpolate: options.interpolate,\n projection: options.projection,\n reprojectionErrorThreshold: options.reprojectionErrorThreshold,\n tileGrid: options.tileGrid,\n tileLoadFunction: options.tileLoadFunction,\n url: options.url,\n urls: options.urls,\n wrapX: options.wrapX !== undefined ? options.wrapX : true,\n transition: options.transition,\n zDirection: options.zDirection,\n });\n\n /**\n * @private\n * @type {!Object}\n */\n this.params_ = options.params || {};\n\n /**\n * @private\n * @type {boolean}\n */\n this.hidpi_ = options.hidpi !== undefined ? options.hidpi : true;\n\n /**\n * @private\n * @type {import(\"../extent.js\").Extent}\n */\n this.tmpExtent_ = createEmpty();\n\n this.setKey(this.getKeyForParams_());\n }\n\n /**\n * @private\n * @return {string} The key for the current params.\n */\n getKeyForParams_() {\n let i = 0;\n const res = [];\n for (const key in this.params_) {\n res[i++] = key + '-' + this.params_[key];\n }\n return res.join('/');\n }\n\n /**\n * Get the user-provided params, i.e. those passed to the constructor through\n * the \"params\" option, and possibly updated using the updateParams method.\n * @return {Object} Params.\n * @api\n */\n getParams() {\n return this.params_;\n }\n\n /**\n * @param {import(\"../tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n * @param {import(\"../size.js\").Size} tileSize Tile size.\n * @param {import(\"../extent.js\").Extent} tileExtent Tile extent.\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @param {Object} params Params.\n * @return {string|undefined} Request URL.\n * @private\n */\n getRequestUrl_(\n tileCoord,\n tileSize,\n tileExtent,\n pixelRatio,\n projection,\n params\n ) {\n const urls = this.urls;\n if (!urls) {\n return undefined;\n }\n\n // ArcGIS Server only wants the numeric portion of the projection ID.\n // (if there is no numeric portion the entire projection code must\n // form a valid ArcGIS SpatialReference definition).\n const srid = projection\n .getCode()\n .split(/:(?=\\d+$)/)\n .pop();\n\n params['SIZE'] = tileSize[0] + ',' + tileSize[1];\n params['BBOX'] = tileExtent.join(',');\n params['BBOXSR'] = srid;\n params['IMAGESR'] = srid;\n params['DPI'] = Math.round(\n params['DPI'] ? params['DPI'] * pixelRatio : 90 * pixelRatio\n );\n\n let url;\n if (urls.length == 1) {\n url = urls[0];\n } else {\n const index = modulo(tileCoordHash(tileCoord), urls.length);\n url = urls[index];\n }\n\n const modifiedUrl = url\n .replace(/MapServer\\/?$/, 'MapServer/export')\n .replace(/ImageServer\\/?$/, 'ImageServer/exportImage');\n return appendParams(modifiedUrl, params);\n }\n\n /**\n * Get the tile pixel ratio for this source.\n * @param {number} pixelRatio Pixel ratio.\n * @return {number} Tile pixel ratio.\n */\n getTilePixelRatio(pixelRatio) {\n return this.hidpi_ ? pixelRatio : 1;\n }\n\n /**\n * Update the user-provided params.\n * @param {Object} params Params.\n * @api\n */\n updateParams(params) {\n Object.assign(this.params_, params);\n this.setKey(this.getKeyForParams_());\n }\n\n /**\n * @param {import(\"../tilecoord.js\").TileCoord} tileCoord The tile coordinate\n * @param {number} pixelRatio The pixel ratio\n * @param {import(\"../proj/Projection.js\").default} projection The projection\n * @return {string|undefined} The tile URL\n * @override\n */\n tileUrlFunction(tileCoord, pixelRatio, projection) {\n let tileGrid = this.getTileGrid();\n if (!tileGrid) {\n tileGrid = this.getTileGridForProjection(projection);\n }\n\n if (tileGrid.getResolutions().length <= tileCoord[0]) {\n return undefined;\n }\n\n if (pixelRatio != 1 && !this.hidpi_) {\n pixelRatio = 1;\n }\n\n const tileExtent = tileGrid.getTileCoordExtent(tileCoord, this.tmpExtent_);\n let tileSize = toSize(tileGrid.getTileSize(tileCoord[0]), this.tmpSize);\n\n if (pixelRatio != 1) {\n tileSize = scaleSize(tileSize, pixelRatio, this.tmpSize);\n }\n\n // Apply default params and override with user specified values.\n const baseParams = {\n 'F': 'image',\n 'FORMAT': 'PNG32',\n 'TRANSPARENT': true,\n };\n Object.assign(baseParams, this.params_);\n\n return this.getRequestUrl_(\n tileCoord,\n tileSize,\n tileExtent,\n pixelRatio,\n projection,\n baseParams\n );\n }\n}\n\nexport default TileArcGISRest;\n","/**\n * @module ol/source/TileDebug\n */\n\nimport XYZ from './XYZ.js';\nimport {createCanvasContext2D} from '../dom.js';\nimport {toSize} from '../size.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"../proj.js\").ProjectionLike} [projection='EPSG:3857'] Optional projection.\n * @property {import(\"../tilegrid/TileGrid.js\").default} [tileGrid] Tile grid.\n * @property {boolean} [wrapX=true] Whether to wrap the world horizontally.\n * @property {number|import(\"../array.js\").NearestDirectionFunction} [zDirection=0]\n * Set to `1` when debugging `VectorTile` sources with a default configuration.\n * Choose whether to use tiles with a higher or lower zoom level when between integer\n * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.\n * @property {string} [template='z:{z} x:{x} y:{y}'] Template for labeling the tiles.\n * Should include `{x}`, `{y}` or `{-y}`, and `{z}` placeholders.\n */\n\n/**\n * @classdesc\n * A pseudo tile source, which does not fetch tiles from a server, but renders\n * a grid outline for the tile grid/projection along with the coordinates for\n * each tile. See examples/canvas-tiles for an example.\n * @api\n */\nclass TileDebug extends XYZ {\n /**\n * @param {Options} [options] Debug tile options.\n */\n constructor(options) {\n /**\n * @type {Options}\n */\n options = options || {};\n\n super({\n opaque: false,\n projection: options.projection,\n tileGrid: options.tileGrid,\n wrapX: options.wrapX !== undefined ? options.wrapX : true,\n zDirection: options.zDirection,\n url: options.template || 'z:{z} x:{x} y:{y}',\n tileLoadFunction: (tile, text) => {\n const z = tile.getTileCoord()[0];\n const tileSize = toSize(this.tileGrid.getTileSize(z));\n const context = createCanvasContext2D(tileSize[0], tileSize[1]);\n\n context.strokeStyle = 'grey';\n context.strokeRect(0.5, 0.5, tileSize[0] + 0.5, tileSize[1] + 0.5);\n\n context.fillStyle = 'grey';\n context.strokeStyle = 'white';\n context.textAlign = 'center';\n context.textBaseline = 'middle';\n context.font = '24px sans-serif';\n context.lineWidth = 4;\n context.strokeText(text, tileSize[0] / 2, tileSize[1] / 2, tileSize[0]);\n context.fillText(text, tileSize[0] / 2, tileSize[1] / 2, tileSize[0]);\n\n /** @type {import(\"../ImageTile.js\").default} */ (tile).setImage(\n context.canvas\n );\n },\n });\n }\n}\n\nexport default TileDebug;\n","/**\n * @module ol/source/TileJSON\n */\n// FIXME check order of async callbacks\n\n/**\n * See https://mapbox.com/developers/api/.\n */\n\nimport TileImage from './TileImage.js';\nimport {applyTransform, intersects} from '../extent.js';\nimport {assert} from '../asserts.js';\nimport {createFromTemplates} from '../tileurlfunction.js';\nimport {createXYZ, extentFromProjection} from '../tilegrid.js';\nimport {get as getProjection, getTransformFromProjections} from '../proj.js';\nimport {jsonp as requestJSONP} from '../net.js';\n\n/**\n * @typedef {Object} Config\n * @property {string} [name] The name.\n * @property {string} [description] The description.\n * @property {string} [version] The version.\n * @property {string} [attribution] The attribution.\n * @property {string} [template] The template.\n * @property {string} [legend] The legend.\n * @property {string} [scheme] The scheme.\n * @property {Array} tiles The tile URL templates.\n * @property {Array} [grids] Optional grids.\n * @property {number} [minzoom] Minimum zoom level.\n * @property {number} [maxzoom] Maximum zoom level.\n * @property {Array} [bounds] Optional bounds.\n * @property {Array} [center] Optional center.\n */\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {number} [cacheSize] Initial tile cache size. Will auto-grow to hold at least the number of tiles in the viewport.\n * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images. Note that\n * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.\n * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.\n * @property {boolean} [interpolate=true] Use interpolated values when resampling. By default,\n * linear interpolation is used when resampling. Set to false to use the nearest neighbor instead.\n * @property {boolean} [jsonp=false] Use JSONP with callback to load the TileJSON.\n * Useful when the server does not support CORS..\n * @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).\n * Higher values can increase reprojection performance, but decrease precision.\n * @property {Config} [tileJSON] TileJSON configuration for this source.\n * If not provided, `url` must be configured.\n * @property {import(\"../Tile.js\").LoadFunction} [tileLoadFunction] Optional function to load a tile given a URL. The default is\n * ```js\n * function(imageTile, src) {\n * imageTile.getImage().src = src;\n * };\n * ```\n * @property {number|import(\"../size.js\").Size} [tileSize=[256, 256]] The tile size used by the tile service.\n * Note: `tileSize` and other non-standard TileJSON properties are currently ignored.\n * @property {string} [url] URL to the TileJSON file. If not provided, `tileJSON` must be configured.\n * @property {boolean} [wrapX=true] Whether to wrap the world horizontally.\n * @property {number} [transition] Duration of the opacity transition for rendering.\n * To disable the opacity transition, pass `transition: 0`.\n * @property {number|import(\"../array.js\").NearestDirectionFunction} [zDirection=0]\n * Choose whether to use tiles with a higher or lower zoom level when between integer\n * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.\n */\n\n/**\n * @classdesc\n * Layer source for tile data in TileJSON format.\n * @api\n */\nclass TileJSON extends TileImage {\n /**\n * @param {Options} options TileJSON options.\n */\n constructor(options) {\n super({\n attributions: options.attributions,\n cacheSize: options.cacheSize,\n crossOrigin: options.crossOrigin,\n interpolate: options.interpolate,\n projection: getProjection('EPSG:3857'),\n reprojectionErrorThreshold: options.reprojectionErrorThreshold,\n state: 'loading',\n tileLoadFunction: options.tileLoadFunction,\n wrapX: options.wrapX !== undefined ? options.wrapX : true,\n transition: options.transition,\n zDirection: options.zDirection,\n });\n\n /**\n * @type {Config}\n * @private\n */\n this.tileJSON_ = null;\n\n /**\n * @type {number|import(\"../size.js\").Size}\n * @private\n */\n this.tileSize_ = options.tileSize;\n\n if (options.url) {\n if (options.jsonp) {\n requestJSONP(\n options.url,\n this.handleTileJSONResponse.bind(this),\n this.handleTileJSONError.bind(this)\n );\n } else {\n const client = new XMLHttpRequest();\n client.addEventListener('load', this.onXHRLoad_.bind(this));\n client.addEventListener('error', this.onXHRError_.bind(this));\n client.open('GET', options.url);\n client.send();\n }\n } else if (options.tileJSON) {\n this.handleTileJSONResponse(options.tileJSON);\n } else {\n assert(false, 51); // Either `url` or `tileJSON` options must be provided\n }\n }\n\n /**\n * @private\n * @param {Event} event The load event.\n */\n onXHRLoad_(event) {\n const client = /** @type {XMLHttpRequest} */ (event.target);\n // status will be 0 for file:// urls\n if (!client.status || (client.status >= 200 && client.status < 300)) {\n let response;\n try {\n response = /** @type {Config} */ (JSON.parse(client.responseText));\n } catch (err) {\n this.handleTileJSONError();\n return;\n }\n this.handleTileJSONResponse(response);\n } else {\n this.handleTileJSONError();\n }\n }\n\n /**\n * @private\n * @param {Event} event The error event.\n */\n onXHRError_(event) {\n this.handleTileJSONError();\n }\n\n /**\n * @return {Config} The tilejson object.\n * @api\n */\n getTileJSON() {\n return this.tileJSON_;\n }\n\n /**\n * @protected\n * @param {Config} tileJSON Tile JSON.\n */\n handleTileJSONResponse(tileJSON) {\n const epsg4326Projection = getProjection('EPSG:4326');\n\n const sourceProjection = this.getProjection();\n let extent;\n if (tileJSON['bounds'] !== undefined) {\n const transform = getTransformFromProjections(\n epsg4326Projection,\n sourceProjection\n );\n extent = applyTransform(tileJSON['bounds'], transform);\n }\n\n const gridExtent = extentFromProjection(sourceProjection);\n const minZoom = tileJSON['minzoom'] || 0;\n const maxZoom = tileJSON['maxzoom'] || 22;\n const tileGrid = createXYZ({\n extent: gridExtent,\n maxZoom: maxZoom,\n minZoom: minZoom,\n tileSize: this.tileSize_,\n });\n this.tileGrid = tileGrid;\n\n this.tileUrlFunction = createFromTemplates(tileJSON['tiles'], tileGrid);\n\n if (tileJSON['attribution'] && !this.getAttributions()) {\n const attributionExtent = extent !== undefined ? extent : gridExtent;\n this.setAttributions(function (frameState) {\n if (intersects(attributionExtent, frameState.extent)) {\n return [tileJSON['attribution']];\n }\n return null;\n });\n }\n this.tileJSON_ = tileJSON;\n this.setState('ready');\n }\n\n /**\n * @protected\n */\n handleTileJSONError() {\n this.setState('error');\n }\n}\n\nexport default TileJSON;\n","/**\n * @module ol/source/TileWMS\n */\n\nimport TileImage from './TileImage.js';\nimport {DEFAULT_VERSION} from './wms.js';\nimport {appendParams} from '../uri.js';\nimport {assert} from '../asserts.js';\nimport {buffer, createEmpty} from '../extent.js';\nimport {buffer as bufferSize, scale as scaleSize, toSize} from '../size.js';\nimport {calculateSourceResolution} from '../reproj.js';\nimport {compareVersions} from '../string.js';\nimport {get as getProjection, transform, transformExtent} from '../proj.js';\nimport {modulo} from '../math.js';\nimport {hash as tileCoordHash} from '../tilecoord.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.\n * @property {number} [cacheSize] Initial tile cache size. Will auto-grow to hold at least the number of tiles in the viewport.\n * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images. Note that\n * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.\n * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.\n * @property {boolean} [interpolate=true] Use interpolated values when resampling. By default,\n * linear interpolation is used when resampling. Set to false to use the nearest neighbor instead.\n * @property {Object} params WMS request parameters.\n * At least a `LAYERS` param is required. `STYLES` is\n * `''` by default. `VERSION` is `1.3.0` by default. `WIDTH`, `HEIGHT`, `BBOX`\n * and `CRS` (`SRS` for WMS version < 1.3.0) will be set dynamically.\n * @property {number} [gutter=0]\n * The size in pixels of the gutter around image tiles to ignore. By setting\n * this property to a non-zero value, images will be requested that are wider\n * and taller than the tile size by a value of `2 x gutter`.\n * Using a non-zero value allows artifacts of rendering at tile edges to be\n * ignored. If you control the WMS service it is recommended to address\n * \"artifacts at tile edges\" issues by properly configuring the WMS service. For\n * example, MapServer has a `tile_map_edge_buffer` configuration parameter for\n * this. See https://mapserver.org/output/tile_mode.html.\n * @property {boolean} [hidpi=true] Use the `ol/Map#pixelRatio` value when requesting\n * the image from the remote server.\n * @property {import(\"../proj.js\").ProjectionLike} [projection] Projection. Default is the view projection.\n * @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).\n * Higher values can increase reprojection performance, but decrease precision.\n * @property {typeof import(\"../ImageTile.js\").default} [tileClass] Class used to instantiate image tiles.\n * Default is {@link module:ol/ImageTile~ImageTile}.\n * @property {import(\"../tilegrid/TileGrid.js\").default} [tileGrid] Tile grid. Base this on the resolutions,\n * tilesize and extent supported by the server.\n * If this is not defined, a default grid will be used: if there is a projection\n * extent, the grid will be based on that; if not, a grid based on a global\n * extent with origin at 0,0 will be used.\n * @property {import(\"./wms.js\").ServerType} [serverType] The type of\n * the remote WMS server: `mapserver`, `geoserver`, `carmentaserver`, or `qgis`.\n * Only needed if `hidpi` is `true`.\n * @property {import(\"../Tile.js\").LoadFunction} [tileLoadFunction] Optional function to load a tile given a URL. The default is\n * ```js\n * function(imageTile, src) {\n * imageTile.getImage().src = src;\n * };\n * ```\n * @property {string} [url] WMS service URL.\n * @property {Array} [urls] WMS service urls.\n * Use this instead of `url` when the WMS supports multiple urls for GetMap requests.\n * @property {boolean} [wrapX=true] Whether to wrap the world horizontally.\n * When set to `false`, only one world\n * will be rendered. When `true`, tiles will be requested for one world only,\n * but they will be wrapped horizontally to render multiple worlds.\n * @property {number} [transition] Duration of the opacity transition for rendering.\n * To disable the opacity transition, pass `transition: 0`.\n * @property {number|import(\"../array.js\").NearestDirectionFunction} [zDirection=0]\n * Choose whether to use tiles with a higher or lower zoom level when between integer\n * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.\n */\n\n/**\n * @classdesc\n * Layer source for tile data from WMS servers.\n * @api\n */\nclass TileWMS extends TileImage {\n /**\n * @param {Options} [options] Tile WMS options.\n */\n constructor(options) {\n options = options ? options : /** @type {Options} */ ({});\n\n const params = Object.assign({}, options.params);\n\n const transparent = 'TRANSPARENT' in params ? params['TRANSPARENT'] : true;\n\n super({\n attributions: options.attributions,\n attributionsCollapsible: options.attributionsCollapsible,\n cacheSize: options.cacheSize,\n crossOrigin: options.crossOrigin,\n interpolate: options.interpolate,\n opaque: !transparent,\n projection: options.projection,\n reprojectionErrorThreshold: options.reprojectionErrorThreshold,\n tileClass: options.tileClass,\n tileGrid: options.tileGrid,\n tileLoadFunction: options.tileLoadFunction,\n url: options.url,\n urls: options.urls,\n wrapX: options.wrapX !== undefined ? options.wrapX : true,\n transition: options.transition,\n zDirection: options.zDirection,\n });\n\n /**\n * @private\n * @type {number}\n */\n this.gutter_ = options.gutter !== undefined ? options.gutter : 0;\n\n /**\n * @private\n * @type {!Object}\n */\n this.params_ = params;\n\n /**\n * @private\n * @type {boolean}\n */\n this.v13_ = true;\n\n /**\n * @private\n * @type {import(\"./wms.js\").ServerType}\n */\n this.serverType_ = options.serverType;\n\n /**\n * @private\n * @type {boolean}\n */\n this.hidpi_ = options.hidpi !== undefined ? options.hidpi : true;\n\n /**\n * @private\n * @type {import(\"../extent.js\").Extent}\n */\n this.tmpExtent_ = createEmpty();\n\n this.updateV13_();\n this.setKey(this.getKeyForParams_());\n }\n\n /**\n * Return the GetFeatureInfo URL for the passed coordinate, resolution, and\n * projection. Return `undefined` if the GetFeatureInfo URL cannot be\n * constructed.\n * @param {import(\"../coordinate.js\").Coordinate} coordinate Coordinate.\n * @param {number} resolution Resolution.\n * @param {import(\"../proj.js\").ProjectionLike} projection Projection.\n * @param {!Object} params GetFeatureInfo params. `INFO_FORMAT` at least should\n * be provided. If `QUERY_LAYERS` is not provided then the layers specified\n * in the `LAYERS` parameter will be used. `VERSION` should not be\n * specified here.\n * @return {string|undefined} GetFeatureInfo URL.\n * @api\n */\n getFeatureInfoUrl(coordinate, resolution, projection, params) {\n const projectionObj = getProjection(projection);\n const sourceProjectionObj = this.getProjection();\n\n let tileGrid = this.getTileGrid();\n if (!tileGrid) {\n tileGrid = this.getTileGridForProjection(projectionObj);\n }\n\n const z = tileGrid.getZForResolution(resolution, this.zDirection);\n const tileCoord = tileGrid.getTileCoordForCoordAndZ(coordinate, z);\n\n if (tileGrid.getResolutions().length <= tileCoord[0]) {\n return undefined;\n }\n\n let tileResolution = tileGrid.getResolution(tileCoord[0]);\n let tileExtent = tileGrid.getTileCoordExtent(tileCoord, this.tmpExtent_);\n let tileSize = toSize(tileGrid.getTileSize(tileCoord[0]), this.tmpSize);\n\n const gutter = this.gutter_;\n if (gutter !== 0) {\n tileSize = bufferSize(tileSize, gutter, this.tmpSize);\n tileExtent = buffer(tileExtent, tileResolution * gutter, tileExtent);\n }\n\n if (sourceProjectionObj && sourceProjectionObj !== projectionObj) {\n tileResolution = calculateSourceResolution(\n sourceProjectionObj,\n projectionObj,\n coordinate,\n tileResolution\n );\n tileExtent = transformExtent(\n tileExtent,\n projectionObj,\n sourceProjectionObj\n );\n coordinate = transform(coordinate, projectionObj, sourceProjectionObj);\n }\n\n const baseParams = {\n 'SERVICE': 'WMS',\n 'VERSION': DEFAULT_VERSION,\n 'REQUEST': 'GetFeatureInfo',\n 'FORMAT': 'image/png',\n 'TRANSPARENT': true,\n 'QUERY_LAYERS': this.params_['LAYERS'],\n };\n Object.assign(baseParams, this.params_, params);\n\n const x = Math.floor((coordinate[0] - tileExtent[0]) / tileResolution);\n const y = Math.floor((tileExtent[3] - coordinate[1]) / tileResolution);\n\n baseParams[this.v13_ ? 'I' : 'X'] = x;\n baseParams[this.v13_ ? 'J' : 'Y'] = y;\n\n return this.getRequestUrl_(\n tileCoord,\n tileSize,\n tileExtent,\n 1,\n sourceProjectionObj || projectionObj,\n baseParams\n );\n }\n\n /**\n * Return the GetLegendGraphic URL, optionally optimized for the passed\n * resolution and possibly including any passed specific parameters. Returns\n * `undefined` if the GetLegendGraphic URL cannot be constructed.\n *\n * @param {number} [resolution] Resolution. If set to undefined, `SCALE`\n * will not be calculated and included in URL.\n * @param {Object} [params] GetLegendGraphic params. If `LAYER` is set, the\n * request is generated for this wms layer, else it will try to use the\n * configured wms layer. Default `FORMAT` is `image/png`.\n * `VERSION` should not be specified here.\n * @return {string|undefined} GetLegendGraphic URL.\n * @api\n */\n getLegendUrl(resolution, params) {\n if (this.urls[0] === undefined) {\n return undefined;\n }\n\n const baseParams = {\n 'SERVICE': 'WMS',\n 'VERSION': DEFAULT_VERSION,\n 'REQUEST': 'GetLegendGraphic',\n 'FORMAT': 'image/png',\n };\n\n if (params === undefined || params['LAYER'] === undefined) {\n const layers = this.params_.LAYERS;\n const isSingleLayer = !Array.isArray(layers) || layers.length === 1;\n if (!isSingleLayer) {\n return undefined;\n }\n baseParams['LAYER'] = layers;\n }\n\n if (resolution !== undefined) {\n const mpu = this.getProjection()\n ? this.getProjection().getMetersPerUnit()\n : 1;\n const pixelSize = 0.00028;\n baseParams['SCALE'] = (resolution * mpu) / pixelSize;\n }\n\n Object.assign(baseParams, params);\n\n return appendParams(/** @type {string} */ (this.urls[0]), baseParams);\n }\n\n /**\n * @return {number} Gutter.\n */\n getGutter() {\n return this.gutter_;\n }\n\n /**\n * Get the user-provided params, i.e. those passed to the constructor through\n * the \"params\" option, and possibly updated using the updateParams method.\n * @return {Object} Params.\n * @api\n */\n getParams() {\n return this.params_;\n }\n\n /**\n * @param {import(\"../tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n * @param {import(\"../size.js\").Size} tileSize Tile size.\n * @param {import(\"../extent.js\").Extent} tileExtent Tile extent.\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @param {Object} params Params.\n * @return {string|undefined} Request URL.\n * @private\n */\n getRequestUrl_(\n tileCoord,\n tileSize,\n tileExtent,\n pixelRatio,\n projection,\n params\n ) {\n const urls = this.urls;\n if (!urls) {\n return undefined;\n }\n\n params['WIDTH'] = tileSize[0];\n params['HEIGHT'] = tileSize[1];\n\n params[this.v13_ ? 'CRS' : 'SRS'] = projection.getCode();\n\n if (!('STYLES' in this.params_)) {\n params['STYLES'] = '';\n }\n\n if (pixelRatio != 1) {\n switch (this.serverType_) {\n case 'geoserver':\n const dpi = (90 * pixelRatio + 0.5) | 0;\n if ('FORMAT_OPTIONS' in params) {\n params['FORMAT_OPTIONS'] += ';dpi:' + dpi;\n } else {\n params['FORMAT_OPTIONS'] = 'dpi:' + dpi;\n }\n break;\n case 'mapserver':\n params['MAP_RESOLUTION'] = 90 * pixelRatio;\n break;\n case 'carmentaserver':\n case 'qgis':\n params['DPI'] = 90 * pixelRatio;\n break;\n default: // Unknown `serverType` configured\n assert(false, 52);\n break;\n }\n }\n\n const axisOrientation = projection.getAxisOrientation();\n const bbox = tileExtent;\n if (this.v13_ && axisOrientation.substr(0, 2) == 'ne') {\n let tmp;\n tmp = tileExtent[0];\n bbox[0] = tileExtent[1];\n bbox[1] = tmp;\n tmp = tileExtent[2];\n bbox[2] = tileExtent[3];\n bbox[3] = tmp;\n }\n params['BBOX'] = bbox.join(',');\n\n let url;\n if (urls.length == 1) {\n url = urls[0];\n } else {\n const index = modulo(tileCoordHash(tileCoord), urls.length);\n url = urls[index];\n }\n return appendParams(url, params);\n }\n\n /**\n * Get the tile pixel ratio for this source.\n * @param {number} pixelRatio Pixel ratio.\n * @return {number} Tile pixel ratio.\n */\n getTilePixelRatio(pixelRatio) {\n return !this.hidpi_ || this.serverType_ === undefined ? 1 : pixelRatio;\n }\n\n /**\n * @private\n * @return {string} The key for the current params.\n */\n getKeyForParams_() {\n let i = 0;\n const res = [];\n for (const key in this.params_) {\n res[i++] = key + '-' + this.params_[key];\n }\n return res.join('/');\n }\n\n /**\n * Update the user-provided params.\n * @param {Object} params Params.\n * @api\n */\n updateParams(params) {\n Object.assign(this.params_, params);\n this.updateV13_();\n this.setKey(this.getKeyForParams_());\n }\n\n /**\n * @private\n */\n updateV13_() {\n const version = this.params_['VERSION'] || DEFAULT_VERSION;\n this.v13_ = compareVersions(version, '1.3') >= 0;\n }\n\n /**\n * @param {import(\"../tilecoord.js\").TileCoord} tileCoord The tile coordinate\n * @param {number} pixelRatio The pixel ratio\n * @param {import(\"../proj/Projection.js\").default} projection The projection\n * @return {string|undefined} The tile URL\n * @override\n */\n tileUrlFunction(tileCoord, pixelRatio, projection) {\n let tileGrid = this.getTileGrid();\n if (!tileGrid) {\n tileGrid = this.getTileGridForProjection(projection);\n }\n\n if (tileGrid.getResolutions().length <= tileCoord[0]) {\n return undefined;\n }\n\n if (pixelRatio != 1 && (!this.hidpi_ || this.serverType_ === undefined)) {\n pixelRatio = 1;\n }\n\n const tileResolution = tileGrid.getResolution(tileCoord[0]);\n let tileExtent = tileGrid.getTileCoordExtent(tileCoord, this.tmpExtent_);\n let tileSize = toSize(tileGrid.getTileSize(tileCoord[0]), this.tmpSize);\n\n const gutter = this.gutter_;\n if (gutter !== 0) {\n tileSize = bufferSize(tileSize, gutter, this.tmpSize);\n tileExtent = buffer(tileExtent, tileResolution * gutter, tileExtent);\n }\n\n if (pixelRatio != 1) {\n tileSize = scaleSize(tileSize, pixelRatio, this.tmpSize);\n }\n\n const baseParams = {\n 'SERVICE': 'WMS',\n 'VERSION': DEFAULT_VERSION,\n 'REQUEST': 'GetMap',\n 'FORMAT': 'image/png',\n 'TRANSPARENT': true,\n };\n Object.assign(baseParams, this.params_);\n\n return this.getRequestUrl_(\n tileCoord,\n tileSize,\n tileExtent,\n pixelRatio,\n projection,\n baseParams\n );\n }\n}\n\nexport default TileWMS;\n","/**\n * @module ol/source/UTFGrid\n */\n\nimport EventType from '../events/EventType.js';\nimport Tile from '../Tile.js';\nimport TileSource from './Tile.js';\nimport TileState from '../TileState.js';\nimport {applyTransform, intersects} from '../extent.js';\nimport {assert} from '../asserts.js';\nimport {createFromTemplates, nullTileUrlFunction} from '../tileurlfunction.js';\nimport {createXYZ, extentFromProjection} from '../tilegrid.js';\nimport {getKeyZXY} from '../tilecoord.js';\nimport {get as getProjection, getTransformFromProjections} from '../proj.js';\nimport {listenOnce} from '../events.js';\nimport {jsonp as requestJSONP} from '../net.js';\n\n/**\n * @typedef {Object} UTFGridJSON\n * @property {Array} grid The grid.\n * @property {Array} keys The keys.\n * @property {Object} [data] Optional data.\n */\n\nexport class CustomTile extends Tile {\n /**\n * @param {import(\"../tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n * @param {import(\"../TileState.js\").default} state State.\n * @param {string} src Image source URI.\n * @param {import(\"../extent.js\").Extent} extent Extent of the tile.\n * @param {boolean} preemptive Load the tile when visible (before it's needed).\n * @param {boolean} jsonp Load the tile as a script.\n */\n constructor(tileCoord, state, src, extent, preemptive, jsonp) {\n super(tileCoord, state);\n\n /**\n * @private\n * @type {string}\n */\n this.src_ = src;\n\n /**\n * @private\n * @type {import(\"../extent.js\").Extent}\n */\n this.extent_ = extent;\n\n /**\n * @private\n * @type {boolean}\n */\n this.preemptive_ = preemptive;\n\n /**\n * @private\n * @type {Array}\n */\n this.grid_ = null;\n\n /**\n * @private\n * @type {Array}\n */\n this.keys_ = null;\n\n /**\n * @private\n * @type {Object|undefined}\n */\n this.data_ = null;\n\n /**\n * @private\n * @type {boolean}\n */\n this.jsonp_ = jsonp;\n }\n\n /**\n * Get the image element for this tile.\n * @return {HTMLImageElement} Image.\n */\n getImage() {\n return null;\n }\n\n /**\n * Synchronously returns data at given coordinate (if available).\n * @param {import(\"../coordinate.js\").Coordinate} coordinate Coordinate.\n * @return {*} The data.\n */\n getData(coordinate) {\n if (!this.grid_ || !this.keys_) {\n return null;\n }\n const xRelative =\n (coordinate[0] - this.extent_[0]) / (this.extent_[2] - this.extent_[0]);\n const yRelative =\n (coordinate[1] - this.extent_[1]) / (this.extent_[3] - this.extent_[1]);\n\n const row = this.grid_[Math.floor((1 - yRelative) * this.grid_.length)];\n\n if (typeof row !== 'string') {\n return null;\n }\n\n let code = row.charCodeAt(Math.floor(xRelative * row.length));\n if (code >= 93) {\n code--;\n }\n if (code >= 35) {\n code--;\n }\n code -= 32;\n\n let data = null;\n if (code in this.keys_) {\n const id = this.keys_[code];\n if (this.data_ && id in this.data_) {\n data = this.data_[id];\n } else {\n data = id;\n }\n }\n return data;\n }\n\n /**\n * Calls the callback (synchronously by default) with the available data\n * for given coordinate (or `null` if not yet loaded).\n * @param {import(\"../coordinate.js\").Coordinate} coordinate Coordinate.\n * @param {function(*): void} callback Callback.\n * @param {boolean} [request] If `true` the callback is always async.\n * The tile data is requested if not yet loaded.\n */\n forDataAtCoordinate(coordinate, callback, request) {\n if (this.state == TileState.EMPTY && request === true) {\n this.state = TileState.IDLE;\n listenOnce(\n this,\n EventType.CHANGE,\n function (e) {\n callback(this.getData(coordinate));\n },\n this\n );\n this.loadInternal_();\n } else {\n if (request === true) {\n setTimeout(() => {\n callback(this.getData(coordinate));\n }, 0);\n } else {\n callback(this.getData(coordinate));\n }\n }\n }\n\n /**\n * Return the key to be used for all tiles in the source.\n * @return {string} The key for all tiles.\n */\n getKey() {\n return this.src_;\n }\n\n /**\n * @private\n */\n handleError_() {\n this.state = TileState.ERROR;\n this.changed();\n }\n\n /**\n * @param {!UTFGridJSON} json UTFGrid data.\n * @private\n */\n handleLoad_(json) {\n this.grid_ = json['grid'];\n this.keys_ = json['keys'];\n this.data_ = json['data'];\n\n this.state = TileState.LOADED;\n this.changed();\n }\n\n /**\n * @private\n */\n loadInternal_() {\n if (this.state == TileState.IDLE) {\n this.state = TileState.LOADING;\n if (this.jsonp_) {\n requestJSONP(\n this.src_,\n this.handleLoad_.bind(this),\n this.handleError_.bind(this)\n );\n } else {\n const client = new XMLHttpRequest();\n client.addEventListener('load', this.onXHRLoad_.bind(this));\n client.addEventListener('error', this.onXHRError_.bind(this));\n client.open('GET', this.src_);\n client.send();\n }\n }\n }\n\n /**\n * @private\n * @param {Event} event The load event.\n */\n onXHRLoad_(event) {\n const client = /** @type {XMLHttpRequest} */ (event.target);\n // status will be 0 for file:// urls\n if (!client.status || (client.status >= 200 && client.status < 300)) {\n let response;\n try {\n response = /** @type {!UTFGridJSON} */ (\n JSON.parse(client.responseText)\n );\n } catch (err) {\n this.handleError_();\n return;\n }\n this.handleLoad_(response);\n } else {\n this.handleError_();\n }\n }\n\n /**\n * @private\n * @param {Event} event The error event.\n */\n onXHRError_(event) {\n this.handleError_();\n }\n\n /**\n */\n load() {\n if (this.preemptive_) {\n this.loadInternal_();\n } else {\n this.setState(TileState.EMPTY);\n }\n }\n}\n\n/**\n * @typedef {Object} Options\n * @property {boolean} [preemptive=true]\n * If `true` the UTFGrid source loads the tiles based on their \"visibility\".\n * This improves the speed of response, but increases traffic.\n * Note that if set to `false` (lazy loading), you need to pass `true` as\n * `request` to the `forDataAtCoordinateAndResolution` method otherwise no\n * data will ever be loaded.\n * @property {boolean} [jsonp=false] Use JSONP with callback to load the TileJSON.\n * Useful when the server does not support CORS..\n * @property {import(\"./TileJSON.js\").Config} [tileJSON] TileJSON configuration for this source.\n * If not provided, `url` must be configured.\n * @property {string} [url] TileJSON endpoint that provides the configuration for this source.\n * Request will be made through JSONP. If not provided, `tileJSON` must be configured.\n * @property {number|import(\"../array.js\").NearestDirectionFunction} [zDirection=0]\n * Choose whether to use tiles with a higher or lower zoom level when between integer\n * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.\n */\n\n/**\n * @classdesc\n * Layer source for UTFGrid interaction data loaded from TileJSON format.\n * @api\n */\nclass UTFGrid extends TileSource {\n /**\n * @param {Options} options Source options.\n */\n constructor(options) {\n super({\n projection: getProjection('EPSG:3857'),\n state: 'loading',\n zDirection: options.zDirection,\n });\n\n /**\n * @private\n * @type {boolean}\n */\n this.preemptive_ =\n options.preemptive !== undefined ? options.preemptive : true;\n\n /**\n * @private\n * @type {!import(\"../Tile.js\").UrlFunction}\n */\n this.tileUrlFunction_ = nullTileUrlFunction;\n\n /**\n * @private\n * @type {string|undefined}\n */\n this.template_ = undefined;\n\n /**\n * @private\n * @type {boolean}\n */\n this.jsonp_ = options.jsonp || false;\n\n if (options.url) {\n if (this.jsonp_) {\n requestJSONP(\n options.url,\n this.handleTileJSONResponse.bind(this),\n this.handleTileJSONError.bind(this)\n );\n } else {\n const client = new XMLHttpRequest();\n client.addEventListener('load', this.onXHRLoad_.bind(this));\n client.addEventListener('error', this.onXHRError_.bind(this));\n client.open('GET', options.url);\n client.send();\n }\n } else if (options.tileJSON) {\n this.handleTileJSONResponse(options.tileJSON);\n } else {\n assert(false, 51); // Either `url` or `tileJSON` options must be provided\n }\n }\n\n /**\n * @private\n * @param {Event} event The load event.\n */\n onXHRLoad_(event) {\n const client = /** @type {XMLHttpRequest} */ (event.target);\n // status will be 0 for file:// urls\n if (!client.status || (client.status >= 200 && client.status < 300)) {\n let response;\n try {\n response = /** @type {import(\"./TileJSON.js\").Config} */ (\n JSON.parse(client.responseText)\n );\n } catch (err) {\n this.handleTileJSONError();\n return;\n }\n this.handleTileJSONResponse(response);\n } else {\n this.handleTileJSONError();\n }\n }\n\n /**\n * @private\n * @param {Event} event The error event.\n */\n onXHRError_(event) {\n this.handleTileJSONError();\n }\n\n /**\n * Return the template from TileJSON.\n * @return {string|undefined} The template from TileJSON.\n * @api\n */\n getTemplate() {\n return this.template_;\n }\n\n /**\n * Calls the callback (synchronously by default) with the available data\n * for given coordinate and resolution (or `null` if not yet loaded or\n * in case of an error).\n * @param {import(\"../coordinate.js\").Coordinate} coordinate Coordinate.\n * @param {number} resolution Resolution.\n * @param {function(*): void} callback Callback.\n * @param {boolean} [request] If `true` the callback is always async.\n * The tile data is requested if not yet loaded.\n * @api\n */\n forDataAtCoordinateAndResolution(coordinate, resolution, callback, request) {\n if (this.tileGrid) {\n const z = this.tileGrid.getZForResolution(resolution, this.zDirection);\n const tileCoord = this.tileGrid.getTileCoordForCoordAndZ(coordinate, z);\n const tile = /** @type {!CustomTile} */ (\n this.getTile(\n tileCoord[0],\n tileCoord[1],\n tileCoord[2],\n 1,\n this.getProjection()\n )\n );\n tile.forDataAtCoordinate(coordinate, callback, request);\n } else {\n if (request === true) {\n setTimeout(function () {\n callback(null);\n }, 0);\n } else {\n callback(null);\n }\n }\n }\n\n /**\n * @protected\n */\n handleTileJSONError() {\n this.setState('error');\n }\n\n /**\n * TODO: very similar to ol/source/TileJSON#handleTileJSONResponse\n * @protected\n * @param {import(\"./TileJSON.js\").Config} tileJSON Tile JSON.\n */\n handleTileJSONResponse(tileJSON) {\n const epsg4326Projection = getProjection('EPSG:4326');\n\n const sourceProjection = this.getProjection();\n let extent;\n if (tileJSON['bounds'] !== undefined) {\n const transform = getTransformFromProjections(\n epsg4326Projection,\n sourceProjection\n );\n extent = applyTransform(tileJSON['bounds'], transform);\n }\n\n const gridExtent = extentFromProjection(sourceProjection);\n const minZoom = tileJSON['minzoom'] || 0;\n const maxZoom = tileJSON['maxzoom'] || 22;\n const tileGrid = createXYZ({\n extent: gridExtent,\n maxZoom: maxZoom,\n minZoom: minZoom,\n });\n this.tileGrid = tileGrid;\n\n this.template_ = tileJSON['template'];\n\n const grids = tileJSON['grids'];\n if (!grids) {\n this.setState('error');\n return;\n }\n\n this.tileUrlFunction_ = createFromTemplates(grids, tileGrid);\n\n if (tileJSON['attribution'] !== undefined) {\n const attributionExtent = extent !== undefined ? extent : gridExtent;\n this.setAttributions(function (frameState) {\n if (intersects(attributionExtent, frameState.extent)) {\n return [tileJSON['attribution']];\n }\n return null;\n });\n }\n\n this.setState('ready');\n }\n\n /**\n * @param {number} z Tile coordinate z.\n * @param {number} x Tile coordinate x.\n * @param {number} y Tile coordinate y.\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {!CustomTile} Tile.\n */\n getTile(z, x, y, pixelRatio, projection) {\n const tileCoordKey = getKeyZXY(z, x, y);\n if (this.tileCache.containsKey(tileCoordKey)) {\n return this.tileCache.get(tileCoordKey);\n }\n const tileCoord = [z, x, y];\n const urlTileCoord = this.getTileCoordForTileUrlFunction(\n tileCoord,\n projection\n );\n const tileUrl = this.tileUrlFunction_(urlTileCoord, pixelRatio, projection);\n const tile = new CustomTile(\n tileCoord,\n tileUrl !== undefined ? TileState.IDLE : TileState.EMPTY,\n tileUrl !== undefined ? tileUrl : '',\n this.tileGrid.getTileCoordExtent(tileCoord),\n this.preemptive_,\n this.jsonp_\n );\n this.tileCache.set(tileCoordKey, tile);\n return tile;\n }\n\n /**\n * Marks a tile coord as being used, without triggering a load.\n * @param {number} z Tile coordinate z.\n * @param {number} x Tile coordinate x.\n * @param {number} y Tile coordinate y.\n */\n useTile(z, x, y) {\n const tileCoordKey = getKeyZXY(z, x, y);\n if (this.tileCache.containsKey(tileCoordKey)) {\n this.tileCache.get(tileCoordKey);\n }\n }\n}\n\nexport default UTFGrid;\n","/**\n * @module ol/tilegrid/WMTS\n */\n\nimport TileGrid from './TileGrid.js';\nimport {get as getProjection} from '../proj.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"../extent.js\").Extent} [extent] Extent for the tile grid. No tiles\n * outside this extent will be requested by {@link module:ol/source/Tile~TileSource} sources.\n * When no `origin` or `origins` are configured, the `origin` will be set to the\n * top-left corner of the extent.\n * @property {import(\"../coordinate.js\").Coordinate} [origin] The tile grid origin, i.e.\n * where the `x` and `y` axes meet (`[z, 0, 0]`). Tile coordinates increase left\n * to right and downwards. If not specified, `extent` or `origins` must be provided.\n * @property {Array} [origins] Tile grid origins,\n * i.e. where the `x` and `y` axes meet (`[z, 0, 0]`), for each zoom level. If\n * given, the array length should match the length of the `resolutions` array, i.e.\n * each resolution can have a different origin. Tile coordinates increase left to\n * right and downwards. If not specified, `extent` or `origin` must be provided.\n * @property {!Array} resolutions Resolutions. The array index of each\n * resolution needs to match the zoom level. This means that even if a `minZoom`\n * is configured, the resolutions array will have a length of `maxZoom + 1`\n * @property {!Array} matrixIds matrix IDs. The length of this array needs\n * to match the length of the `resolutions` array.\n * @property {Array} [sizes] Number of tile rows and columns\n * of the grid for each zoom level. The values here are the `TileMatrixWidth` and\n * `TileMatrixHeight` advertised in the GetCapabilities response of the WMTS, and\n * define each zoom level's extent together with the `origin` or `origins`.\n * A grid `extent` can be configured in addition, and will further limit the extent for\n * which tile requests are made by sources. If the bottom-left corner of\n * an extent is used as `origin` or `origins`, then the `y` value must be\n * negative because OpenLayers tile coordinates use the top left as the origin.\n * @property {number|import(\"../size.js\").Size} [tileSize] Tile size.\n * @property {Array} [tileSizes] Tile sizes. The length of\n * this array needs to match the length of the `resolutions` array.\n */\n\n/**\n * @classdesc\n * Set the grid pattern for sources accessing WMTS tiled-image servers.\n * @api\n */\nclass WMTSTileGrid extends TileGrid {\n /**\n * @param {Options} options WMTS options.\n */\n constructor(options) {\n super({\n extent: options.extent,\n origin: options.origin,\n origins: options.origins,\n resolutions: options.resolutions,\n tileSize: options.tileSize,\n tileSizes: options.tileSizes,\n sizes: options.sizes,\n });\n\n /**\n * @private\n * @type {!Array}\n */\n this.matrixIds_ = options.matrixIds;\n }\n\n /**\n * @param {number} z Z.\n * @return {string} MatrixId..\n */\n getMatrixId(z) {\n return this.matrixIds_[z];\n }\n\n /**\n * Get the list of matrix identifiers.\n * @return {Array} MatrixIds.\n * @api\n */\n getMatrixIds() {\n return this.matrixIds_;\n }\n}\n\nexport default WMTSTileGrid;\n\n/**\n * Create a tile grid from a WMTS capabilities matrix set and an\n * optional TileMatrixSetLimits.\n * @param {Object} matrixSet An object representing a matrixSet in the\n * capabilities document.\n * @param {import(\"../extent.js\").Extent} [extent] An optional extent to restrict the tile\n * ranges the server provides.\n * @param {Array} [matrixLimits] An optional object representing\n * the available matrices for tileGrid.\n * @return {WMTSTileGrid} WMTS tileGrid instance.\n * @api\n */\nexport function createFromCapabilitiesMatrixSet(\n matrixSet,\n extent,\n matrixLimits\n) {\n /** @type {!Array} */\n const resolutions = [];\n /** @type {!Array} */\n const matrixIds = [];\n /** @type {!Array} */\n const origins = [];\n /** @type {!Array} */\n const tileSizes = [];\n /** @type {!Array} */\n const sizes = [];\n\n matrixLimits = matrixLimits !== undefined ? matrixLimits : [];\n\n const supportedCRSPropName = 'SupportedCRS';\n const matrixIdsPropName = 'TileMatrix';\n const identifierPropName = 'Identifier';\n const scaleDenominatorPropName = 'ScaleDenominator';\n const topLeftCornerPropName = 'TopLeftCorner';\n const tileWidthPropName = 'TileWidth';\n const tileHeightPropName = 'TileHeight';\n\n const code = matrixSet[supportedCRSPropName];\n const projection = getProjection(code);\n const metersPerUnit = projection.getMetersPerUnit();\n // swap origin x and y coordinates if axis orientation is lat/long\n const switchOriginXY = projection.getAxisOrientation().substr(0, 2) == 'ne';\n\n matrixSet[matrixIdsPropName].sort(function (a, b) {\n return b[scaleDenominatorPropName] - a[scaleDenominatorPropName];\n });\n\n matrixSet[matrixIdsPropName].forEach(function (elt) {\n let matrixAvailable;\n // use of matrixLimits to filter TileMatrices from GetCapabilities\n // TileMatrixSet from unavailable matrix levels.\n if (matrixLimits.length > 0) {\n matrixAvailable = matrixLimits.find(function (elt_ml) {\n if (elt[identifierPropName] == elt_ml[matrixIdsPropName]) {\n return true;\n }\n // Fallback for tileMatrix identifiers that don't get prefixed\n // by their tileMatrixSet identifiers.\n if (!elt[identifierPropName].includes(':')) {\n return (\n matrixSet[identifierPropName] + ':' + elt[identifierPropName] ===\n elt_ml[matrixIdsPropName]\n );\n }\n return false;\n });\n } else {\n matrixAvailable = true;\n }\n\n if (matrixAvailable) {\n matrixIds.push(elt[identifierPropName]);\n const resolution =\n (elt[scaleDenominatorPropName] * 0.28e-3) / metersPerUnit;\n const tileWidth = elt[tileWidthPropName];\n const tileHeight = elt[tileHeightPropName];\n if (switchOriginXY) {\n origins.push([\n elt[topLeftCornerPropName][1],\n elt[topLeftCornerPropName][0],\n ]);\n } else {\n origins.push(elt[topLeftCornerPropName]);\n }\n resolutions.push(resolution);\n tileSizes.push(\n tileWidth == tileHeight ? tileWidth : [tileWidth, tileHeight]\n );\n sizes.push([elt['MatrixWidth'], elt['MatrixHeight']]);\n }\n });\n\n return new WMTSTileGrid({\n extent: extent,\n origins: origins,\n resolutions: resolutions,\n matrixIds: matrixIds,\n tileSizes: tileSizes,\n sizes: sizes,\n });\n}\n","/**\n * @module ol/source/WMTS\n */\n\nimport TileImage from './TileImage.js';\nimport {appendParams} from '../uri.js';\nimport {containsExtent} from '../extent.js';\nimport {createFromCapabilitiesMatrixSet} from '../tilegrid/WMTS.js';\nimport {createFromTileUrlFunctions, expandUrl} from '../tileurlfunction.js';\nimport {equivalent, get as getProjection, transformExtent} from '../proj.js';\n\n/**\n * Request encoding. One of 'KVP', 'REST'.\n * @typedef {'KVP' | 'REST'} RequestEncoding\n */\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./Source.js\").AttributionLike} [attributions] Attributions.\n * @property {boolean} [attributionsCollapsible=true] Attributions are collapsible.\n * @property {number} [cacheSize] Initial tile cache size. Will auto-grow to hold at least the number of tiles in the viewport.\n * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images. Note that\n * you must provide a `crossOrigin` value if you want to access pixel data with the Canvas renderer.\n * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.\n * @property {boolean} [interpolate=true] Use interpolated values when resampling. By default,\n * linear interpolation is used when resampling. Set to false to use the nearest neighbor instead.\n * @property {import(\"../tilegrid/WMTS.js\").default} tileGrid Tile grid.\n * @property {import(\"../proj.js\").ProjectionLike} [projection] Projection. Default is the view projection.\n * @property {number} [reprojectionErrorThreshold=0.5] Maximum allowed reprojection error (in pixels).\n * Higher values can increase reprojection performance, but decrease precision.\n * @property {RequestEncoding} [requestEncoding='KVP'] Request encoding.\n * @property {string} layer Layer name as advertised in the WMTS capabilities.\n * @property {string} style Style name as advertised in the WMTS capabilities.\n * @property {typeof import(\"../ImageTile.js\").default} [tileClass] Class used to instantiate image tiles. Default is {@link module:ol/ImageTile~ImageTile}.\n * @property {number} [tilePixelRatio=1] The pixel ratio used by the tile service.\n * For example, if the tile service advertizes 256px by 256px tiles but actually sends 512px\n * by 512px images (for retina/hidpi devices) then `tilePixelRatio`\n * should be set to `2`.\n * @property {string} [format='image/jpeg'] Image format. Only used when `requestEncoding` is `'KVP'`.\n * @property {string} [version='1.0.0'] WMTS version.\n * @property {string} matrixSet Matrix set.\n * @property {!Object} [dimensions] Additional \"dimensions\" for tile requests.\n * This is an object with properties named like the advertised WMTS dimensions.\n * @property {string} [url] A URL for the service.\n * For the RESTful request encoding, this is a URL\n * template. For KVP encoding, it is normal URL. A `{?-?}` template pattern,\n * for example `subdomain{a-f}.domain.com`, may be used instead of defining\n * each one separately in the `urls` option.\n * @property {import(\"../Tile.js\").LoadFunction} [tileLoadFunction] Optional function to load a tile given a URL. The default is\n * ```js\n * function(imageTile, src) {\n * imageTile.getImage().src = src;\n * };\n * ```\n * @property {Array} [urls] An array of URLs.\n * Requests will be distributed among the URLs in this array.\n * @property {boolean} [wrapX=false] Whether to wrap the world horizontally.\n * @property {number} [transition] Duration of the opacity transition for rendering.\n * To disable the opacity transition, pass `transition: 0`.\n * @property {number|import(\"../array.js\").NearestDirectionFunction} [zDirection=0]\n * Choose whether to use tiles with a higher or lower zoom level when between integer\n * zoom levels. See {@link module:ol/tilegrid/TileGrid~TileGrid#getZForResolution}.\n */\n\n/**\n * @classdesc\n * Layer source for tile data from WMTS servers.\n * @api\n */\nclass WMTS extends TileImage {\n /**\n * @param {Options} options WMTS options.\n */\n constructor(options) {\n // TODO: add support for TileMatrixLimits\n\n const requestEncoding =\n options.requestEncoding !== undefined ? options.requestEncoding : 'KVP';\n\n // FIXME: should we create a default tileGrid?\n // we could issue a getCapabilities xhr to retrieve missing configuration\n const tileGrid = options.tileGrid;\n\n let urls = options.urls;\n if (urls === undefined && options.url !== undefined) {\n urls = expandUrl(options.url);\n }\n\n super({\n attributions: options.attributions,\n attributionsCollapsible: options.attributionsCollapsible,\n cacheSize: options.cacheSize,\n crossOrigin: options.crossOrigin,\n interpolate: options.interpolate,\n projection: options.projection,\n reprojectionErrorThreshold: options.reprojectionErrorThreshold,\n tileClass: options.tileClass,\n tileGrid: tileGrid,\n tileLoadFunction: options.tileLoadFunction,\n tilePixelRatio: options.tilePixelRatio,\n urls: urls,\n wrapX: options.wrapX !== undefined ? options.wrapX : false,\n transition: options.transition,\n zDirection: options.zDirection,\n });\n\n /**\n * @private\n * @type {string}\n */\n this.version_ = options.version !== undefined ? options.version : '1.0.0';\n\n /**\n * @private\n * @type {string}\n */\n this.format_ = options.format !== undefined ? options.format : 'image/jpeg';\n\n /**\n * @private\n * @type {!Object}\n */\n this.dimensions_ =\n options.dimensions !== undefined ? options.dimensions : {};\n\n /**\n * @private\n * @type {string}\n */\n this.layer_ = options.layer;\n\n /**\n * @private\n * @type {string}\n */\n this.matrixSet_ = options.matrixSet;\n\n /**\n * @private\n * @type {string}\n */\n this.style_ = options.style;\n\n // FIXME: should we guess this requestEncoding from options.url(s)\n // structure? that would mean KVP only if a template is not provided.\n\n /**\n * @private\n * @type {RequestEncoding}\n */\n this.requestEncoding_ = requestEncoding;\n\n this.setKey(this.getKeyForDimensions_());\n\n if (urls && urls.length > 0) {\n this.tileUrlFunction = createFromTileUrlFunctions(\n urls.map(this.createFromWMTSTemplate.bind(this))\n );\n }\n }\n\n /**\n * Set the URLs to use for requests.\n * URLs may contain OGC conform URL Template Variables: {TileMatrix}, {TileRow}, {TileCol}.\n * @param {Array} urls URLs.\n */\n setUrls(urls) {\n this.urls = urls;\n const key = urls.join('\\n');\n this.setTileUrlFunction(\n createFromTileUrlFunctions(\n urls.map(this.createFromWMTSTemplate.bind(this))\n ),\n key\n );\n }\n\n /**\n * Get the dimensions, i.e. those passed to the constructor through the\n * \"dimensions\" option, and possibly updated using the updateDimensions\n * method.\n * @return {!Object} Dimensions.\n * @api\n */\n getDimensions() {\n return this.dimensions_;\n }\n\n /**\n * Return the image format of the WMTS source.\n * @return {string} Format.\n * @api\n */\n getFormat() {\n return this.format_;\n }\n\n /**\n * Return the layer of the WMTS source.\n * @return {string} Layer.\n * @api\n */\n getLayer() {\n return this.layer_;\n }\n\n /**\n * Return the matrix set of the WMTS source.\n * @return {string} MatrixSet.\n * @api\n */\n getMatrixSet() {\n return this.matrixSet_;\n }\n\n /**\n * Return the request encoding, either \"KVP\" or \"REST\".\n * @return {RequestEncoding} Request encoding.\n * @api\n */\n getRequestEncoding() {\n return this.requestEncoding_;\n }\n\n /**\n * Return the style of the WMTS source.\n * @return {string} Style.\n * @api\n */\n getStyle() {\n return this.style_;\n }\n\n /**\n * Return the version of the WMTS source.\n * @return {string} Version.\n * @api\n */\n getVersion() {\n return this.version_;\n }\n\n /**\n * @private\n * @return {string} The key for the current dimensions.\n */\n getKeyForDimensions_() {\n const res = this.urls ? this.urls.slice(0) : [];\n for (const key in this.dimensions_) {\n res.push(key + '-' + this.dimensions_[key]);\n }\n return res.join('/');\n }\n\n /**\n * Update the dimensions.\n * @param {Object} dimensions Dimensions.\n * @api\n */\n updateDimensions(dimensions) {\n Object.assign(this.dimensions_, dimensions);\n this.setKey(this.getKeyForDimensions_());\n }\n\n /**\n * @param {string} template Template.\n * @return {import(\"../Tile.js\").UrlFunction} Tile URL function.\n */\n createFromWMTSTemplate(template) {\n const requestEncoding = this.requestEncoding_;\n\n // context property names are lower case to allow for a case insensitive\n // replacement as some services use different naming conventions\n const context = {\n 'layer': this.layer_,\n 'style': this.style_,\n 'tilematrixset': this.matrixSet_,\n };\n\n if (requestEncoding == 'KVP') {\n Object.assign(context, {\n 'Service': 'WMTS',\n 'Request': 'GetTile',\n 'Version': this.version_,\n 'Format': this.format_,\n });\n }\n\n // TODO: we may want to create our own appendParams function so that params\n // order conforms to wmts spec guidance, and so that we can avoid to escape\n // special template params\n\n template =\n requestEncoding == 'KVP'\n ? appendParams(template, context)\n : template.replace(/\\{(\\w+?)\\}/g, function (m, p) {\n return p.toLowerCase() in context ? context[p.toLowerCase()] : m;\n });\n\n const tileGrid = /** @type {import(\"../tilegrid/WMTS.js\").default} */ (\n this.tileGrid\n );\n const dimensions = this.dimensions_;\n\n return (\n /**\n * @param {import(\"../tilecoord.js\").TileCoord} tileCoord Tile coordinate.\n * @param {number} pixelRatio Pixel ratio.\n * @param {import(\"../proj/Projection.js\").default} projection Projection.\n * @return {string|undefined} Tile URL.\n */\n function (tileCoord, pixelRatio, projection) {\n if (!tileCoord) {\n return undefined;\n }\n const localContext = {\n 'TileMatrix': tileGrid.getMatrixId(tileCoord[0]),\n 'TileCol': tileCoord[1],\n 'TileRow': tileCoord[2],\n };\n Object.assign(localContext, dimensions);\n let url = template;\n if (requestEncoding == 'KVP') {\n url = appendParams(url, localContext);\n } else {\n url = url.replace(/\\{(\\w+?)\\}/g, function (m, p) {\n return localContext[p];\n });\n }\n return url;\n }\n );\n }\n}\n\nexport default WMTS;\n\n/**\n * Generate source options from a capabilities object.\n * @param {Object} wmtsCap An object representing the capabilities document.\n * @param {!Object} config Configuration properties for the layer. Defaults for\n * the layer will apply if not provided.\n *\n * Required config properties:\n * - layer - {string} The layer identifier.\n *\n * Optional config properties:\n * - matrixSet - {string} The matrix set identifier, required if there is\n * more than one matrix set in the layer capabilities.\n * - projection - {string} The desired CRS when no matrixSet is specified.\n * eg: \"EPSG:3857\". If the desired projection is not available,\n * an error is thrown.\n * - requestEncoding - {string} url encoding format for the layer. Default is\n * the first tile url format found in the GetCapabilities response.\n * - style - {string} The name of the style\n * - format - {string} Image format for the layer. Default is the first\n * format returned in the GetCapabilities response.\n * - crossOrigin - {string|null|undefined} Cross origin. Default is `undefined`.\n * @return {Options|null} WMTS source options object or `null` if the layer was not found.\n * @api\n */\nexport function optionsFromCapabilities(wmtsCap, config) {\n const layers = wmtsCap['Contents']['Layer'];\n const l = layers.find(function (elt) {\n return elt['Identifier'] == config['layer'];\n });\n if (!l) {\n return null;\n }\n const tileMatrixSets = wmtsCap['Contents']['TileMatrixSet'];\n let idx;\n if (l['TileMatrixSetLink'].length > 1) {\n if ('projection' in config) {\n idx = l['TileMatrixSetLink'].findIndex(function (elt) {\n const tileMatrixSet = tileMatrixSets.find(function (el) {\n return el['Identifier'] == elt['TileMatrixSet'];\n });\n const supportedCRS = tileMatrixSet['SupportedCRS'];\n const proj1 = getProjection(supportedCRS);\n const proj2 = getProjection(config['projection']);\n if (proj1 && proj2) {\n return equivalent(proj1, proj2);\n }\n return supportedCRS == config['projection'];\n });\n } else {\n idx = l['TileMatrixSetLink'].findIndex(function (elt) {\n return elt['TileMatrixSet'] == config['matrixSet'];\n });\n }\n } else {\n idx = 0;\n }\n if (idx < 0) {\n idx = 0;\n }\n const matrixSet =\n /** @type {string} */\n (l['TileMatrixSetLink'][idx]['TileMatrixSet']);\n const matrixLimits =\n /** @type {Array} */\n (l['TileMatrixSetLink'][idx]['TileMatrixSetLimits']);\n\n let format = /** @type {string} */ (l['Format'][0]);\n if ('format' in config) {\n format = config['format'];\n }\n idx = l['Style'].findIndex(function (elt) {\n if ('style' in config) {\n return elt['Title'] == config['style'];\n }\n return elt['isDefault'];\n });\n if (idx < 0) {\n idx = 0;\n }\n const style = /** @type {string} */ (l['Style'][idx]['Identifier']);\n\n const dimensions = {};\n if ('Dimension' in l) {\n l['Dimension'].forEach(function (elt, index, array) {\n const key = elt['Identifier'];\n let value = elt['Default'];\n if (value === undefined) {\n value = elt['Value'][0];\n }\n dimensions[key] = value;\n });\n }\n\n const matrixSets = wmtsCap['Contents']['TileMatrixSet'];\n const matrixSetObj = matrixSets.find(function (elt) {\n return elt['Identifier'] == matrixSet;\n });\n\n let projection;\n const code = matrixSetObj['SupportedCRS'];\n if (code) {\n projection = getProjection(code);\n }\n if ('projection' in config) {\n const projConfig = getProjection(config['projection']);\n if (projConfig) {\n if (!projection || equivalent(projConfig, projection)) {\n projection = projConfig;\n }\n }\n }\n\n let wrapX = false;\n const switchXY = projection.getAxisOrientation().substr(0, 2) == 'ne';\n\n let matrix = matrixSetObj.TileMatrix[0];\n\n // create default matrixLimit\n let selectedMatrixLimit = {\n MinTileCol: 0,\n MinTileRow: 0,\n // subtract one to end up at tile top left\n MaxTileCol: matrix.MatrixWidth - 1,\n MaxTileRow: matrix.MatrixHeight - 1,\n };\n\n //in case of matrix limits, use matrix limits to calculate extent\n if (matrixLimits) {\n selectedMatrixLimit = matrixLimits[matrixLimits.length - 1];\n const m = matrixSetObj.TileMatrix.find(\n (tileMatrixValue) =>\n tileMatrixValue.Identifier === selectedMatrixLimit.TileMatrix ||\n matrixSetObj.Identifier + ':' + tileMatrixValue.Identifier ===\n selectedMatrixLimit.TileMatrix\n );\n if (m) {\n matrix = m;\n }\n }\n\n const resolution =\n (matrix.ScaleDenominator * 0.00028) / projection.getMetersPerUnit(); // WMTS 1.0.0: standardized rendering pixel size\n const origin = switchXY\n ? [matrix.TopLeftCorner[1], matrix.TopLeftCorner[0]]\n : matrix.TopLeftCorner;\n const tileSpanX = matrix.TileWidth * resolution;\n const tileSpanY = matrix.TileHeight * resolution;\n let matrixSetExtent = matrixSetObj['BoundingBox'];\n if (matrixSetExtent && switchXY) {\n matrixSetExtent = [\n matrixSetExtent[1],\n matrixSetExtent[0],\n matrixSetExtent[3],\n matrixSetExtent[2],\n ];\n }\n let extent = [\n origin[0] + tileSpanX * selectedMatrixLimit.MinTileCol,\n // add one to get proper bottom/right coordinate\n origin[1] - tileSpanY * (1 + selectedMatrixLimit.MaxTileRow),\n origin[0] + tileSpanX * (1 + selectedMatrixLimit.MaxTileCol),\n origin[1] - tileSpanY * selectedMatrixLimit.MinTileRow,\n ];\n\n if (\n matrixSetExtent !== undefined &&\n !containsExtent(matrixSetExtent, extent)\n ) {\n const wgs84BoundingBox = l['WGS84BoundingBox'];\n const wgs84ProjectionExtent = getProjection('EPSG:4326').getExtent();\n extent = matrixSetExtent;\n if (wgs84BoundingBox) {\n wrapX =\n wgs84BoundingBox[0] === wgs84ProjectionExtent[0] &&\n wgs84BoundingBox[2] === wgs84ProjectionExtent[2];\n } else {\n const wgs84MatrixSetExtent = transformExtent(\n matrixSetExtent,\n matrixSetObj['SupportedCRS'],\n 'EPSG:4326'\n );\n // Ignore slight deviation from the correct x limits\n wrapX =\n wgs84MatrixSetExtent[0] - 1e-10 <= wgs84ProjectionExtent[0] &&\n wgs84MatrixSetExtent[2] + 1e-10 >= wgs84ProjectionExtent[2];\n }\n }\n\n const tileGrid = createFromCapabilitiesMatrixSet(\n matrixSetObj,\n extent,\n matrixLimits\n );\n\n /** @type {!Array} */\n const urls = [];\n let requestEncoding = config['requestEncoding'];\n requestEncoding = requestEncoding !== undefined ? requestEncoding : '';\n\n if (\n 'OperationsMetadata' in wmtsCap &&\n 'GetTile' in wmtsCap['OperationsMetadata']\n ) {\n const gets = wmtsCap['OperationsMetadata']['GetTile']['DCP']['HTTP']['Get'];\n\n for (let i = 0, ii = gets.length; i < ii; ++i) {\n if (gets[i]['Constraint']) {\n const constraint = gets[i]['Constraint'].find(function (element) {\n return element['name'] == 'GetEncoding';\n });\n const encodings = constraint['AllowedValues']['Value'];\n\n if (requestEncoding === '') {\n // requestEncoding not provided, use the first encoding from the list\n requestEncoding = encodings[0];\n }\n if (requestEncoding === 'KVP') {\n if (encodings.includes('KVP')) {\n urls.push(/** @type {string} */ (gets[i]['href']));\n }\n } else {\n break;\n }\n } else if (gets[i]['href']) {\n requestEncoding = 'KVP';\n urls.push(/** @type {string} */ (gets[i]['href']));\n }\n }\n }\n if (urls.length === 0) {\n requestEncoding = 'REST';\n l['ResourceURL'].forEach(function (element) {\n if (element['resourceType'] === 'tile') {\n format = element['format'];\n urls.push(/** @type {string} */ (element['template']));\n }\n });\n }\n\n return {\n urls: urls,\n layer: config['layer'],\n matrixSet: matrixSet,\n format: format,\n projection: projection,\n requestEncoding: requestEncoding,\n tileGrid: tileGrid,\n style: style,\n dimensions: dimensions,\n wrapX: wrapX,\n crossOrigin: config['crossOrigin'],\n };\n}\n","/**\n * @module ol/webgl\n */\n\nimport {SAFARI_BUG_237906} from './has.js';\n\n/**\n * Constants taken from goog.webgl\n */\n\n/**\n * Used by {@link module:ol/webgl/Helper~WebGLHelper} for buffers containing vertices data, such as\n * position, color, texture coordinate, etc. These vertices are then referenced by an index buffer\n * to be drawn on screen (see {@link module:ol/webgl.ELEMENT_ARRAY_BUFFER}).\n * @const\n * @type {number}\n * @api\n */\nexport const ARRAY_BUFFER = 0x8892;\n\n/**\n * Used by {@link module:ol/webgl/Helper~WebGLHelper} for buffers containing indices data.\n * Index buffers are essentially lists of references to vertices defined in a vertex buffer\n * (see {@link module:ol/webgl.ARRAY_BUFFER}), and define the primitives (triangles) to be drawn.\n * @const\n * @type {number}\n * @api\n */\nexport const ELEMENT_ARRAY_BUFFER = 0x8893;\n\n/**\n * Used by {link module:ol/webgl/Buffer~WebGLArrayBuffer}.\n * @const\n * @type {number}\n * @api\n */\nexport const STREAM_DRAW = 0x88e0;\n\n/**\n * Used by {link module:ol/webgl/Buffer~WebGLArrayBuffer}.\n * @const\n * @type {number}\n * @api\n */\nexport const STATIC_DRAW = 0x88e4;\n\n/**\n * Used by {link module:ol/webgl/Buffer~WebGLArrayBuffer}.\n * @const\n * @type {number}\n * @api\n */\nexport const DYNAMIC_DRAW = 0x88e8;\n\n/**\n * @const\n * @type {number}\n */\nexport const UNSIGNED_BYTE = 0x1401;\n\n/**\n * @const\n * @type {number}\n */\nexport const UNSIGNED_SHORT = 0x1403;\n\n/**\n * @const\n * @type {number}\n */\nexport const UNSIGNED_INT = 0x1405;\n\n/**\n * @const\n * @type {number}\n */\nexport const FLOAT = 0x1406;\n\n/** end of goog.webgl constants\n */\n\n/**\n * @const\n * @type {Array}\n */\nconst CONTEXT_IDS = ['experimental-webgl', 'webgl', 'webkit-3d', 'moz-webgl'];\n\n/**\n * @param {HTMLCanvasElement} canvas Canvas.\n * @param {Object} [attributes] Attributes.\n * @return {WebGLRenderingContext} WebGL rendering context.\n */\nexport function getContext(canvas, attributes) {\n attributes = Object.assign(\n {\n preserveDrawingBuffer: true,\n antialias: SAFARI_BUG_237906 ? false : true, // https://bugs.webkit.org/show_bug.cgi?id=237906\n },\n attributes\n );\n const ii = CONTEXT_IDS.length;\n for (let i = 0; i < ii; ++i) {\n try {\n const context = canvas.getContext(CONTEXT_IDS[i], attributes);\n if (context) {\n return /** @type {!WebGLRenderingContext} */ (context);\n }\n } catch (e) {\n // pass\n }\n }\n return null;\n}\n\n/**\n * @type {Array}\n */\nlet supportedExtensions;\n\n/**\n * @return {Array} List of supported WebGL extensions.\n */\nexport function getSupportedExtensions() {\n if (!supportedExtensions) {\n const canvas = document.createElement('canvas');\n const gl = getContext(canvas);\n if (gl) {\n supportedExtensions = gl.getSupportedExtensions();\n }\n }\n return supportedExtensions;\n}\n","/**\n * @module ol/xml\n */\nimport {extend} from './array.js';\n\n/**\n * When using {@link module:ol/xml.makeChildAppender} or\n * {@link module:ol/xml.makeSimpleNodeFactory}, the top `objectStack` item needs\n * to have this structure.\n * @typedef {Object} NodeStackItem\n * @property {Element} node Node.\n */\n\n/**\n * @typedef {function(Element, Array<*>): void} Parser\n */\n\n/**\n * @typedef {function(Element, *, Array<*>): void} Serializer\n */\n\n/**\n * @type {string}\n */\nexport const XML_SCHEMA_INSTANCE_URI =\n 'http://www.w3.org/2001/XMLSchema-instance';\n\n/**\n * @param {string} namespaceURI Namespace URI.\n * @param {string} qualifiedName Qualified name.\n * @return {Element} Node.\n */\nexport function createElementNS(namespaceURI, qualifiedName) {\n return getDocument().createElementNS(namespaceURI, qualifiedName);\n}\n\n/**\n * Recursively grab all text content of child nodes into a single string.\n * @param {Node} node Node.\n * @param {boolean} normalizeWhitespace Normalize whitespace: remove all line\n * breaks.\n * @return {string} All text content.\n * @api\n */\nexport function getAllTextContent(node, normalizeWhitespace) {\n return getAllTextContent_(node, normalizeWhitespace, []).join('');\n}\n\n/**\n * Recursively grab all text content of child nodes into a single string.\n * @param {Node} node Node.\n * @param {boolean} normalizeWhitespace Normalize whitespace: remove all line\n * breaks.\n * @param {Array} accumulator Accumulator.\n * @private\n * @return {Array} Accumulator.\n */\nexport function getAllTextContent_(node, normalizeWhitespace, accumulator) {\n if (\n node.nodeType == Node.CDATA_SECTION_NODE ||\n node.nodeType == Node.TEXT_NODE\n ) {\n if (normalizeWhitespace) {\n accumulator.push(String(node.nodeValue).replace(/(\\r\\n|\\r|\\n)/g, ''));\n } else {\n accumulator.push(node.nodeValue);\n }\n } else {\n let n;\n for (n = node.firstChild; n; n = n.nextSibling) {\n getAllTextContent_(n, normalizeWhitespace, accumulator);\n }\n }\n return accumulator;\n}\n\n/**\n * @param {Object} object Object.\n * @return {boolean} Is a document.\n */\nexport function isDocument(object) {\n return 'documentElement' in object;\n}\n\n/**\n * @param {Element} node Node.\n * @param {?string} namespaceURI Namespace URI.\n * @param {string} name Attribute name.\n * @return {string} Value\n */\nexport function getAttributeNS(node, namespaceURI, name) {\n return node.getAttributeNS(namespaceURI, name) || '';\n}\n\n/**\n * Parse an XML string to an XML Document.\n * @param {string} xml XML.\n * @return {Document} Document.\n * @api\n */\nexport function parse(xml) {\n return new DOMParser().parseFromString(xml, 'application/xml');\n}\n\n/**\n * Make an array extender function for extending the array at the top of the\n * object stack.\n * @param {function(this: T, Node, Array<*>): (Array<*>|undefined)} valueReader Value reader.\n * @param {T} [thisArg] The object to use as `this` in `valueReader`.\n * @return {Parser} Parser.\n * @template T\n */\nexport function makeArrayExtender(valueReader, thisArg) {\n return (\n /**\n * @param {Node} node Node.\n * @param {Array<*>} objectStack Object stack.\n */\n function (node, objectStack) {\n const value = valueReader.call(\n thisArg !== undefined ? thisArg : this,\n node,\n objectStack\n );\n if (value !== undefined) {\n const array = /** @type {Array<*>} */ (\n objectStack[objectStack.length - 1]\n );\n extend(array, value);\n }\n }\n );\n}\n\n/**\n * Make an array pusher function for pushing to the array at the top of the\n * object stack.\n * @param {function(this: T, Element, Array<*>): *} valueReader Value reader.\n * @param {T} [thisArg] The object to use as `this` in `valueReader`.\n * @return {Parser} Parser.\n * @template T\n */\nexport function makeArrayPusher(valueReader, thisArg) {\n return (\n /**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n */\n function (node, objectStack) {\n const value = valueReader.call(\n thisArg !== undefined ? thisArg : this,\n node,\n objectStack\n );\n if (value !== undefined) {\n const array = /** @type {Array<*>} */ (\n objectStack[objectStack.length - 1]\n );\n array.push(value);\n }\n }\n );\n}\n\n/**\n * Make an object stack replacer function for replacing the object at the\n * top of the stack.\n * @param {function(this: T, Node, Array<*>): *} valueReader Value reader.\n * @param {T} [thisArg] The object to use as `this` in `valueReader`.\n * @return {Parser} Parser.\n * @template T\n */\nexport function makeReplacer(valueReader, thisArg) {\n return (\n /**\n * @param {Node} node Node.\n * @param {Array<*>} objectStack Object stack.\n */\n function (node, objectStack) {\n const value = valueReader.call(\n thisArg !== undefined ? thisArg : this,\n node,\n objectStack\n );\n if (value !== undefined) {\n objectStack[objectStack.length - 1] = value;\n }\n }\n );\n}\n\n/**\n * Make an object property pusher function for adding a property to the\n * object at the top of the stack.\n * @param {function(this: T, Element, Array<*>): *} valueReader Value reader.\n * @param {string} [property] Property.\n * @param {T} [thisArg] The object to use as `this` in `valueReader`.\n * @return {Parser} Parser.\n * @template T\n */\nexport function makeObjectPropertyPusher(valueReader, property, thisArg) {\n return (\n /**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n */\n function (node, objectStack) {\n const value = valueReader.call(\n thisArg !== undefined ? thisArg : this,\n node,\n objectStack\n );\n if (value !== undefined) {\n const object = /** @type {!Object} */ (\n objectStack[objectStack.length - 1]\n );\n const name = property !== undefined ? property : node.localName;\n let array;\n if (name in object) {\n array = object[name];\n } else {\n array = [];\n object[name] = array;\n }\n array.push(value);\n }\n }\n );\n}\n\n/**\n * Make an object property setter function.\n * @param {function(this: T, Element, Array<*>): *} valueReader Value reader.\n * @param {string} [property] Property.\n * @param {T} [thisArg] The object to use as `this` in `valueReader`.\n * @return {Parser} Parser.\n * @template T\n */\nexport function makeObjectPropertySetter(valueReader, property, thisArg) {\n return (\n /**\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n */\n function (node, objectStack) {\n const value = valueReader.call(\n thisArg !== undefined ? thisArg : this,\n node,\n objectStack\n );\n if (value !== undefined) {\n const object = /** @type {!Object} */ (\n objectStack[objectStack.length - 1]\n );\n const name = property !== undefined ? property : node.localName;\n object[name] = value;\n }\n }\n );\n}\n\n/**\n * Create a serializer that appends nodes written by its `nodeWriter` to its\n * designated parent. The parent is the `node` of the\n * {@link module:ol/xml~NodeStackItem} at the top of the `objectStack`.\n * @param {function(this: T, Node, V, Array<*>): void} nodeWriter Node writer.\n * @param {T} [thisArg] The object to use as `this` in `nodeWriter`.\n * @return {Serializer} Serializer.\n * @template T, V\n */\nexport function makeChildAppender(nodeWriter, thisArg) {\n return function (node, value, objectStack) {\n nodeWriter.call(\n thisArg !== undefined ? thisArg : this,\n node,\n value,\n objectStack\n );\n const parent = /** @type {NodeStackItem} */ (\n objectStack[objectStack.length - 1]\n );\n const parentNode = parent.node;\n parentNode.appendChild(node);\n };\n}\n\n/**\n * Create a serializer that calls the provided `nodeWriter` from\n * {@link module:ol/xml.serialize}. This can be used by the parent writer to have the\n * `nodeWriter` called with an array of values when the `nodeWriter` was\n * designed to serialize a single item. An example would be a LineString\n * geometry writer, which could be reused for writing MultiLineString\n * geometries.\n * @param {function(this: T, Element, V, Array<*>): void} nodeWriter Node writer.\n * @param {T} [thisArg] The object to use as `this` in `nodeWriter`.\n * @return {Serializer} Serializer.\n * @template T, V\n */\nexport function makeArraySerializer(nodeWriter, thisArg) {\n let serializersNS, nodeFactory;\n return function (node, value, objectStack) {\n if (serializersNS === undefined) {\n serializersNS = {};\n const serializers = {};\n serializers[node.localName] = nodeWriter;\n serializersNS[node.namespaceURI] = serializers;\n nodeFactory = makeSimpleNodeFactory(node.localName);\n }\n serialize(serializersNS, nodeFactory, value, objectStack);\n };\n}\n\n/**\n * Create a node factory which can use the `keys` passed to\n * {@link module:ol/xml.serialize} or {@link module:ol/xml.pushSerializeAndPop} as node names,\n * or a fixed node name. The namespace of the created nodes can either be fixed,\n * or the parent namespace will be used.\n * @param {string} [fixedNodeName] Fixed node name which will be used for all\n * created nodes. If not provided, the 3rd argument to the resulting node\n * factory needs to be provided and will be the nodeName.\n * @param {string} [fixedNamespaceURI] Fixed namespace URI which will be used for\n * all created nodes. If not provided, the namespace of the parent node will\n * be used.\n * @return {function(*, Array<*>, string=): (Node|undefined)} Node factory.\n */\nexport function makeSimpleNodeFactory(fixedNodeName, fixedNamespaceURI) {\n return (\n /**\n * @param {*} value Value.\n * @param {Array<*>} objectStack Object stack.\n * @param {string} [newNodeName] Node name.\n * @return {Node} Node.\n */\n function (value, objectStack, newNodeName) {\n const context = /** @type {NodeStackItem} */ (\n objectStack[objectStack.length - 1]\n );\n const node = context.node;\n let nodeName = fixedNodeName;\n if (nodeName === undefined) {\n nodeName = newNodeName;\n }\n\n const namespaceURI =\n fixedNamespaceURI !== undefined ? fixedNamespaceURI : node.namespaceURI;\n return createElementNS(namespaceURI, /** @type {string} */ (nodeName));\n }\n );\n}\n\n/**\n * A node factory that creates a node using the parent's `namespaceURI` and the\n * `nodeName` passed by {@link module:ol/xml.serialize} or\n * {@link module:ol/xml.pushSerializeAndPop} to the node factory.\n * @const\n * @type {function(*, Array<*>, string=): (Node|undefined)}\n */\nexport const OBJECT_PROPERTY_NODE_FACTORY = makeSimpleNodeFactory();\n\n/**\n * Create an array of `values` to be used with {@link module:ol/xml.serialize} or\n * {@link module:ol/xml.pushSerializeAndPop}, where `orderedKeys` has to be provided as\n * `key` argument.\n * @param {Object} object Key-value pairs for the sequence. Keys can\n * be a subset of the `orderedKeys`.\n * @param {Array} orderedKeys Keys in the order of the sequence.\n * @return {Array<*>} Values in the order of the sequence. The resulting array\n * has the same length as the `orderedKeys` array. Values that are not\n * present in `object` will be `undefined` in the resulting array.\n */\nexport function makeSequence(object, orderedKeys) {\n const length = orderedKeys.length;\n const sequence = new Array(length);\n for (let i = 0; i < length; ++i) {\n sequence[i] = object[orderedKeys[i]];\n }\n return sequence;\n}\n\n/**\n * Create a namespaced structure, using the same values for each namespace.\n * This can be used as a starting point for versioned parsers, when only a few\n * values are version specific.\n * @param {Array} namespaceURIs Namespace URIs.\n * @param {T} structure Structure.\n * @param {Object} [structureNS] Namespaced structure to add to.\n * @return {Object} Namespaced structure.\n * @template T\n */\nexport function makeStructureNS(namespaceURIs, structure, structureNS) {\n structureNS = structureNS !== undefined ? structureNS : {};\n let i, ii;\n for (i = 0, ii = namespaceURIs.length; i < ii; ++i) {\n structureNS[namespaceURIs[i]] = structure;\n }\n return structureNS;\n}\n\n/**\n * Parse a node using the parsers and object stack.\n * @param {Object>} parsersNS\n * Parsers by namespace.\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @param {*} [thisArg] The object to use as `this`.\n */\nexport function parseNode(parsersNS, node, objectStack, thisArg) {\n let n;\n for (n = node.firstElementChild; n; n = n.nextElementSibling) {\n const parsers = parsersNS[n.namespaceURI];\n if (parsers !== undefined) {\n const parser = parsers[n.localName];\n if (parser !== undefined) {\n parser.call(thisArg, n, objectStack);\n }\n }\n }\n}\n\n/**\n * Push an object on top of the stack, parse and return the popped object.\n * @param {T} object Object.\n * @param {Object>} parsersNS\n * Parsers by namespace.\n * @param {Element} node Node.\n * @param {Array<*>} objectStack Object stack.\n * @param {*} [thisArg] The object to use as `this`.\n * @return {T} Object.\n * @template T\n */\nexport function pushParseAndPop(object, parsersNS, node, objectStack, thisArg) {\n objectStack.push(object);\n parseNode(parsersNS, node, objectStack, thisArg);\n return /** @type {T} */ (objectStack.pop());\n}\n\n/**\n * Walk through an array of `values` and call a serializer for each value.\n * @param {Object>} serializersNS\n * Namespaced serializers.\n * @param {function(this: T, *, Array<*>, (string|undefined)): (Node|undefined)} nodeFactory\n * Node factory. The `nodeFactory` creates the node whose namespace and name\n * will be used to choose a node writer from `serializersNS`. This\n * separation allows us to decide what kind of node to create, depending on\n * the value we want to serialize. An example for this would be different\n * geometry writers based on the geometry type.\n * @param {Array<*>} values Values to serialize. An example would be an array\n * of {@link module:ol/Feature~Feature} instances.\n * @param {Array<*>} objectStack Node stack.\n * @param {Array} [keys] Keys of the `values`. Will be passed to the\n * `nodeFactory`. This is used for serializing object literals where the\n * node name relates to the property key. The array length of `keys` has\n * to match the length of `values`. For serializing a sequence, `keys`\n * determines the order of the sequence.\n * @param {T} [thisArg] The object to use as `this` for the node factory and\n * serializers.\n * @template T\n */\nexport function serialize(\n serializersNS,\n nodeFactory,\n values,\n objectStack,\n keys,\n thisArg\n) {\n const length = (keys !== undefined ? keys : values).length;\n let value, node;\n for (let i = 0; i < length; ++i) {\n value = values[i];\n if (value !== undefined) {\n node = nodeFactory.call(\n thisArg !== undefined ? thisArg : this,\n value,\n objectStack,\n keys !== undefined ? keys[i] : undefined\n );\n if (node !== undefined) {\n serializersNS[node.namespaceURI][node.localName].call(\n thisArg,\n node,\n value,\n objectStack\n );\n }\n }\n }\n}\n\n/**\n * @param {O} object Object.\n * @param {Object>} serializersNS\n * Namespaced serializers.\n * @param {function(this: T, *, Array<*>, (string|undefined)): (Node|undefined)} nodeFactory\n * Node factory. The `nodeFactory` creates the node whose namespace and name\n * will be used to choose a node writer from `serializersNS`. This\n * separation allows us to decide what kind of node to create, depending on\n * the value we want to serialize. An example for this would be different\n * geometry writers based on the geometry type.\n * @param {Array<*>} values Values to serialize. An example would be an array\n * of {@link module:ol/Feature~Feature} instances.\n * @param {Array<*>} objectStack Node stack.\n * @param {Array} [keys] Keys of the `values`. Will be passed to the\n * `nodeFactory`. This is used for serializing object literals where the\n * node name relates to the property key. The array length of `keys` has\n * to match the length of `values`. For serializing a sequence, `keys`\n * determines the order of the sequence.\n * @param {T} [thisArg] The object to use as `this` for the node factory and\n * serializers.\n * @return {O|undefined} Object.\n * @template O, T\n */\nexport function pushSerializeAndPop(\n object,\n serializersNS,\n nodeFactory,\n values,\n objectStack,\n keys,\n thisArg\n) {\n objectStack.push(object);\n serialize(serializersNS, nodeFactory, values, objectStack, keys, thisArg);\n return /** @type {O|undefined} */ (objectStack.pop());\n}\n\nlet xmlSerializer_ = undefined;\n\n/**\n * Register a XMLSerializer. Can be used to inject a XMLSerializer\n * where there is no globally available implementation.\n *\n * @param {XMLSerializer} xmlSerializer A XMLSerializer.\n * @api\n */\nexport function registerXMLSerializer(xmlSerializer) {\n xmlSerializer_ = xmlSerializer;\n}\n\n/**\n * @return {XMLSerializer} The XMLSerializer.\n */\nexport function getXMLSerializer() {\n if (xmlSerializer_ === undefined && typeof XMLSerializer !== 'undefined') {\n xmlSerializer_ = new XMLSerializer();\n }\n return xmlSerializer_;\n}\n\nlet document_ = undefined;\n\n/**\n * Register a Document to use when creating nodes for XML serializations. Can be used\n * to inject a Document where there is no globally available implementation.\n *\n * @param {Document} document A Document.\n * @api\n */\nexport function registerDocument(document) {\n document_ = document;\n}\n\n/**\n * Get a document that should be used when creating nodes for XML serializations.\n * @return {Document} The document.\n */\nexport function getDocument() {\n if (document_ === undefined && typeof document !== 'undefined') {\n document_ = document.implementation.createDocument('', '', null);\n }\n return document_;\n}\n","/**\n * @module ol/webgl/BaseTileRepresentation\n */\n\nimport EventTarget from '../events/Target.js';\nimport EventType from '../events/EventType.js';\nimport ImageTile from '../ImageTile.js';\nimport TileState from '../TileState.js';\nimport {abstract} from '../util.js';\n\n/**\n * @typedef {import(\"../Tile.js\").default} BaseTileType\n */\n\n/**\n * @template {BaseTileType} TileType\n * @typedef {Object} TileRepresentationOptions\n * @property {TileType} tile The tile.\n * @property {import(\"../tilegrid/TileGrid.js\").default} grid Tile grid.\n * @property {import(\"../webgl/Helper.js\").default} helper WebGL helper.\n * @property {number} [gutter=0] The size in pixels of the gutter around image tiles to ignore.\n */\n\n/**\n * @classdesc\n * Base class for representing a tile in a webgl context\n * @template {import(\"../Tile.js\").default} TileType\n * @abstract\n */\nclass BaseTileRepresentation extends EventTarget {\n /**\n * @param {TileRepresentationOptions} options The tile representation options.\n */\n constructor(options) {\n super();\n\n /**\n * @type {TileType}\n */\n this.tile;\n this.handleTileChange_ = this.handleTileChange_.bind(this);\n\n /**\n * @type {number}\n * @protected\n */\n this.gutter_ = options.gutter || 0;\n\n /**\n * @type {import(\"../webgl/Helper.js\").default}\n * @protected\n */\n this.helper_ = options.helper;\n\n this.loaded = false;\n this.ready = false;\n }\n\n /**\n * @param {TileType} tile Tile.\n */\n setTile(tile) {\n if (tile !== this.tile) {\n if (this.tile) {\n this.tile.removeEventListener(EventType.CHANGE, this.handleTileChange_);\n }\n this.tile = tile;\n this.loaded = tile.getState() === TileState.LOADED;\n if (this.loaded) {\n this.uploadTile();\n } else {\n if (tile instanceof ImageTile) {\n const image = tile.getImage();\n if (image instanceof Image && !image.crossOrigin) {\n image.crossOrigin = 'anonymous';\n }\n }\n tile.addEventListener(EventType.CHANGE, this.handleTileChange_);\n }\n }\n }\n\n /**\n * @abstract\n * @protected\n */\n uploadTile() {\n abstract();\n }\n\n setReady() {\n this.ready = true;\n this.dispatchEvent(EventType.CHANGE);\n }\n\n handleTileChange_() {\n if (this.tile.getState() === TileState.LOADED) {\n this.loaded = true;\n this.uploadTile();\n }\n }\n\n disposeInternal() {\n this.tile.removeEventListener(EventType.CHANGE, this.handleTileChange_);\n }\n}\n\nexport default BaseTileRepresentation;\n","/**\n * @module ol/webgl/Buffer\n */\nimport {\n ARRAY_BUFFER,\n DYNAMIC_DRAW,\n ELEMENT_ARRAY_BUFFER,\n STATIC_DRAW,\n STREAM_DRAW,\n} from '../webgl.js';\nimport {assert} from '../asserts.js';\n\n/**\n * Used to describe the intended usage for the data: `STATIC_DRAW`, `STREAM_DRAW`\n * or `DYNAMIC_DRAW`.\n * @enum {number}\n */\nexport const BufferUsage = {\n STATIC_DRAW: STATIC_DRAW,\n STREAM_DRAW: STREAM_DRAW,\n DYNAMIC_DRAW: DYNAMIC_DRAW,\n};\n\n/**\n * @classdesc\n * Object used to store an array of data as well as usage information for that data.\n * Stores typed arrays internally, either Float32Array or Uint16/32Array depending on\n * the buffer type (ARRAY_BUFFER or ELEMENT_ARRAY_BUFFER) and available extensions.\n *\n * To populate the array, you can either use:\n * * A size using `#ofSize(buffer)`\n * * An `ArrayBuffer` object using `#fromArrayBuffer(buffer)`\n * * A plain array using `#fromArray(array)`\n *\n * Note:\n * See the documentation of [WebGLRenderingContext.bufferData](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bufferData)\n * for more info on buffer usage.\n * @api\n */\nclass WebGLArrayBuffer {\n /**\n * @param {number} type Buffer type, either ARRAY_BUFFER or ELEMENT_ARRAY_BUFFER.\n * @param {number} [usage] Intended usage, either `STATIC_DRAW`, `STREAM_DRAW` or `DYNAMIC_DRAW`.\n * Default is `DYNAMIC_DRAW`.\n */\n constructor(type, usage) {\n /**\n * @private\n * @type {Float32Array|Uint32Array}\n */\n this.array = null;\n\n /**\n * @private\n * @type {number}\n */\n this.type = type;\n\n assert(type === ARRAY_BUFFER || type === ELEMENT_ARRAY_BUFFER, 62);\n\n /**\n * @private\n * @type {number}\n */\n this.usage = usage !== undefined ? usage : BufferUsage.STATIC_DRAW;\n }\n\n /**\n * Populates the buffer with an array of the given size (all values will be zeroes).\n * @param {number} size Array size\n * @return {WebGLArrayBuffer} This\n */\n ofSize(size) {\n this.array = new (getArrayClassForType(this.type))(size);\n return this;\n }\n\n /**\n * Populates the buffer with an array of the given size.\n * @param {Array} array Numerical array\n * @return {WebGLArrayBuffer} This\n */\n fromArray(array) {\n this.array = getArrayClassForType(this.type).from(array);\n return this;\n }\n\n /**\n * Populates the buffer with a raw binary array buffer.\n * @param {ArrayBuffer} buffer Raw binary buffer to populate the array with. Note that this buffer must have been\n * initialized for the same typed array class.\n * @return {WebGLArrayBuffer} This\n */\n fromArrayBuffer(buffer) {\n this.array = new (getArrayClassForType(this.type))(buffer);\n return this;\n }\n\n /**\n * @return {number} Buffer type.\n */\n getType() {\n return this.type;\n }\n\n /**\n * Will return null if the buffer was not initialized\n * @return {Float32Array|Uint32Array} Array.\n */\n getArray() {\n return this.array;\n }\n\n /**\n * @return {number} Usage.\n */\n getUsage() {\n return this.usage;\n }\n\n /**\n * Will return 0 if the buffer is not initialized\n * @return {number} Array size\n */\n getSize() {\n return this.array ? this.array.length : 0;\n }\n}\n\n/**\n * Returns a typed array constructor based on the given buffer type\n * @param {number} type Buffer type, either ARRAY_BUFFER or ELEMENT_ARRAY_BUFFER.\n * @return {Float32ArrayConstructor|Uint32ArrayConstructor} The typed array class to use for this buffer.\n */\nexport function getArrayClassForType(type) {\n switch (type) {\n case ARRAY_BUFFER:\n return Float32Array;\n case ELEMENT_ARRAY_BUFFER:\n return Uint32Array;\n default:\n return Float32Array;\n }\n}\n\nexport default WebGLArrayBuffer;\n","/**\n * @module ol/webgl/ContextEventType\n */\n\n/**\n * @enum {string}\n */\nexport default {\n LOST: 'webglcontextlost',\n RESTORED: 'webglcontextrestored',\n};\n","/**\n * @module ol/webgl/PostProcessingPass\n */\n\nimport {getUid} from '../util.js';\n\nconst DEFAULT_VERTEX_SHADER = `\n precision mediump float;\n \n attribute vec2 a_position;\n varying vec2 v_texCoord;\n varying vec2 v_screenCoord;\n \n uniform vec2 u_screenSize;\n \n void main() {\n v_texCoord = a_position * 0.5 + 0.5;\n v_screenCoord = v_texCoord * u_screenSize;\n gl_Position = vec4(a_position, 0.0, 1.0);\n }\n`;\n\nconst DEFAULT_FRAGMENT_SHADER = `\n precision mediump float;\n \n uniform sampler2D u_image;\n uniform float u_opacity;\n \n varying vec2 v_texCoord;\n \n void main() {\n gl_FragColor = texture2D(u_image, v_texCoord) * u_opacity;\n }\n`;\n\n/**\n * @typedef {Object} Options\n * @property {WebGLRenderingContext} webGlContext WebGL context; mandatory.\n * @property {number} [scaleRatio] Scale ratio; if < 1, the post process will render to a texture smaller than\n * the main canvas that will then be sampled up (useful for saving resource on blur steps).\n * @property {string} [vertexShader] Vertex shader source\n * @property {string} [fragmentShader] Fragment shader source\n * @property {Object} [uniforms] Uniform definitions for the post process step\n */\n\n/**\n * @typedef {Object} UniformInternalDescription\n * @property {import(\"./Helper\").UniformValue} value Value\n * @property {WebGLUniformLocation} location Location\n * @property {WebGLTexture} [texture] Texture\n * @private\n */\n\n/**\n * @classdesc\n * This class is used to define Post Processing passes with custom shaders and uniforms.\n * This is used internally by {@link module:ol/webgl/Helper~WebGLHelper}.\n *\n * Please note that the final output on the DOM canvas is expected to have premultiplied alpha, which means that\n * a pixel which is 100% red with an opacity of 50% must have a color of (r=0.5, g=0, b=0, a=0.5).\n * Failing to provide pixel colors with premultiplied alpha will result in render anomalies.\n *\n * The default post-processing pass does *not* multiply color values with alpha value, it expects color values to be\n * premultiplied.\n *\n * Default shaders are shown hereafter:\n *\n * * Vertex shader:\n *\n * ```\n * precision mediump float;\n *\n * attribute vec2 a_position;\n * varying vec2 v_texCoord;\n * varying vec2 v_screenCoord;\n *\n * uniform vec2 u_screenSize;\n *\n * void main() {\n * v_texCoord = a_position * 0.5 + 0.5;\n * v_screenCoord = v_texCoord * u_screenSize;\n * gl_Position = vec4(a_position, 0.0, 1.0);\n * }\n * ```\n *\n * * Fragment shader:\n *\n * ```\n * precision mediump float;\n *\n * uniform sampler2D u_image;\n * uniform float u_opacity;\n *\n * varying vec2 v_texCoord;\n *\n * void main() {\n * gl_FragColor = texture2D(u_image, v_texCoord) * u_opacity;\n * }\n * ```\n *\n * @api\n */\nclass WebGLPostProcessingPass {\n /**\n * @param {Options} options Options.\n */\n constructor(options) {\n this.gl_ = options.webGlContext;\n const gl = this.gl_;\n\n this.scaleRatio_ = options.scaleRatio || 1;\n\n this.renderTargetTexture_ = gl.createTexture();\n this.renderTargetTextureSize_ = null;\n\n this.frameBuffer_ = gl.createFramebuffer();\n this.depthBuffer_ = gl.createRenderbuffer();\n\n // compile the program for the frame buffer\n // TODO: make compilation errors show up\n const vertexShader = gl.createShader(gl.VERTEX_SHADER);\n gl.shaderSource(\n vertexShader,\n options.vertexShader || DEFAULT_VERTEX_SHADER\n );\n gl.compileShader(vertexShader);\n const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);\n gl.shaderSource(\n fragmentShader,\n options.fragmentShader || DEFAULT_FRAGMENT_SHADER\n );\n gl.compileShader(fragmentShader);\n this.renderTargetProgram_ = gl.createProgram();\n gl.attachShader(this.renderTargetProgram_, vertexShader);\n gl.attachShader(this.renderTargetProgram_, fragmentShader);\n gl.linkProgram(this.renderTargetProgram_);\n\n // bind the vertices buffer for the frame buffer\n this.renderTargetVerticesBuffer_ = gl.createBuffer();\n const verticesArray = [-1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1];\n gl.bindBuffer(gl.ARRAY_BUFFER, this.renderTargetVerticesBuffer_);\n gl.bufferData(\n gl.ARRAY_BUFFER,\n new Float32Array(verticesArray),\n gl.STATIC_DRAW\n );\n\n this.renderTargetAttribLocation_ = gl.getAttribLocation(\n this.renderTargetProgram_,\n 'a_position'\n );\n this.renderTargetUniformLocation_ = gl.getUniformLocation(\n this.renderTargetProgram_,\n 'u_screenSize'\n );\n this.renderTargetOpacityLocation_ = gl.getUniformLocation(\n this.renderTargetProgram_,\n 'u_opacity'\n );\n this.renderTargetTextureLocation_ = gl.getUniformLocation(\n this.renderTargetProgram_,\n 'u_image'\n );\n\n /**\n * Holds info about custom uniforms used in the post processing pass\n * @type {Array}\n * @private\n */\n this.uniforms_ = [];\n options.uniforms &&\n Object.keys(options.uniforms).forEach((name) => {\n this.uniforms_.push({\n value: options.uniforms[name],\n location: gl.getUniformLocation(this.renderTargetProgram_, name),\n });\n });\n }\n\n /**\n * Get the WebGL rendering context\n * @return {WebGLRenderingContext} The rendering context.\n * @api\n */\n getGL() {\n return this.gl_;\n }\n\n /**\n * Initialize the render target texture of the post process, make sure it is at the\n * right size and bind it as a render target for the next draw calls.\n * The last step to be initialized will be the one where the primitives are rendered.\n * @param {import(\"../Map.js\").FrameState} frameState current frame state\n * @api\n */\n init(frameState) {\n const gl = this.getGL();\n const textureSize = [\n gl.drawingBufferWidth * this.scaleRatio_,\n gl.drawingBufferHeight * this.scaleRatio_,\n ];\n\n // rendering goes to my buffer\n gl.bindFramebuffer(gl.FRAMEBUFFER, this.getFrameBuffer());\n gl.bindRenderbuffer(gl.RENDERBUFFER, this.getDepthBuffer());\n gl.viewport(0, 0, textureSize[0], textureSize[1]);\n\n // if size has changed: adjust canvas & render target texture\n if (\n !this.renderTargetTextureSize_ ||\n this.renderTargetTextureSize_[0] !== textureSize[0] ||\n this.renderTargetTextureSize_[1] !== textureSize[1]\n ) {\n this.renderTargetTextureSize_ = textureSize;\n\n // create a new texture\n const level = 0;\n const internalFormat = gl.RGBA;\n const border = 0;\n const format = gl.RGBA;\n const type = gl.UNSIGNED_BYTE;\n const data = null;\n gl.bindTexture(gl.TEXTURE_2D, this.renderTargetTexture_);\n gl.texImage2D(\n gl.TEXTURE_2D,\n level,\n internalFormat,\n textureSize[0],\n textureSize[1],\n border,\n format,\n type,\n data\n );\n\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n\n // bind the texture to the framebuffer\n gl.framebufferTexture2D(\n gl.FRAMEBUFFER,\n gl.COLOR_ATTACHMENT0,\n gl.TEXTURE_2D,\n this.renderTargetTexture_,\n 0\n );\n\n gl.renderbufferStorage(\n gl.RENDERBUFFER,\n gl.DEPTH_COMPONENT16,\n textureSize[0],\n textureSize[1]\n );\n gl.framebufferRenderbuffer(\n gl.FRAMEBUFFER,\n gl.DEPTH_ATTACHMENT,\n gl.RENDERBUFFER,\n this.depthBuffer_\n );\n }\n }\n\n /**\n * Render to the next postprocessing pass (or to the canvas if final pass).\n * @param {import(\"../Map.js\").FrameState} frameState current frame state\n * @param {WebGLPostProcessingPass} [nextPass] Next pass, optional\n * @param {function(WebGLRenderingContext, import(\"../Map.js\").FrameState):void} [preCompose] Called before composing.\n * @param {function(WebGLRenderingContext, import(\"../Map.js\").FrameState):void} [postCompose] Called before composing.\n * @api\n */\n apply(frameState, nextPass, preCompose, postCompose) {\n const gl = this.getGL();\n const size = frameState.size;\n\n gl.bindFramebuffer(\n gl.FRAMEBUFFER,\n nextPass ? nextPass.getFrameBuffer() : null\n );\n gl.activeTexture(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, this.renderTargetTexture_);\n\n if (!nextPass) {\n // clear the canvas if we are the first to render to it\n // and preserveDrawingBuffer is true\n const canvasId = getUid(gl.canvas);\n if (!frameState.renderTargets[canvasId]) {\n const attributes = gl.getContextAttributes();\n if (attributes && attributes.preserveDrawingBuffer) {\n gl.clearColor(0.0, 0.0, 0.0, 0.0);\n gl.clearDepth(1.0);\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n }\n\n frameState.renderTargets[canvasId] = true;\n }\n }\n\n gl.disable(gl.DEPTH_TEST);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);\n gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);\n\n gl.bindBuffer(gl.ARRAY_BUFFER, this.renderTargetVerticesBuffer_);\n\n gl.useProgram(this.renderTargetProgram_);\n gl.enableVertexAttribArray(this.renderTargetAttribLocation_);\n gl.vertexAttribPointer(\n this.renderTargetAttribLocation_,\n 2,\n gl.FLOAT,\n false,\n 0,\n 0\n );\n gl.uniform2f(this.renderTargetUniformLocation_, size[0], size[1]);\n gl.uniform1i(this.renderTargetTextureLocation_, 0);\n\n const opacity = frameState.layerStatesArray[frameState.layerIndex].opacity;\n gl.uniform1f(this.renderTargetOpacityLocation_, opacity);\n\n this.applyUniforms(frameState);\n\n if (preCompose) {\n preCompose(gl, frameState);\n }\n gl.drawArrays(gl.TRIANGLES, 0, 6);\n if (postCompose) {\n postCompose(gl, frameState);\n }\n }\n\n /**\n * @return {WebGLFramebuffer} Frame buffer\n * @api\n */\n getFrameBuffer() {\n return this.frameBuffer_;\n }\n\n /**\n * @return {WebGLRenderbuffer} Depth buffer\n * @api\n */\n getDepthBuffer() {\n return this.depthBuffer_;\n }\n\n /**\n * Sets the custom uniforms based on what was given in the constructor.\n * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n * @private\n */\n applyUniforms(frameState) {\n const gl = this.getGL();\n\n let value;\n let textureSlot = 1;\n this.uniforms_.forEach(function (uniform) {\n value =\n typeof uniform.value === 'function'\n ? uniform.value(frameState)\n : uniform.value;\n\n // apply value based on type\n if (value instanceof HTMLCanvasElement || value instanceof ImageData) {\n // create a texture & put data\n if (!uniform.texture) {\n uniform.texture = gl.createTexture();\n }\n gl.activeTexture(gl[`TEXTURE${textureSlot}`]);\n gl.bindTexture(gl.TEXTURE_2D, uniform.texture);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n\n if (value instanceof ImageData) {\n gl.texImage2D(\n gl.TEXTURE_2D,\n 0,\n gl.RGBA,\n gl.RGBA,\n value.width,\n value.height,\n 0,\n gl.UNSIGNED_BYTE,\n new Uint8Array(value.data)\n );\n } else {\n gl.texImage2D(\n gl.TEXTURE_2D,\n 0,\n gl.RGBA,\n gl.RGBA,\n gl.UNSIGNED_BYTE,\n value\n );\n }\n\n // fill texture slots\n gl.uniform1i(uniform.location, textureSlot++);\n } else if (Array.isArray(value)) {\n switch (value.length) {\n case 2:\n gl.uniform2f(uniform.location, value[0], value[1]);\n return;\n case 3:\n gl.uniform3f(uniform.location, value[0], value[1], value[2]);\n return;\n case 4:\n gl.uniform4f(\n uniform.location,\n value[0],\n value[1],\n value[2],\n value[3]\n );\n return;\n default:\n return;\n }\n } else if (typeof value === 'number') {\n gl.uniform1f(uniform.location, value);\n }\n });\n }\n}\n\nexport default WebGLPostProcessingPass;\n","/**\n * @module ol/vec/mat4\n */\n\n/**\n * @return {Array} \"4x4 matrix representing a 3D identity transform.\"\n */\nexport function create() {\n return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];\n}\n\n/**\n * @param {Array} mat4 Flattened 4x4 matrix receiving the result.\n * @param {import(\"../transform.js\").Transform} transform Transformation matrix.\n * @return {Array} \"2D transformation matrix as flattened 4x4 matrix.\"\n */\nexport function fromTransform(mat4, transform) {\n mat4[0] = transform[0];\n mat4[1] = transform[1];\n mat4[4] = transform[2];\n mat4[5] = transform[3];\n mat4[12] = transform[4];\n mat4[13] = transform[5];\n return mat4;\n}\n","/**\n * @module ol/webgl/Helper\n */\nimport ContextEventType from '../webgl/ContextEventType.js';\nimport Disposable from '../Disposable.js';\nimport WebGLPostProcessingPass from './PostProcessingPass.js';\nimport {\n FLOAT,\n UNSIGNED_BYTE,\n UNSIGNED_INT,\n UNSIGNED_SHORT,\n getContext,\n} from '../webgl.js';\nimport {clear} from '../obj.js';\nimport {\n compose as composeTransform,\n create as createTransform,\n reset as resetTransform,\n rotate as rotateTransform,\n scale as scaleTransform,\n} from '../transform.js';\nimport {create, fromTransform} from '../vec/mat4.js';\nimport {getUid} from '../util.js';\n\n/**\n * @typedef {Object} BufferCacheEntry\n * @property {import(\"./Buffer.js\").default} buffer Buffer.\n * @property {WebGLBuffer} webGlBuffer WebGlBuffer.\n */\n\n/**\n * Shader types, either `FRAGMENT_SHADER` or `VERTEX_SHADER`.\n * @enum {number}\n */\nexport const ShaderType = {\n FRAGMENT_SHADER: 0x8b30,\n VERTEX_SHADER: 0x8b31,\n};\n\n/**\n * Names of uniforms made available to all shaders.\n * Please note: changing these *will* break custom shaders!\n * @enum {string}\n */\nexport const DefaultUniform = {\n PROJECTION_MATRIX: 'u_projectionMatrix',\n OFFSET_SCALE_MATRIX: 'u_offsetScaleMatrix',\n OFFSET_ROTATION_MATRIX: 'u_offsetRotateMatrix',\n TIME: 'u_time',\n ZOOM: 'u_zoom',\n RESOLUTION: 'u_resolution',\n VIEWPORT_SIZE_PX: 'u_viewportSizePx',\n PIXEL_RATIO: 'u_pixelRatio',\n HIT_DETECTION: 'u_hitDetection',\n};\n\n/**\n * Attribute types, either `UNSIGNED_BYTE`, `UNSIGNED_SHORT`, `UNSIGNED_INT` or `FLOAT`\n * Note: an attribute stored in a `Float32Array` should be of type `FLOAT`.\n * @enum {number}\n */\nexport const AttributeType = {\n UNSIGNED_BYTE: UNSIGNED_BYTE,\n UNSIGNED_SHORT: UNSIGNED_SHORT,\n UNSIGNED_INT: UNSIGNED_INT,\n FLOAT: FLOAT,\n};\n\n/**\n * Description of an attribute in a buffer\n * @typedef {Object} AttributeDescription\n * @property {string} name Attribute name to use in shaders\n * @property {number} size Number of components per attributes\n * @property {AttributeType} [type] Attribute type, i.e. number of bytes used to store the value. This is\n * determined by the class of typed array which the buffer uses (eg. `Float32Array` for a `FLOAT` attribute).\n * Default is `FLOAT`.\n */\n\n/**\n * @typedef {number|Array|HTMLCanvasElement|HTMLImageElement|ImageData|import(\"../transform\").Transform} UniformLiteralValue\n */\n\n/**\n * Uniform value can be a number, array of numbers (2 to 4), canvas element or a callback returning\n * one of the previous types.\n * @typedef {UniformLiteralValue|function(import(\"../Map.js\").FrameState):UniformLiteralValue} UniformValue\n */\n\n/**\n * @typedef {Object} PostProcessesOptions\n * @property {number} [scaleRatio] Scale ratio; if < 1, the post process will render to a texture smaller than\n * the main canvas which will then be sampled up (useful for saving resource on blur steps).\n * @property {string} [vertexShader] Vertex shader source\n * @property {string} [fragmentShader] Fragment shader source\n * @property {Object} [uniforms] Uniform definitions for the post process step\n */\n\n/**\n * @typedef {Object} Options\n * @property {Object} [uniforms] Uniform definitions; property names must match the uniform\n * names in the provided or default shaders.\n * @property {Array} [postProcesses] Post-processes definitions\n * @property {string} [canvasCacheKey] The cache key for the canvas.\n */\n\n/**\n * @typedef {Object} UniformInternalDescription\n * @property {string} name Name\n * @property {UniformValue} [value] Value\n * @property {UniformValue} [prevValue] The previous value.\n * @property {WebGLTexture} [texture] Texture\n * @private\n */\n\n/**\n * @typedef {Object} CanvasCacheItem\n * @property {WebGLRenderingContext} context The context of this canvas.\n * @property {number} users The count of users of this canvas.\n */\n\n/**\n * @type {Object}\n */\nconst canvasCache = {};\n\n/**\n * @param {string} key The cache key for the canvas.\n * @return {string} The shared cache key.\n */\nfunction getSharedCanvasCacheKey(key) {\n return 'shared/' + key;\n}\n\nlet uniqueCanvasCacheKeyCount = 0;\n\n/**\n * @return {string} The unique cache key.\n */\nfunction getUniqueCanvasCacheKey() {\n const key = 'unique/' + uniqueCanvasCacheKeyCount;\n uniqueCanvasCacheKeyCount += 1;\n return key;\n}\n\n/**\n * @param {string} key The cache key for the canvas.\n * @return {WebGLRenderingContext} The canvas.\n */\nfunction getOrCreateContext(key) {\n let cacheItem = canvasCache[key];\n if (!cacheItem) {\n const canvas = document.createElement('canvas');\n canvas.width = 1;\n canvas.height = 1;\n canvas.style.position = 'absolute';\n canvas.style.left = '0';\n const context = getContext(canvas);\n cacheItem = {users: 0, context};\n canvasCache[key] = cacheItem;\n }\n\n cacheItem.users += 1;\n return cacheItem.context;\n}\n\n/**\n * @param {string} key The cache key for the canvas.\n */\nfunction releaseCanvas(key) {\n const cacheItem = canvasCache[key];\n if (!cacheItem) {\n return;\n }\n\n cacheItem.users -= 1;\n if (cacheItem.users > 0) {\n return;\n }\n\n const gl = cacheItem.context;\n const extension = gl.getExtension('WEBGL_lose_context');\n if (extension) {\n extension.loseContext();\n }\n const canvas = gl.canvas;\n canvas.width = 1;\n canvas.height = 1;\n\n delete canvasCache[key];\n}\n\n/**\n * @classdesc\n * This class is intended to provide low-level functions related to WebGL rendering, so that accessing\n * directly the WebGL API should not be required anymore.\n *\n * Several operations are handled by the `WebGLHelper` class:\n *\n * ### Define custom shaders and uniforms\n *\n * *Shaders* are low-level programs executed on the GPU and written in GLSL. There are two types of shaders:\n *\n * Vertex shaders are used to manipulate the position and attribute of *vertices* of rendered primitives (ie. corners of a square).\n * Outputs are:\n *\n * * `gl_Position`: position of the vertex in screen space\n *\n * * Varyings usually prefixed with `v_` are passed on to the fragment shader\n *\n * Fragment shaders are used to control the actual color of the pixels drawn on screen. Their only output is `gl_FragColor`.\n *\n * Both shaders can take *uniforms* or *attributes* as input. Attributes are explained later. Uniforms are common, read-only values that\n * can be changed at every frame and can be of type float, arrays of float or images.\n *\n * Shaders must be compiled and assembled into a program like so:\n * ```js\n * // here we simply create two shaders and assemble them in a program which is then used\n * // for subsequent rendering calls; note how a frameState is required to set up a program,\n * // as several default uniforms are computed from it (projection matrix, zoom level, etc.)\n * const vertexShader = new WebGLVertex(VERTEX_SHADER);\n * const fragmentShader = new WebGLFragment(FRAGMENT_SHADER);\n * const program = this.context.getProgram(fragmentShader, vertexShader);\n * helper.useProgram(this.program, frameState);\n * ```\n *\n * Uniforms are defined using the `uniforms` option and can either be explicit values or callbacks taking the frame state as argument.\n * You can also change their value along the way like so:\n * ```js\n * helper.setUniformFloatValue('u_value', valueAsNumber);\n * ```\n *\n * ### Defining post processing passes\n *\n * *Post processing* describes the act of rendering primitives to a texture, and then rendering this texture to the final canvas\n * while applying special effects in screen space.\n * Typical uses are: blurring, color manipulation, depth of field, filtering...\n *\n * The `WebGLHelper` class offers the possibility to define post processes at creation time using the `postProcesses` option.\n * A post process step accepts the following options:\n *\n * * `fragmentShader` and `vertexShader`: text literals in GLSL language that will be compiled and used in the post processing step.\n * * `uniforms`: uniforms can be defined for the post processing steps just like for the main render.\n * * `scaleRatio`: allows using an intermediate texture smaller or higher than the final canvas in the post processing step.\n * This is typically used in blur steps to reduce the performance overhead by using an already downsampled texture as input.\n *\n * The {@link module:ol/webgl/PostProcessingPass~WebGLPostProcessingPass} class is used internally, refer to its documentation for more info.\n *\n * ### Binding WebGL buffers and flushing data into them\n *\n * Data that must be passed to the GPU has to be transferred using {@link module:ol/webgl/Buffer~WebGLArrayBuffer} objects.\n * A buffer has to be created only once, but must be bound every time the buffer content will be used for rendering.\n * This is done using {@link bindBuffer}.\n * When the buffer's array content has changed, the new data has to be flushed to the GPU memory; this is done using\n * {@link flushBufferData}. Note: this operation is expensive and should be done as infrequently as possible.\n *\n * When binding an array buffer, a `target` parameter must be given: it should be either {@link module:ol/webgl.ARRAY_BUFFER}\n * (if the buffer contains vertices data) or {@link module:ol/webgl.ELEMENT_ARRAY_BUFFER} (if the buffer contains indices data).\n *\n * Examples below:\n * ```js\n * // at initialization phase\n * const verticesBuffer = new WebGLArrayBuffer([], DYNAMIC_DRAW);\n * const indicesBuffer = new WebGLArrayBuffer([], DYNAMIC_DRAW);\n *\n * // when array values have changed\n * helper.flushBufferData(ARRAY_BUFFER, this.verticesBuffer);\n * helper.flushBufferData(ELEMENT_ARRAY_BUFFER, this.indicesBuffer);\n *\n * // at rendering phase\n * helper.bindBuffer(ARRAY_BUFFER, this.verticesBuffer);\n * helper.bindBuffer(ELEMENT_ARRAY_BUFFER, this.indicesBuffer);\n * ```\n *\n * ### Specifying attributes\n *\n * The GPU only receives the data as arrays of numbers. These numbers must be handled differently depending on what it describes (position, texture coordinate...).\n * Attributes are used to specify these uses. Specify the attribute names with\n * {@link module:ol/webgl/Helper~WebGLHelper#enableAttributes} (see code snippet below).\n *\n * Please note that you will have to specify the type and offset of the attributes in the data array. You can refer to the documentation of [WebGLRenderingContext.vertexAttribPointer](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/vertexAttribPointer) for more explanation.\n * ```js\n * // here we indicate that the data array has the following structure:\n * // [posX, posY, offsetX, offsetY, texCoordU, texCoordV, posX, posY, ...]\n * helper.enableAttributes([\n * {\n * name: 'a_position',\n * size: 2\n * },\n * {\n * name: 'a_offset',\n * size: 2\n * },\n * {\n * name: 'a_texCoord',\n * size: 2\n * }\n * ])\n * ```\n *\n * ### Rendering primitives\n *\n * Once all the steps above have been achieved, rendering primitives to the screen is done using {@link prepareDraw}, {@link drawElements} and {@link finalizeDraw}.\n * ```js\n * // frame preparation step\n * helper.prepareDraw(frameState);\n *\n * // call this for every data array that has to be rendered on screen\n * helper.drawElements(0, this.indicesBuffer.getArray().length);\n *\n * // finalize the rendering by applying post processes\n * helper.finalizeDraw(frameState);\n * ```\n *\n * For an example usage of this class, refer to {@link module:ol/renderer/webgl/PointsLayer~WebGLPointsLayerRenderer}.\n */\nclass WebGLHelper extends Disposable {\n /**\n * @param {Options} [options] Options.\n */\n constructor(options) {\n super();\n options = options || {};\n\n /** @private */\n this.boundHandleWebGLContextLost_ = this.handleWebGLContextLost.bind(this);\n\n /** @private */\n this.boundHandleWebGLContextRestored_ =\n this.handleWebGLContextRestored.bind(this);\n\n /**\n * @private\n * @type {string}\n */\n this.canvasCacheKey_ = options.canvasCacheKey\n ? getSharedCanvasCacheKey(options.canvasCacheKey)\n : getUniqueCanvasCacheKey();\n\n /**\n * @private\n * @type {WebGLRenderingContext}\n */\n this.gl_ = getOrCreateContext(this.canvasCacheKey_);\n\n /**\n * @private\n * @type {!Object}\n */\n this.bufferCache_ = {};\n\n /**\n * @private\n * @type {Object}\n */\n this.extensionCache_ = {};\n\n /**\n * @private\n * @type {WebGLProgram}\n */\n this.currentProgram_ = null;\n\n const canvas = this.gl_.canvas;\n\n canvas.addEventListener(\n ContextEventType.LOST,\n this.boundHandleWebGLContextLost_\n );\n canvas.addEventListener(\n ContextEventType.RESTORED,\n this.boundHandleWebGLContextRestored_\n );\n\n /**\n * @private\n * @type {import(\"../transform.js\").Transform}\n */\n this.offsetRotateMatrix_ = createTransform();\n\n /**\n * @private\n * @type {import(\"../transform.js\").Transform}\n */\n this.offsetScaleMatrix_ = createTransform();\n\n /**\n * @private\n * @type {Array}\n */\n this.tmpMat4_ = create();\n\n /**\n * @private\n * @type {Object>}\n */\n this.uniformLocationsByProgram_ = {};\n\n /**\n * @private\n * @type {Object>}\n */\n this.attribLocationsByProgram_ = {};\n\n /**\n * Holds info about custom uniforms used in the post processing pass.\n * If the uniform is a texture, the WebGL Texture object will be stored here.\n * @type {Array}\n * @private\n */\n this.uniforms_ = [];\n if (options.uniforms) {\n this.setUniforms(options.uniforms);\n }\n\n /**\n * An array of PostProcessingPass objects is kept in this variable, built from the steps provided in the\n * options. If no post process was given, a default one is used (so as not to have to make an exception to\n * the frame buffer logic).\n * @type {Array}\n * @private\n */\n this.postProcessPasses_ = options.postProcesses\n ? options.postProcesses.map(\n (options) =>\n new WebGLPostProcessingPass({\n webGlContext: this.gl_,\n scaleRatio: options.scaleRatio,\n vertexShader: options.vertexShader,\n fragmentShader: options.fragmentShader,\n uniforms: options.uniforms,\n })\n )\n : [new WebGLPostProcessingPass({webGlContext: this.gl_})];\n\n /**\n * @type {string|null}\n * @private\n */\n this.shaderCompileErrors_ = null;\n\n /**\n * @type {number}\n * @private\n */\n this.startTime_ = Date.now();\n }\n\n /**\n * @param {Object} uniforms Uniform definitions.\n */\n setUniforms(uniforms) {\n this.uniforms_ = [];\n for (const name in uniforms) {\n this.uniforms_.push({\n name: name,\n value: uniforms[name],\n });\n }\n }\n\n /**\n * @param {string} canvasCacheKey The canvas cache key.\n * @return {boolean} The provided key matches the one this helper was constructed with.\n */\n canvasCacheKeyMatches(canvasCacheKey) {\n return this.canvasCacheKey_ === getSharedCanvasCacheKey(canvasCacheKey);\n }\n\n /**\n * Get a WebGL extension. If the extension is not supported, null is returned.\n * Extensions are cached after they are enabled for the first time.\n * @param {string} name The extension name.\n * @return {Object|null} The extension or null if not supported.\n */\n getExtension(name) {\n if (name in this.extensionCache_) {\n return this.extensionCache_[name];\n }\n const extension = this.gl_.getExtension(name);\n this.extensionCache_[name] = extension;\n return extension;\n }\n\n /**\n * Just bind the buffer if it's in the cache. Otherwise create\n * the WebGL buffer, bind it, populate it, and add an entry to\n * the cache.\n * @param {import(\"./Buffer\").default} buffer Buffer.\n */\n bindBuffer(buffer) {\n const gl = this.gl_;\n const bufferKey = getUid(buffer);\n let bufferCache = this.bufferCache_[bufferKey];\n if (!bufferCache) {\n const webGlBuffer = gl.createBuffer();\n bufferCache = {\n buffer: buffer,\n webGlBuffer: webGlBuffer,\n };\n this.bufferCache_[bufferKey] = bufferCache;\n }\n gl.bindBuffer(buffer.getType(), bufferCache.webGlBuffer);\n }\n\n /**\n * Update the data contained in the buffer array; this is required for the\n * new data to be rendered\n * @param {import(\"./Buffer\").default} buffer Buffer.\n */\n flushBufferData(buffer) {\n const gl = this.gl_;\n this.bindBuffer(buffer);\n gl.bufferData(buffer.getType(), buffer.getArray(), buffer.getUsage());\n }\n\n /**\n * @param {import(\"./Buffer.js\").default} buf Buffer.\n */\n deleteBuffer(buf) {\n const gl = this.gl_;\n const bufferKey = getUid(buf);\n const bufferCacheEntry = this.bufferCache_[bufferKey];\n if (bufferCacheEntry && !gl.isContextLost()) {\n gl.deleteBuffer(bufferCacheEntry.webGlBuffer);\n }\n delete this.bufferCache_[bufferKey];\n }\n\n /**\n * Clean up.\n */\n disposeInternal() {\n const canvas = this.gl_.canvas;\n canvas.removeEventListener(\n ContextEventType.LOST,\n this.boundHandleWebGLContextLost_\n );\n canvas.removeEventListener(\n ContextEventType.RESTORED,\n this.boundHandleWebGLContextRestored_\n );\n\n releaseCanvas(this.canvasCacheKey_);\n\n delete this.gl_;\n }\n\n /**\n * Clear the buffer & set the viewport to draw.\n * Post process passes will be initialized here, the first one being bound as a render target for\n * subsequent draw calls.\n * @param {import(\"../Map.js\").FrameState} frameState current frame state\n * @param {boolean} [disableAlphaBlend] If true, no alpha blending will happen.\n * @param {boolean} [enableDepth] If true, enables depth testing.\n */\n prepareDraw(frameState, disableAlphaBlend, enableDepth) {\n const gl = this.gl_;\n const canvas = this.getCanvas();\n const size = frameState.size;\n const pixelRatio = frameState.pixelRatio;\n\n if (\n canvas.width !== size[0] * pixelRatio ||\n canvas.height !== size[1] * pixelRatio\n ) {\n canvas.width = size[0] * pixelRatio;\n canvas.height = size[1] * pixelRatio;\n canvas.style.width = size[0] + 'px';\n canvas.style.height = size[1] + 'px';\n }\n\n // loop backwards in post processes list\n for (let i = this.postProcessPasses_.length - 1; i >= 0; i--) {\n this.postProcessPasses_[i].init(frameState);\n }\n\n gl.bindTexture(gl.TEXTURE_2D, null);\n\n gl.clearColor(0.0, 0.0, 0.0, 0.0);\n gl.depthRange(0.0, 1.0);\n gl.clearDepth(1.0);\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE, disableAlphaBlend ? gl.ZERO : gl.ONE_MINUS_SRC_ALPHA);\n if (enableDepth) {\n gl.enable(gl.DEPTH_TEST);\n gl.depthFunc(gl.LEQUAL);\n } else {\n gl.disable(gl.DEPTH_TEST);\n }\n }\n\n /**\n * Prepare a program to use a texture.\n * @param {WebGLTexture} texture The texture.\n * @param {number} slot The texture slot.\n * @param {string} uniformName The corresponding uniform name.\n */\n bindTexture(texture, slot, uniformName) {\n const gl = this.gl_;\n gl.activeTexture(gl.TEXTURE0 + slot);\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.uniform1i(this.getUniformLocation(uniformName), slot);\n }\n\n /**\n * Clear the render target & bind it for future draw operations.\n * This is similar to `prepareDraw`, only post processes will not be applied.\n * Note: the whole viewport will be drawn to the render target, regardless of its size.\n * @param {import(\"../Map.js\").FrameState} frameState current frame state\n * @param {import(\"./RenderTarget.js\").default} renderTarget Render target to draw to\n * @param {boolean} [disableAlphaBlend] If true, no alpha blending will happen.\n * @param {boolean} [enableDepth] If true, enables depth testing.\n */\n prepareDrawToRenderTarget(\n frameState,\n renderTarget,\n disableAlphaBlend,\n enableDepth\n ) {\n const gl = this.gl_;\n const size = renderTarget.getSize();\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, renderTarget.getFramebuffer());\n gl.bindRenderbuffer(gl.RENDERBUFFER, renderTarget.getDepthbuffer());\n gl.viewport(0, 0, size[0], size[1]);\n gl.bindTexture(gl.TEXTURE_2D, renderTarget.getTexture());\n gl.clearColor(0.0, 0.0, 0.0, 0.0);\n gl.depthRange(0.0, 1.0);\n gl.clearDepth(1.0);\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n gl.enable(gl.BLEND);\n gl.blendFunc(gl.ONE, disableAlphaBlend ? gl.ZERO : gl.ONE_MINUS_SRC_ALPHA);\n if (enableDepth) {\n gl.enable(gl.DEPTH_TEST);\n gl.depthFunc(gl.LEQUAL);\n } else {\n gl.disable(gl.DEPTH_TEST);\n }\n }\n\n /**\n * Execute a draw call based on the currently bound program, texture, buffers, attributes.\n * @param {number} start Start index.\n * @param {number} end End index.\n */\n drawElements(start, end) {\n const gl = this.gl_;\n this.getExtension('OES_element_index_uint');\n\n const elementType = gl.UNSIGNED_INT;\n const elementSize = 4;\n\n const numItems = end - start;\n const offsetInBytes = start * elementSize;\n gl.drawElements(gl.TRIANGLES, numItems, elementType, offsetInBytes);\n }\n\n /**\n * Apply the successive post process passes which will eventually render to the actual canvas.\n * @param {import(\"../Map.js\").FrameState} frameState current frame state\n * @param {function(WebGLRenderingContext, import(\"../Map.js\").FrameState):void} [preCompose] Called before composing.\n * @param {function(WebGLRenderingContext, import(\"../Map.js\").FrameState):void} [postCompose] Called before composing.\n */\n finalizeDraw(frameState, preCompose, postCompose) {\n // apply post processes using the next one as target\n for (let i = 0, ii = this.postProcessPasses_.length; i < ii; i++) {\n if (i === ii - 1) {\n this.postProcessPasses_[i].apply(\n frameState,\n null,\n preCompose,\n postCompose\n );\n } else {\n this.postProcessPasses_[i].apply(\n frameState,\n this.postProcessPasses_[i + 1]\n );\n }\n }\n }\n\n /**\n * @return {HTMLCanvasElement} Canvas.\n */\n getCanvas() {\n return /** @type {HTMLCanvasElement} */ (this.gl_.canvas);\n }\n\n /**\n * Get the WebGL rendering context\n * @return {WebGLRenderingContext} The rendering context.\n */\n getGL() {\n return this.gl_;\n }\n\n /**\n * Sets the default matrix uniforms for a given frame state. This is called internally in `prepareDraw`.\n * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n */\n applyFrameState(frameState) {\n const size = frameState.size;\n const rotation = frameState.viewState.rotation;\n const pixelRatio = frameState.pixelRatio;\n\n const offsetScaleMatrix = resetTransform(this.offsetScaleMatrix_);\n scaleTransform(offsetScaleMatrix, 2 / size[0], 2 / size[1]);\n\n const offsetRotateMatrix = resetTransform(this.offsetRotateMatrix_);\n if (rotation !== 0) {\n rotateTransform(offsetRotateMatrix, -rotation);\n }\n\n this.setUniformMatrixValue(\n DefaultUniform.OFFSET_SCALE_MATRIX,\n fromTransform(this.tmpMat4_, offsetScaleMatrix)\n );\n this.setUniformMatrixValue(\n DefaultUniform.OFFSET_ROTATION_MATRIX,\n fromTransform(this.tmpMat4_, offsetRotateMatrix)\n );\n\n this.setUniformFloatValue(\n DefaultUniform.TIME,\n (Date.now() - this.startTime_) * 0.001\n );\n this.setUniformFloatValue(DefaultUniform.ZOOM, frameState.viewState.zoom);\n this.setUniformFloatValue(\n DefaultUniform.RESOLUTION,\n frameState.viewState.resolution\n );\n this.setUniformFloatValue(DefaultUniform.PIXEL_RATIO, pixelRatio);\n this.setUniformFloatVec2(DefaultUniform.VIEWPORT_SIZE_PX, [\n size[0],\n size[1],\n ]);\n }\n\n /**\n * Sets the `u_hitDetection` uniform.\n * @param {boolean} enabled Whether to enable the hit detection code path\n */\n applyHitDetectionUniform(enabled) {\n const loc = this.getUniformLocation(DefaultUniform.HIT_DETECTION);\n this.getGL().uniform1i(loc, enabled ? 1 : 0);\n }\n\n /**\n * Sets the custom uniforms based on what was given in the constructor. This is called internally in `prepareDraw`.\n * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n */\n applyUniforms(frameState) {\n const gl = this.gl_;\n\n let value;\n let textureSlot = 0;\n this.uniforms_.forEach((uniform) => {\n value =\n typeof uniform.value === 'function'\n ? uniform.value(frameState)\n : uniform.value;\n\n // apply value based on type\n if (\n value instanceof HTMLCanvasElement ||\n value instanceof HTMLImageElement ||\n value instanceof ImageData\n ) {\n // create a texture & put data\n if (!uniform.texture) {\n uniform.prevValue = undefined;\n uniform.texture = gl.createTexture();\n }\n gl.activeTexture(gl[`TEXTURE${textureSlot}`]);\n gl.bindTexture(gl.TEXTURE_2D, uniform.texture);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n\n const imageReady =\n !(value instanceof HTMLImageElement) ||\n /** @type {HTMLImageElement} */ (value).complete;\n if (imageReady && uniform.prevValue !== value) {\n uniform.prevValue = value;\n gl.texImage2D(\n gl.TEXTURE_2D,\n 0,\n gl.RGBA,\n gl.RGBA,\n gl.UNSIGNED_BYTE,\n value\n );\n }\n\n // fill texture slots by increasing index\n gl.uniform1i(this.getUniformLocation(uniform.name), textureSlot++);\n } else if (Array.isArray(value) && value.length === 6) {\n this.setUniformMatrixValue(\n uniform.name,\n fromTransform(this.tmpMat4_, value)\n );\n } else if (Array.isArray(value) && value.length <= 4) {\n switch (value.length) {\n case 2:\n gl.uniform2f(\n this.getUniformLocation(uniform.name),\n value[0],\n value[1]\n );\n return;\n case 3:\n gl.uniform3f(\n this.getUniformLocation(uniform.name),\n value[0],\n value[1],\n value[2]\n );\n return;\n case 4:\n gl.uniform4f(\n this.getUniformLocation(uniform.name),\n value[0],\n value[1],\n value[2],\n value[3]\n );\n return;\n default:\n return;\n }\n } else if (typeof value === 'number') {\n gl.uniform1f(this.getUniformLocation(uniform.name), value);\n }\n });\n }\n\n /**\n * Set up a program for use. The program will be set as the current one. Then, the uniforms used\n * in the program will be set based on the current frame state and the helper configuration.\n * @param {WebGLProgram} program Program.\n * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n */\n useProgram(program, frameState) {\n const gl = this.gl_;\n gl.useProgram(program);\n this.currentProgram_ = program;\n this.applyFrameState(frameState);\n this.applyUniforms(frameState);\n }\n\n /**\n * Will attempt to compile a vertex or fragment shader based on source\n * On error, the shader will be returned but\n * `gl.getShaderParameter(shader, gl.COMPILE_STATUS)` will return `true`\n * Use `gl.getShaderInfoLog(shader)` to have details\n * @param {string} source Shader source\n * @param {ShaderType} type VERTEX_SHADER or FRAGMENT_SHADER\n * @return {WebGLShader} Shader object\n */\n compileShader(source, type) {\n const gl = this.gl_;\n const shader = gl.createShader(type);\n gl.shaderSource(shader, source);\n gl.compileShader(shader);\n return shader;\n }\n\n /**\n * Create a program for a vertex and fragment shader. Throws if shader compilation fails.\n * @param {string} fragmentShaderSource Fragment shader source.\n * @param {string} vertexShaderSource Vertex shader source.\n * @return {WebGLProgram} Program\n */\n getProgram(fragmentShaderSource, vertexShaderSource) {\n const gl = this.gl_;\n\n const fragmentShader = this.compileShader(\n fragmentShaderSource,\n gl.FRAGMENT_SHADER\n );\n\n const vertexShader = this.compileShader(\n vertexShaderSource,\n gl.VERTEX_SHADER\n );\n\n const program = gl.createProgram();\n gl.attachShader(program, fragmentShader);\n gl.attachShader(program, vertexShader);\n gl.linkProgram(program);\n\n if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {\n const message = `Fragment shader compilation failed: ${gl.getShaderInfoLog(\n fragmentShader\n )}`;\n throw new Error(message);\n }\n gl.deleteShader(fragmentShader);\n\n if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {\n const message = `Vertex shader compilation failed: ${gl.getShaderInfoLog(\n vertexShader\n )}`;\n throw new Error(message);\n }\n gl.deleteShader(vertexShader);\n\n if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {\n const message = `GL program linking failed: ${gl.getProgramInfoLog(\n program\n )}`;\n throw new Error(message);\n }\n\n return program;\n }\n\n /**\n * Will get the location from the shader or the cache\n * @param {string} name Uniform name\n * @return {WebGLUniformLocation} uniformLocation\n */\n getUniformLocation(name) {\n const programUid = getUid(this.currentProgram_);\n if (this.uniformLocationsByProgram_[programUid] === undefined) {\n this.uniformLocationsByProgram_[programUid] = {};\n }\n if (this.uniformLocationsByProgram_[programUid][name] === undefined) {\n this.uniformLocationsByProgram_[programUid][name] =\n this.gl_.getUniformLocation(this.currentProgram_, name);\n }\n return this.uniformLocationsByProgram_[programUid][name];\n }\n\n /**\n * Will get the location from the shader or the cache\n * @param {string} name Attribute name\n * @return {number} attribLocation\n */\n getAttributeLocation(name) {\n const programUid = getUid(this.currentProgram_);\n if (this.attribLocationsByProgram_[programUid] === undefined) {\n this.attribLocationsByProgram_[programUid] = {};\n }\n if (this.attribLocationsByProgram_[programUid][name] === undefined) {\n this.attribLocationsByProgram_[programUid][name] =\n this.gl_.getAttribLocation(this.currentProgram_, name);\n }\n return this.attribLocationsByProgram_[programUid][name];\n }\n\n /**\n * Sets the given transform to apply the rotation/translation/scaling of the given frame state.\n * The resulting transform can be used to convert world space coordinates to view coordinates in the [-1, 1] range.\n * @param {import(\"../Map.js\").FrameState} frameState Frame state.\n * @param {import(\"../transform\").Transform} transform Transform to update.\n * @return {import(\"../transform\").Transform} The updated transform object.\n */\n makeProjectionTransform(frameState, transform) {\n const size = frameState.size;\n const rotation = frameState.viewState.rotation;\n const resolution = frameState.viewState.resolution;\n const center = frameState.viewState.center;\n composeTransform(\n transform,\n 0,\n 0,\n 2 / (resolution * size[0]),\n 2 / (resolution * size[1]),\n -rotation,\n -center[0],\n -center[1]\n );\n return transform;\n }\n\n /**\n * Give a value for a standard float uniform\n * @param {string} uniform Uniform name\n * @param {number} value Value\n */\n setUniformFloatValue(uniform, value) {\n this.gl_.uniform1f(this.getUniformLocation(uniform), value);\n }\n\n /**\n * Give a value for a vec2 uniform\n * @param {string} uniform Uniform name\n * @param {Array} value Array of length 4.\n */\n setUniformFloatVec2(uniform, value) {\n this.gl_.uniform2fv(this.getUniformLocation(uniform), value);\n }\n\n /**\n * Give a value for a vec4 uniform\n * @param {string} uniform Uniform name\n * @param {Array} value Array of length 4.\n */\n setUniformFloatVec4(uniform, value) {\n this.gl_.uniform4fv(this.getUniformLocation(uniform), value);\n }\n\n /**\n * Give a value for a standard matrix4 uniform\n * @param {string} uniform Uniform name\n * @param {Array} value Matrix value\n */\n setUniformMatrixValue(uniform, value) {\n this.gl_.uniformMatrix4fv(this.getUniformLocation(uniform), false, value);\n }\n\n /**\n * Will set the currently bound buffer to an attribute of the shader program. Used by `#enableAttributes`\n * internally.\n * @param {string} attribName Attribute name\n * @param {number} size Number of components per attributes\n * @param {number} type UNSIGNED_INT, UNSIGNED_BYTE, UNSIGNED_SHORT or FLOAT\n * @param {number} stride Stride in bytes (0 means attribs are packed)\n * @param {number} offset Offset in bytes\n * @private\n */\n enableAttributeArray_(attribName, size, type, stride, offset) {\n const location = this.getAttributeLocation(attribName);\n // the attribute has not been found in the shaders or is not used; do not enable it\n if (location < 0) {\n return;\n }\n this.gl_.enableVertexAttribArray(location);\n this.gl_.vertexAttribPointer(location, size, type, false, stride, offset);\n }\n\n /**\n * Will enable the following attributes to be read from the currently bound buffer,\n * i.e. tell the GPU where to read the different attributes in the buffer. An error in the\n * size/type/order of attributes will most likely break the rendering and throw a WebGL exception.\n * @param {Array} attributes Ordered list of attributes to read from the buffer\n */\n enableAttributes(attributes) {\n const stride = computeAttributesStride(attributes);\n let offset = 0;\n for (let i = 0; i < attributes.length; i++) {\n const attr = attributes[i];\n this.enableAttributeArray_(\n attr.name,\n attr.size,\n attr.type || FLOAT,\n stride,\n offset\n );\n offset += attr.size * getByteSizeFromType(attr.type);\n }\n }\n\n /**\n * WebGL context was lost\n * @private\n */\n handleWebGLContextLost() {\n clear(this.bufferCache_);\n this.currentProgram_ = null;\n }\n\n /**\n * WebGL context was restored\n * @private\n */\n handleWebGLContextRestored() {}\n\n /**\n * Will create or reuse a given webgl texture and apply the given size. If no image data\n * specified, the texture will be empty, otherwise image data will be used and the `size`\n * parameter will be ignored.\n * Note: wrap parameters are set to clamp to edge, min filter is set to linear.\n * @param {Array} size Expected size of the texture\n * @param {ImageData|HTMLImageElement|HTMLCanvasElement} [data] Image data/object to bind to the texture\n * @param {WebGLTexture} [texture] Existing texture to reuse\n * @return {WebGLTexture} The generated texture\n */\n createTexture(size, data, texture) {\n const gl = this.gl_;\n texture = texture || gl.createTexture();\n\n // set params & size\n const level = 0;\n const internalFormat = gl.RGBA;\n const border = 0;\n const format = gl.RGBA;\n const type = gl.UNSIGNED_BYTE;\n gl.bindTexture(gl.TEXTURE_2D, texture);\n if (data) {\n gl.texImage2D(gl.TEXTURE_2D, level, internalFormat, format, type, data);\n } else {\n gl.texImage2D(\n gl.TEXTURE_2D,\n level,\n internalFormat,\n size[0],\n size[1],\n border,\n format,\n type,\n null\n );\n }\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n\n return texture;\n }\n}\n\n/**\n * Compute a stride in bytes based on a list of attributes\n * @param {Array} attributes Ordered list of attributes\n * @return {number} Stride, ie amount of values for each vertex in the vertex buffer\n */\nexport function computeAttributesStride(attributes) {\n let stride = 0;\n for (let i = 0; i < attributes.length; i++) {\n const attr = attributes[i];\n stride += attr.size * getByteSizeFromType(attr.type);\n }\n return stride;\n}\n\n/**\n * Computes the size in byte of an attribute type.\n * @param {AttributeType} type Attribute type\n * @return {number} The size in bytes\n */\nfunction getByteSizeFromType(type) {\n switch (type) {\n case AttributeType.UNSIGNED_BYTE:\n return Uint8Array.BYTES_PER_ELEMENT;\n case AttributeType.UNSIGNED_SHORT:\n return Uint16Array.BYTES_PER_ELEMENT;\n case AttributeType.UNSIGNED_INT:\n return Uint32Array.BYTES_PER_ELEMENT;\n case AttributeType.FLOAT:\n default:\n return Float32Array.BYTES_PER_ELEMENT;\n }\n}\n\nexport default WebGLHelper;\n","/**\n * @module ol/webgl/PaletteTexture\n */\n\nclass PaletteTexture {\n /**\n * @param {string} name The name of the texture.\n * @param {Uint8Array} data The texture data.\n */\n constructor(name, data) {\n this.name = name;\n this.data = data;\n\n /**\n * @type {WebGLTexture}\n * @private\n */\n this.texture_ = null;\n }\n\n /**\n * @param {WebGLRenderingContext} gl Rendering context.\n * @return {WebGLTexture} The texture.\n */\n getTexture(gl) {\n if (!this.texture_) {\n const texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);\n gl.texImage2D(\n gl.TEXTURE_2D,\n 0,\n gl.RGBA,\n this.data.length / 4,\n 1,\n 0,\n gl.RGBA,\n gl.UNSIGNED_BYTE,\n this.data\n );\n this.texture_ = texture;\n }\n return this.texture_;\n }\n}\n\nexport default PaletteTexture;\n","/**\n * A wrapper class to simplify rendering to a texture instead of the final canvas\n * @module ol/webgl/RenderTarget\n */\nimport {equals} from '../array.js';\n\n// for pixel color reading\nconst tmpArray4 = new Uint8Array(4);\n\n/**\n * @classdesc\n * This class is a wrapper around the association of both a `WebGLTexture` and a `WebGLFramebuffer` instances,\n * simplifying initialization and binding for rendering.\n * @api\n */\nclass WebGLRenderTarget {\n /**\n * @param {import(\"./Helper.js\").default} helper WebGL helper; mandatory.\n * @param {Array} [size] Expected size of the render target texture; note: this can be changed later on.\n */\n constructor(helper, size) {\n /**\n * @private\n * @type {import(\"./Helper.js\").default}\n */\n this.helper_ = helper;\n const gl = helper.getGL();\n\n /**\n * @private\n * @type {WebGLTexture}\n */\n this.texture_ = gl.createTexture();\n\n /**\n * @private\n * @type {WebGLFramebuffer}\n */\n this.framebuffer_ = gl.createFramebuffer();\n\n /**\n * @private\n * @type {WebGLRenderbuffer}\n */\n this.depthbuffer_ = gl.createRenderbuffer();\n\n /**\n * @type {Array}\n * @private\n */\n this.size_ = size || [1, 1];\n\n /**\n * @type {Uint8Array}\n * @private\n */\n this.data_ = new Uint8Array(0);\n\n /**\n * @type {boolean}\n * @private\n */\n this.dataCacheDirty_ = true;\n\n this.updateSize_();\n }\n\n /**\n * Changes the size of the render target texture. Note: will do nothing if the size\n * is already the same.\n * @param {Array} size Expected size of the render target texture\n * @api\n */\n setSize(size) {\n if (equals(size, this.size_)) {\n return;\n }\n this.size_[0] = size[0];\n this.size_[1] = size[1];\n this.updateSize_();\n }\n\n /**\n * Returns the size of the render target texture\n * @return {Array} Size of the render target texture\n * @api\n */\n getSize() {\n return this.size_;\n }\n\n /**\n * This will cause following calls to `#readAll` or `#readPixel` to download the content of the\n * render target into memory, which is an expensive operation.\n * This content will be kept in cache but should be cleared after each new render.\n * @api\n */\n clearCachedData() {\n this.dataCacheDirty_ = true;\n }\n\n /**\n * Returns the full content of the frame buffer as a series of r, g, b, a components\n * in the 0-255 range (unsigned byte).\n * @return {Uint8Array} Integer array of color values\n * @api\n */\n readAll() {\n if (this.dataCacheDirty_) {\n const size = this.size_;\n const gl = this.helper_.getGL();\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer_);\n gl.readPixels(\n 0,\n 0,\n size[0],\n size[1],\n gl.RGBA,\n gl.UNSIGNED_BYTE,\n this.data_\n );\n this.dataCacheDirty_ = false;\n }\n return this.data_;\n }\n\n /**\n * Reads one pixel of the frame buffer as an array of r, g, b, a components\n * in the 0-255 range (unsigned byte).\n * If x and/or y are outside of existing data, an array filled with 0 is returned.\n * @param {number} x Pixel coordinate\n * @param {number} y Pixel coordinate\n * @return {Uint8Array} Integer array with one color value (4 components)\n * @api\n */\n readPixel(x, y) {\n if (x < 0 || y < 0 || x > this.size_[0] || y >= this.size_[1]) {\n tmpArray4[0] = 0;\n tmpArray4[1] = 0;\n tmpArray4[2] = 0;\n tmpArray4[3] = 0;\n return tmpArray4;\n }\n\n this.readAll();\n const index =\n Math.floor(x) + (this.size_[1] - Math.floor(y) - 1) * this.size_[0];\n tmpArray4[0] = this.data_[index * 4];\n tmpArray4[1] = this.data_[index * 4 + 1];\n tmpArray4[2] = this.data_[index * 4 + 2];\n tmpArray4[3] = this.data_[index * 4 + 3];\n return tmpArray4;\n }\n\n /**\n * @return {WebGLTexture} Texture to render to\n */\n getTexture() {\n return this.texture_;\n }\n\n /**\n * @return {WebGLFramebuffer} Frame buffer of the render target\n */\n getFramebuffer() {\n return this.framebuffer_;\n }\n\n /**\n * @return {WebGLRenderbuffer} Depth buffer of the render target\n */\n getDepthbuffer() {\n return this.depthbuffer_;\n }\n\n /**\n * @private\n */\n updateSize_() {\n const size = this.size_;\n const gl = this.helper_.getGL();\n\n this.texture_ = this.helper_.createTexture(size, null, this.texture_);\n\n gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer_);\n gl.viewport(0, 0, size[0], size[1]);\n gl.framebufferTexture2D(\n gl.FRAMEBUFFER,\n gl.COLOR_ATTACHMENT0,\n gl.TEXTURE_2D,\n this.texture_,\n 0\n );\n\n gl.bindRenderbuffer(gl.RENDERBUFFER, this.depthbuffer_);\n gl.renderbufferStorage(\n gl.RENDERBUFFER,\n gl.DEPTH_COMPONENT16,\n size[0],\n size[1]\n );\n gl.framebufferRenderbuffer(\n gl.FRAMEBUFFER,\n gl.DEPTH_ATTACHMENT,\n gl.RENDERBUFFER,\n this.depthbuffer_\n );\n\n this.data_ = new Uint8Array(size[0] * size[1] * 4);\n }\n}\n\nexport default WebGLRenderTarget;\n","/**\n * @module ol/webgl/TileTexture\n */\n\nimport BaseTileRepresentation from './BaseTileRepresentation.js';\nimport DataTile, {asArrayLike, asImageLike} from '../DataTile.js';\nimport EventType from '../events/EventType.js';\nimport ImageTile from '../ImageTile.js';\nimport ReprojTile from '../reproj/Tile.js';\nimport WebGLArrayBuffer from './Buffer.js';\nimport {ARRAY_BUFFER, STATIC_DRAW} from '../webgl.js';\nimport {createCanvasContext2D} from '../dom.js';\nimport {toSize} from '../size.js';\n\n/**\n * @param {WebGLRenderingContext} gl The WebGL context.\n * @param {WebGLTexture} texture The texture.\n * @param {boolean} interpolate Interpolate when resampling.\n */\nfunction bindAndConfigure(gl, texture, interpolate) {\n const resampleFilter = interpolate ? gl.LINEAR : gl.NEAREST;\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, resampleFilter);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, resampleFilter);\n}\n\n/**\n * @param {WebGLRenderingContext} gl The WebGL context.\n * @param {WebGLTexture} texture The texture.\n * @param {import(\"../DataTile.js\").ImageLike} image The image.\n * @param {boolean} interpolate Interpolate when resampling.\n */\nfunction uploadImageTexture(gl, texture, image, interpolate) {\n bindAndConfigure(gl, texture, interpolate);\n\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);\n}\n\n/**\n * @param {import(\"./Helper.js\").default} helper The WebGL helper.\n * @param {WebGLTexture} texture The texture.\n * @param {import(\"../DataTile.js\").ArrayLike} data The pixel data.\n * @param {import(\"../size.js\").Size} size The pixel size.\n * @param {number} bandCount The band count.\n * @param {boolean} interpolate Interpolate when resampling.\n */\nfunction uploadDataTexture(\n helper,\n texture,\n data,\n size,\n bandCount,\n interpolate\n) {\n const gl = helper.getGL();\n let textureType;\n let canInterpolate;\n if (data instanceof Float32Array) {\n textureType = gl.FLOAT;\n helper.getExtension('OES_texture_float');\n const extension = helper.getExtension('OES_texture_float_linear');\n canInterpolate = extension !== null;\n } else {\n textureType = gl.UNSIGNED_BYTE;\n canInterpolate = true;\n }\n bindAndConfigure(gl, texture, interpolate && canInterpolate);\n\n const bytesPerRow = data.byteLength / size[1];\n let unpackAlignment = 1;\n if (bytesPerRow % 8 === 0) {\n unpackAlignment = 8;\n } else if (bytesPerRow % 4 === 0) {\n unpackAlignment = 4;\n } else if (bytesPerRow % 2 === 0) {\n unpackAlignment = 2;\n }\n\n let format;\n switch (bandCount) {\n case 1: {\n format = gl.LUMINANCE;\n break;\n }\n case 2: {\n format = gl.LUMINANCE_ALPHA;\n break;\n }\n case 3: {\n format = gl.RGB;\n break;\n }\n case 4: {\n format = gl.RGBA;\n break;\n }\n default: {\n throw new Error(`Unsupported number of bands: ${bandCount}`);\n }\n }\n\n const oldUnpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);\n gl.pixelStorei(gl.UNPACK_ALIGNMENT, unpackAlignment);\n gl.texImage2D(\n gl.TEXTURE_2D,\n 0,\n format,\n size[0],\n size[1],\n 0,\n format,\n textureType,\n data\n );\n gl.pixelStorei(gl.UNPACK_ALIGNMENT, oldUnpackAlignment);\n}\n\n/**\n * @type {CanvasRenderingContext2D}\n */\nlet pixelContext = null;\n\nfunction createPixelContext() {\n pixelContext = createCanvasContext2D(1, 1, undefined, {\n willReadFrequently: true,\n });\n}\n\n/**\n * @typedef {import(\"../DataTile.js\").default|ImageTile|ReprojTile} TileType\n */\n\n/**\n * @extends {BaseTileRepresentation}\n */\nclass TileTexture extends BaseTileRepresentation {\n /**\n * @param {import(\"./BaseTileRepresentation.js\").TileRepresentationOptions} options The tile texture options.\n */\n constructor(options) {\n super(options);\n\n /**\n * @type {Array}\n */\n this.textures = [];\n\n /**\n * @type {import(\"../size.js\").Size}\n * @private\n */\n this.renderSize_ = toSize(\n options.grid.getTileSize(options.tile.tileCoord[0])\n );\n\n /**\n * @type {number}\n */\n this.bandCount = NaN;\n\n const coords = new WebGLArrayBuffer(ARRAY_BUFFER, STATIC_DRAW);\n coords.fromArray([\n 0, // P0\n 1,\n 1, // P1\n 1,\n 1, // P2\n 0,\n 0, // P3\n 0,\n ]);\n this.helper_.flushBufferData(coords);\n\n /**\n * @type {WebGLArrayBuffer}\n */\n this.coords = coords;\n\n this.setTile(options.tile);\n }\n\n uploadTile() {\n const helper = this.helper_;\n const gl = helper.getGL();\n const tile = this.tile;\n\n this.textures.length = 0;\n\n /**\n * @type {import(\"../DataTile.js\").Data}\n */\n let data;\n\n if (tile instanceof ImageTile || tile instanceof ReprojTile) {\n data = tile.getImage();\n } else {\n data = tile.getData();\n }\n\n const image = asImageLike(data);\n if (image) {\n const texture = gl.createTexture();\n this.textures.push(texture);\n this.bandCount = 4;\n uploadImageTexture(gl, texture, image, tile.interpolate);\n this.setReady();\n return;\n }\n\n data = asArrayLike(data);\n\n const sourceTileSize = /** @type {DataTile} */ (tile).getSize();\n const pixelSize = [\n sourceTileSize[0] + 2 * this.gutter_,\n sourceTileSize[1] + 2 * this.gutter_,\n ];\n const isFloat = data instanceof Float32Array;\n const pixelCount = pixelSize[0] * pixelSize[1];\n const DataType = isFloat ? Float32Array : Uint8Array;\n const bytesPerElement = DataType.BYTES_PER_ELEMENT;\n const bytesPerRow = data.byteLength / pixelSize[1];\n\n this.bandCount = Math.floor(bytesPerRow / bytesPerElement / pixelSize[0]);\n const textureCount = Math.ceil(this.bandCount / 4);\n\n if (textureCount === 1) {\n const texture = gl.createTexture();\n this.textures.push(texture);\n uploadDataTexture(\n helper,\n texture,\n data,\n pixelSize,\n this.bandCount,\n tile.interpolate\n );\n this.setReady();\n return;\n }\n\n const textureDataArrays = new Array(textureCount);\n for (let textureIndex = 0; textureIndex < textureCount; ++textureIndex) {\n const texture = gl.createTexture();\n this.textures.push(texture);\n\n const bandCount =\n textureIndex < textureCount - 1 ? 4 : ((this.bandCount - 1) % 4) + 1;\n textureDataArrays[textureIndex] = new DataType(pixelCount * bandCount);\n }\n\n let dataIndex = 0;\n let rowOffset = 0;\n const colCount = pixelSize[0] * this.bandCount;\n for (let rowIndex = 0; rowIndex < pixelSize[1]; ++rowIndex) {\n for (let colIndex = 0; colIndex < colCount; ++colIndex) {\n const dataValue = data[rowOffset + colIndex];\n\n const pixelIndex = Math.floor(dataIndex / this.bandCount);\n const bandIndex = colIndex % this.bandCount;\n const textureIndex = Math.floor(bandIndex / 4);\n const textureData = textureDataArrays[textureIndex];\n const bandCount = textureData.length / pixelCount;\n const textureBandIndex = bandIndex % 4;\n textureData[pixelIndex * bandCount + textureBandIndex] = dataValue;\n\n ++dataIndex;\n }\n rowOffset += bytesPerRow / bytesPerElement;\n }\n\n for (let textureIndex = 0; textureIndex < textureCount; ++textureIndex) {\n const texture = this.textures[textureIndex];\n const textureData = textureDataArrays[textureIndex];\n const bandCount = textureData.length / pixelCount;\n uploadDataTexture(\n helper,\n texture,\n textureData,\n pixelSize,\n bandCount,\n tile.interpolate\n );\n }\n\n this.setReady();\n }\n\n disposeInternal() {\n const gl = this.helper_.getGL();\n this.helper_.deleteBuffer(this.coords);\n for (let i = 0; i < this.textures.length; ++i) {\n gl.deleteTexture(this.textures[i]);\n }\n this.tile.removeEventListener(EventType.CHANGE, this.handleTileChange_);\n }\n\n /**\n * @param {import(\"../DataTile.js\").ImageLike} image The image.\n * @param {number} renderCol The column index (in rendered tile space).\n * @param {number} renderRow The row index (in rendered tile space).\n * @return {Uint8ClampedArray|null} The data.\n * @private\n */\n getImagePixelData_(image, renderCol, renderRow) {\n const gutter = this.gutter_;\n const renderWidth = this.renderSize_[0];\n const renderHeight = this.renderSize_[1];\n\n if (!pixelContext) {\n createPixelContext();\n }\n pixelContext.clearRect(0, 0, 1, 1);\n\n const sourceWidth = image.width;\n const sourceHeight = image.height;\n\n const sourceWidthWithoutGutter = sourceWidth - 2 * gutter;\n const sourceHeightWithoutGutter = sourceHeight - 2 * gutter;\n\n const sourceCol =\n gutter + Math.floor(sourceWidthWithoutGutter * (renderCol / renderWidth));\n\n const sourceRow =\n gutter +\n Math.floor(sourceHeightWithoutGutter * (renderRow / renderHeight));\n\n let data;\n try {\n pixelContext.drawImage(image, sourceCol, sourceRow, 1, 1, 0, 0, 1, 1);\n data = pixelContext.getImageData(0, 0, 1, 1).data;\n } catch (err) {\n pixelContext = null;\n return null;\n }\n return data;\n }\n\n /**\n * @param {import(\"../DataTile.js\").ArrayLike} data The data.\n * @param {import(\"../size.js\").Size} sourceSize The size.\n * @param {number} renderCol The column index (in rendered tile space).\n * @param {number} renderRow The row index (in rendered tile space).\n * @return {import(\"../DataTile.js\").ArrayLike|null} The data.\n * @private\n */\n getArrayPixelData_(data, sourceSize, renderCol, renderRow) {\n const gutter = this.gutter_;\n const renderWidth = this.renderSize_[0];\n const renderHeight = this.renderSize_[1];\n\n const sourceWidthWithoutGutter = sourceSize[0];\n const sourceHeightWithoutGutter = sourceSize[1];\n const sourceWidth = sourceWidthWithoutGutter + 2 * gutter;\n const sourceHeight = sourceHeightWithoutGutter + 2 * gutter;\n\n const sourceCol =\n gutter + Math.floor(sourceWidthWithoutGutter * (renderCol / renderWidth));\n\n const sourceRow =\n gutter +\n Math.floor(sourceHeightWithoutGutter * (renderRow / renderHeight));\n\n if (data instanceof DataView) {\n const bytesPerPixel = data.byteLength / (sourceWidth * sourceHeight);\n const offset = bytesPerPixel * (sourceRow * sourceWidth + sourceCol);\n const buffer = data.buffer.slice(offset, offset + bytesPerPixel);\n return new DataView(buffer);\n }\n\n const offset = this.bandCount * (sourceRow * sourceWidth + sourceCol);\n return data.slice(offset, offset + this.bandCount);\n }\n\n /**\n * Get data for a pixel. If the tile is not loaded, null is returned.\n * @param {number} renderCol The column index (in rendered tile space).\n * @param {number} renderRow The row index (in rendered tile space).\n * @return {import(\"../DataTile.js\").ArrayLike|null} The data.\n */\n getPixelData(renderCol, renderRow) {\n if (!this.loaded) {\n return null;\n }\n\n if (this.tile instanceof DataTile) {\n const data = this.tile.getData();\n const arrayData = asArrayLike(data);\n if (arrayData) {\n const sourceSize = this.tile.getSize();\n return this.getArrayPixelData_(\n arrayData,\n sourceSize,\n renderCol,\n renderRow\n );\n }\n return this.getImagePixelData_(asImageLike(data), renderCol, renderRow);\n }\n\n return this.getImagePixelData_(this.tile.getImage(), renderCol, renderRow);\n }\n}\n\nexport default TileTexture;\n","/**\n * @module ol/renderer/webgl/Layer\n */\nimport LayerProperty from '../../layer/Property.js';\nimport LayerRenderer from '../Layer.js';\nimport RenderEvent from '../../render/Event.js';\nimport RenderEventType from '../../render/EventType.js';\nimport WebGLHelper from '../../webgl/Helper.js';\nimport {\n compose as composeTransform,\n create as createTransform,\n} from '../../transform.js';\n\n/**\n * @typedef {Object} PostProcessesOptions\n * @property {number} [scaleRatio] Scale ratio; if < 1, the post process will render to a texture smaller than\n * the main canvas that will then be sampled up (useful for saving resource on blur steps).\n * @property {string} [vertexShader] Vertex shader source\n * @property {string} [fragmentShader] Fragment shader source\n * @property {Object} [uniforms] Uniform definitions for the post process step\n */\n\n/**\n * @typedef {Object} Options\n * @property {Object} [uniforms] Uniform definitions for the post process steps\n * @property {Array} [postProcesses] Post-processes definitions\n */\n\n/**\n * @classdesc\n * Base WebGL renderer class.\n * Holds all logic related to data manipulation & some common rendering logic\n * @template {import(\"../../layer/Layer.js\").default} LayerType\n * @extends {LayerRenderer}\n */\nclass WebGLLayerRenderer extends LayerRenderer {\n /**\n * @param {LayerType} layer Layer.\n * @param {Options} [options] Options.\n */\n constructor(layer, options) {\n super(layer);\n\n options = options || {};\n\n /**\n * The transform for viewport CSS pixels to rendered pixels. This transform is only\n * set before dispatching rendering events.\n * @private\n * @type {import(\"../../transform.js\").Transform}\n */\n this.inversePixelTransform_ = createTransform();\n\n /**\n * @private\n * @type {CanvasRenderingContext2D}\n */\n this.pixelContext_ = null;\n\n /**\n * @private\n */\n this.postProcesses_ = options.postProcesses;\n\n /**\n * @private\n */\n this.uniforms_ = options.uniforms;\n\n /**\n * @type {WebGLHelper}\n * @protected\n */\n this.helper;\n\n layer.addChangeListener(LayerProperty.MAP, this.removeHelper.bind(this));\n\n this.dispatchPreComposeEvent = this.dispatchPreComposeEvent.bind(this);\n this.dispatchPostComposeEvent = this.dispatchPostComposeEvent.bind(this);\n }\n\n /**\n * @param {WebGLRenderingContext} context The WebGL rendering context.\n * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n * @protected\n */\n dispatchPreComposeEvent(context, frameState) {\n const layer = this.getLayer();\n if (layer.hasListener(RenderEventType.PRECOMPOSE)) {\n const event = new RenderEvent(\n RenderEventType.PRECOMPOSE,\n undefined,\n frameState,\n context\n );\n layer.dispatchEvent(event);\n }\n }\n\n /**\n * @param {WebGLRenderingContext} context The WebGL rendering context.\n * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n * @protected\n */\n dispatchPostComposeEvent(context, frameState) {\n const layer = this.getLayer();\n if (layer.hasListener(RenderEventType.POSTCOMPOSE)) {\n const event = new RenderEvent(\n RenderEventType.POSTCOMPOSE,\n undefined,\n frameState,\n context\n );\n layer.dispatchEvent(event);\n }\n }\n\n /**\n * Reset options (only handles uniforms).\n * @param {Options} options Options.\n */\n reset(options) {\n this.uniforms_ = options.uniforms;\n if (this.helper) {\n this.helper.setUniforms(this.uniforms_);\n }\n }\n\n /**\n * @protected\n */\n removeHelper() {\n if (this.helper) {\n this.helper.dispose();\n delete this.helper;\n }\n }\n\n /**\n * Determine whether renderFrame should be called.\n * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n * @return {boolean} Layer is ready to be rendered.\n */\n prepareFrame(frameState) {\n if (this.getLayer().getRenderSource()) {\n let incrementGroup = true;\n let groupNumber = -1;\n let className;\n for (let i = 0, ii = frameState.layerStatesArray.length; i < ii; i++) {\n const layer = frameState.layerStatesArray[i].layer;\n const renderer = layer.getRenderer();\n if (!(renderer instanceof WebGLLayerRenderer)) {\n incrementGroup = true;\n continue;\n }\n const layerClassName = layer.getClassName();\n if (incrementGroup || layerClassName !== className) {\n groupNumber += 1;\n incrementGroup = false;\n }\n className = layerClassName;\n if (renderer === this) {\n break;\n }\n }\n\n const canvasCacheKey =\n 'map/' + frameState.mapId + '/group/' + groupNumber;\n\n if (!this.helper || !this.helper.canvasCacheKeyMatches(canvasCacheKey)) {\n this.removeHelper();\n\n this.helper = new WebGLHelper({\n postProcesses: this.postProcesses_,\n uniforms: this.uniforms_,\n canvasCacheKey: canvasCacheKey,\n });\n\n if (className) {\n this.helper.getCanvas().className = className;\n }\n\n this.afterHelperCreated();\n }\n }\n\n return this.prepareFrameInternal(frameState);\n }\n\n /**\n * @protected\n */\n afterHelperCreated() {}\n\n /**\n * Determine whether renderFrame should be called.\n * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n * @return {boolean} Layer is ready to be rendered.\n * @protected\n */\n prepareFrameInternal(frameState) {\n return true;\n }\n\n /**\n * Clean up.\n */\n disposeInternal() {\n this.removeHelper();\n super.disposeInternal();\n }\n\n /**\n * @param {import(\"../../render/EventType.js\").default} type Event type.\n * @param {WebGLRenderingContext} context The rendering context.\n * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n * @private\n */\n dispatchRenderEvent_(type, context, frameState) {\n const layer = this.getLayer();\n if (layer.hasListener(type)) {\n composeTransform(\n this.inversePixelTransform_,\n 0,\n 0,\n frameState.pixelRatio,\n -frameState.pixelRatio,\n 0,\n 0,\n -frameState.size[1]\n );\n\n const event = new RenderEvent(\n type,\n this.inversePixelTransform_,\n frameState,\n context\n );\n layer.dispatchEvent(event);\n }\n }\n\n /**\n * @param {WebGLRenderingContext} context The rendering context.\n * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n * @protected\n */\n preRender(context, frameState) {\n this.dispatchRenderEvent_(RenderEventType.PRERENDER, context, frameState);\n }\n\n /**\n * @param {WebGLRenderingContext} context The rendering context.\n * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n * @protected\n */\n postRender(context, frameState) {\n this.dispatchRenderEvent_(RenderEventType.POSTRENDER, context, frameState);\n }\n}\n\nexport default WebGLLayerRenderer;\n","/**\n * @module ol/renderer/webgl/TileLayerBase\n */\nimport LRUCache from '../../structs/LRUCache.js';\nimport ReprojDataTile from '../../reproj/DataTile.js';\nimport ReprojTile from '../../reproj/Tile.js';\nimport TileRange from '../../TileRange.js';\nimport TileState from '../../TileState.js';\nimport WebGLLayerRenderer from './Layer.js';\nimport {abstract, getUid} from '../../util.js';\nimport {create as createMat4} from '../../vec/mat4.js';\nimport {\n createOrUpdate as createTileCoord,\n getKey as getTileCoordKey,\n} from '../../tilecoord.js';\nimport {\n create as createTransform,\n reset as resetTransform,\n rotate as rotateTransform,\n scale as scaleTransform,\n translate as translateTransform,\n} from '../../transform.js';\nimport {descending} from '../../array.js';\nimport {fromUserExtent} from '../../proj.js';\nimport {getIntersection, isEmpty} from '../../extent.js';\nimport {toSize} from '../../size.js';\n\nexport const Uniforms = {\n TILE_TRANSFORM: 'u_tileTransform',\n TRANSITION_ALPHA: 'u_transitionAlpha',\n DEPTH: 'u_depth',\n RENDER_EXTENT: 'u_renderExtent', // intersection of layer, source, and view extent\n RESOLUTION: 'u_resolution',\n ZOOM: 'u_zoom',\n GLOBAL_ALPHA: 'u_globalAlpha',\n PROJECTION_MATRIX: 'u_projectionMatrix',\n SCREEN_TO_WORLD_MATRIX: 'u_screenToWorldMatrix',\n};\n\n/**\n * @type {Object}\n */\nconst empty = {};\n\n/**\n * Transform a zoom level into a depth value ranging from -1 to 1.\n * @param {number} z A zoom level.\n * @return {number} A depth value.\n */\nfunction depthForZ(z) {\n return 1 / (z + 2);\n}\n\n/**\n * @typedef {import(\"../../webgl/BaseTileRepresentation.js\").default} AbstractTileRepresentation\n */\n/**\n * @typedef {Object} TileRepresentationLookup\n * @property {Set} tileIds The set of tile ids in the lookup.\n * @property {Object>} representationsByZ Tile representations by zoom level.\n */\n\n/**\n * @return {TileRepresentationLookup} A new tile representation lookup.\n */\nexport function newTileRepresentationLookup() {\n return {tileIds: new Set(), representationsByZ: {}};\n}\n\n/**\n * Check if a tile is already in the tile representation lookup.\n * @param {TileRepresentationLookup} tileRepresentationLookup Lookup of tile representations by zoom level.\n * @param {import(\"../../Tile.js\").default} tile A tile.\n * @return {boolean} The tile is already in the lookup.\n */\nfunction lookupHasTile(tileRepresentationLookup, tile) {\n return tileRepresentationLookup.tileIds.has(getUid(tile));\n}\n\n/**\n * Add a tile representation to the lookup.\n * @param {TileRepresentationLookup} tileRepresentationLookup Lookup of tile representations by zoom level.\n * @param {AbstractTileRepresentation} tileRepresentation A tile representation.\n * @param {number} z The zoom level.\n */\nfunction addTileRepresentationToLookup(\n tileRepresentationLookup,\n tileRepresentation,\n z\n) {\n const representationsByZ = tileRepresentationLookup.representationsByZ;\n if (!(z in representationsByZ)) {\n representationsByZ[z] = new Set();\n }\n representationsByZ[z].add(tileRepresentation);\n tileRepresentationLookup.tileIds.add(getUid(tileRepresentation.tile));\n}\n\n/**\n * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n * @param {import(\"../../extent.js\").Extent} extent The frame extent.\n * @return {import(\"../../extent.js\").Extent} Frame extent intersected with layer extents.\n */\nfunction getRenderExtent(frameState, extent) {\n const layerState = frameState.layerStatesArray[frameState.layerIndex];\n if (layerState.extent) {\n extent = getIntersection(\n extent,\n fromUserExtent(layerState.extent, frameState.viewState.projection)\n );\n }\n const source = /** @type {import(\"../../source/Tile.js\").default} */ (\n layerState.layer.getRenderSource()\n );\n if (!source.getWrapX()) {\n const gridExtent = source\n .getTileGridForProjection(frameState.viewState.projection)\n .getExtent();\n if (gridExtent) {\n extent = getIntersection(extent, gridExtent);\n }\n }\n return extent;\n}\n\nexport function getCacheKey(source, tileCoord) {\n return `${source.getKey()},${getTileCoordKey(tileCoord)}`;\n}\n\n/**\n * @typedef {Object} Options\n * @property {Object} [uniforms] Additional uniforms\n * made available to shaders.\n * @property {number} [cacheSize=512] The tile representation cache size.\n * @property {Array} [postProcesses] Post-processes definitions.\n */\n\n/**\n * @typedef {import(\"../../layer/BaseTile.js\").default} BaseLayerType\n */\n\n/**\n * @classdesc\n * Base WebGL renderer for tile layers.\n * @template {BaseLayerType} LayerType\n * @template {import(\"../../Tile.js\").default} TileType\n * @template {import(\"../../webgl/BaseTileRepresentation.js\").default} TileRepresentation\n * @extends {WebGLLayerRenderer}\n */\nclass WebGLBaseTileLayerRenderer extends WebGLLayerRenderer {\n /**\n * @param {LayerType} tileLayer Tile layer.\n * @param {Options} options Options.\n */\n constructor(tileLayer, options) {\n super(tileLayer, {\n uniforms: options.uniforms,\n postProcesses: options.postProcesses,\n });\n\n /**\n * The last call to `renderFrame` was completed with all tiles loaded\n * @type {boolean}\n */\n this.renderComplete = false;\n\n /**\n * This transform converts representation coordinates to screen coordinates.\n * @type {import(\"../../transform.js\").Transform}\n * @private\n */\n this.tileTransform_ = createTransform();\n\n /**\n * @type {Array}\n * @protected\n */\n this.tempMat4 = createMat4();\n\n /**\n * @type {import(\"../../TileRange.js\").default}\n * @private\n */\n this.tempTileRange_ = new TileRange(0, 0, 0, 0);\n\n /**\n * @type {import(\"../../tilecoord.js\").TileCoord}\n * @private\n */\n this.tempTileCoord_ = createTileCoord(0, 0, 0);\n\n /**\n * @type {import(\"../../size.js\").Size}\n * @private\n */\n this.tempSize_ = [0, 0];\n\n const cacheSize = options.cacheSize !== undefined ? options.cacheSize : 512;\n /**\n * @type {import(\"../../structs/LRUCache.js\").default}\n * @protected\n */\n this.tileRepresentationCache = new LRUCache(cacheSize);\n\n /**\n * @protected\n * @type {import(\"../../Map.js\").FrameState|null}\n */\n this.frameState = null;\n\n /**\n * @private\n * @type {import(\"../../proj/Projection.js\").default}\n */\n this.projection_ = undefined;\n }\n\n /**\n * @param {Options} options Options.\n */\n reset(options) {\n super.reset({\n uniforms: options.uniforms,\n });\n }\n\n /**\n * @param {TileType} tile Tile.\n * @return {boolean} Tile is drawable.\n * @private\n */\n isDrawableTile_(tile) {\n const tileLayer = this.getLayer();\n const tileState = tile.getState();\n const useInterimTilesOnError = tileLayer.getUseInterimTilesOnError();\n return (\n tileState == TileState.LOADED ||\n tileState == TileState.EMPTY ||\n (tileState == TileState.ERROR && !useInterimTilesOnError)\n );\n }\n\n /**\n * Determine whether renderFrame should be called.\n * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n * @return {boolean} Layer is ready to be rendered.\n */\n prepareFrameInternal(frameState) {\n if (!this.projection_) {\n this.projection_ = frameState.viewState.projection;\n } else if (frameState.viewState.projection !== this.projection_) {\n this.clearCache();\n this.projection_ = frameState.viewState.projection;\n }\n\n const layer = this.getLayer();\n const source = layer.getRenderSource();\n if (!source) {\n return false;\n }\n\n if (isEmpty(getRenderExtent(frameState, frameState.extent))) {\n return false;\n }\n return source.getState() === 'ready';\n }\n\n /**\n * @abstract\n * @param {import(\"../../webgl/BaseTileRepresentation.js\").TileRepresentationOptions} options tile representation options\n * @return {TileRepresentation} A new tile representation\n * @protected\n */\n createTileRepresentation(options) {\n return abstract();\n }\n\n /**\n * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n * @param {import(\"../../extent.js\").Extent} extent The extent to be rendered.\n * @param {number} initialZ The zoom level.\n * @param {TileRepresentationLookup} tileRepresentationLookup The zoom level.\n * @param {number} preload Number of additional levels to load.\n */\n enqueueTiles(\n frameState,\n extent,\n initialZ,\n tileRepresentationLookup,\n preload\n ) {\n const viewState = frameState.viewState;\n const tileLayer = this.getLayer();\n const tileSource = tileLayer.getRenderSource();\n const tileGrid = tileSource.getTileGridForProjection(viewState.projection);\n const gutter = tileSource.getGutterForProjection(viewState.projection);\n\n const tileSourceKey = getUid(tileSource);\n if (!(tileSourceKey in frameState.wantedTiles)) {\n frameState.wantedTiles[tileSourceKey] = {};\n }\n\n const wantedTiles = frameState.wantedTiles[tileSourceKey];\n const tileRepresentationCache = this.tileRepresentationCache;\n\n const map = tileLayer.getMapInternal();\n const minZ = Math.max(\n initialZ - preload,\n tileGrid.getMinZoom(),\n tileGrid.getZForResolution(\n Math.min(\n tileLayer.getMaxResolution(),\n map\n ? map\n .getView()\n .getResolutionForZoom(Math.max(tileLayer.getMinZoom(), 0))\n : tileGrid.getResolution(0)\n ),\n tileSource.zDirection\n )\n );\n for (let z = initialZ; z >= minZ; --z) {\n const tileRange = tileGrid.getTileRangeForExtentAndZ(\n extent,\n z,\n this.tempTileRange_\n );\n\n const tileResolution = tileGrid.getResolution(z);\n\n for (let x = tileRange.minX; x <= tileRange.maxX; ++x) {\n for (let y = tileRange.minY; y <= tileRange.maxY; ++y) {\n const tileCoord = createTileCoord(z, x, y, this.tempTileCoord_);\n const cacheKey = getCacheKey(tileSource, tileCoord);\n\n /** @type {TileRepresentation} */\n let tileRepresentation;\n\n /** @type {TileType} */\n let tile;\n\n if (tileRepresentationCache.containsKey(cacheKey)) {\n tileRepresentation = tileRepresentationCache.get(cacheKey);\n tile = tileRepresentation.tile;\n }\n if (\n !tileRepresentation ||\n tileRepresentation.tile.key !== tileSource.getKey()\n ) {\n tile = tileSource.getTile(\n z,\n x,\n y,\n frameState.pixelRatio,\n viewState.projection\n );\n }\n\n if (lookupHasTile(tileRepresentationLookup, tile)) {\n continue;\n }\n\n if (!tileRepresentation) {\n tileRepresentation = this.createTileRepresentation({\n tile: tile,\n grid: tileGrid,\n helper: this.helper,\n gutter: gutter,\n });\n tileRepresentationCache.set(cacheKey, tileRepresentation);\n } else {\n if (this.isDrawableTile_(tile)) {\n tileRepresentation.setTile(tile);\n } else {\n const interimTile = /** @type {TileType} */ (\n tile.getInterimTile()\n );\n tileRepresentation.setTile(interimTile);\n }\n }\n\n addTileRepresentationToLookup(\n tileRepresentationLookup,\n tileRepresentation,\n z\n );\n\n const tileQueueKey = tile.getKey();\n wantedTiles[tileQueueKey] = true;\n\n if (tile.getState() === TileState.IDLE) {\n if (!frameState.tileQueue.isKeyQueued(tileQueueKey)) {\n frameState.tileQueue.enqueue([\n tile,\n tileSourceKey,\n tileGrid.getTileCoordCenter(tileCoord),\n tileResolution,\n ]);\n }\n }\n }\n }\n }\n }\n\n /**\n * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n * @param {boolean} tilesWithAlpha True if at least one of the rendered tiles has alpha\n * @protected\n */\n beforeTilesRender(frameState, tilesWithAlpha) {\n this.helper.prepareDraw(this.frameState, !tilesWithAlpha, true);\n }\n\n /**\n * @param {TileRepresentation} tileRepresentation Tile representation\n * @param {import(\"../../transform.js\").Transform} tileTransform Tile transform\n * @param {import(\"../../Map.js\").FrameState} frameState Frame state\n * @param {import(\"../../extent.js\").Extent} renderExtent Render extent\n * @param {number} tileResolution Tile resolution\n * @param {import(\"../../size.js\").Size} tileSize Tile size\n * @param {import(\"../../coordinate.js\").Coordinate} tileOrigin Tile origin\n * @param {import(\"../../extent.js\").Extent} tileExtent tile Extent\n * @param {number} depth Depth\n * @param {number} gutter Gutter\n * @param {number} alpha Alpha\n * @protected\n */\n renderTile(\n tileRepresentation,\n tileTransform,\n frameState,\n renderExtent,\n tileResolution,\n tileSize,\n tileOrigin,\n tileExtent,\n depth,\n gutter,\n alpha\n ) {}\n\n drawTile_(\n frameState,\n tileRepresentation,\n tileZ,\n gutter,\n extent,\n alphaLookup,\n tileGrid\n ) {\n if (!tileRepresentation.loaded) {\n return;\n }\n const tile = tileRepresentation.tile;\n const tileCoord = tile.tileCoord;\n const tileCoordKey = getTileCoordKey(tileCoord);\n const alpha = tileCoordKey in alphaLookup ? alphaLookup[tileCoordKey] : 1;\n\n const tileResolution = tileGrid.getResolution(tileZ);\n const tileSize = toSize(tileGrid.getTileSize(tileZ), this.tempSize_);\n const tileOrigin = tileGrid.getOrigin(tileZ);\n const tileExtent = tileGrid.getTileCoordExtent(tileCoord);\n // tiles with alpha are rendered last to allow blending\n const depth = alpha < 1 ? -1 : depthForZ(tileZ);\n if (alpha < 1) {\n frameState.animate = true;\n }\n\n const viewState = frameState.viewState;\n const centerX = viewState.center[0];\n const centerY = viewState.center[1];\n\n const tileWidthWithGutter = tileSize[0] + 2 * gutter;\n const tileHeightWithGutter = tileSize[1] + 2 * gutter;\n\n const aspectRatio = tileWidthWithGutter / tileHeightWithGutter;\n\n const centerI = (centerX - tileOrigin[0]) / (tileSize[0] * tileResolution);\n const centerJ = (tileOrigin[1] - centerY) / (tileSize[1] * tileResolution);\n\n const tileScale = viewState.resolution / tileResolution;\n\n const tileCenterI = tileCoord[1];\n const tileCenterJ = tileCoord[2];\n\n resetTransform(this.tileTransform_);\n scaleTransform(\n this.tileTransform_,\n 2 / ((frameState.size[0] * tileScale) / tileWidthWithGutter),\n -2 / ((frameState.size[1] * tileScale) / tileWidthWithGutter)\n );\n rotateTransform(this.tileTransform_, viewState.rotation);\n scaleTransform(this.tileTransform_, 1, 1 / aspectRatio);\n translateTransform(\n this.tileTransform_,\n (tileSize[0] * (tileCenterI - centerI) - gutter) / tileWidthWithGutter,\n (tileSize[1] * (tileCenterJ - centerJ) - gutter) / tileHeightWithGutter\n );\n\n this.renderTile(\n /** @type {TileRepresentation} */ (tileRepresentation),\n this.tileTransform_,\n frameState,\n extent,\n tileResolution,\n tileSize,\n tileOrigin,\n tileExtent,\n depth,\n gutter,\n alpha\n );\n }\n\n /**\n * Render the layer.\n * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n * @return {HTMLElement} The rendered element.\n */\n renderFrame(frameState) {\n this.frameState = frameState;\n this.renderComplete = true;\n const gl = this.helper.getGL();\n this.preRender(gl, frameState);\n\n const viewState = frameState.viewState;\n const tileLayer = this.getLayer();\n const tileSource = tileLayer.getRenderSource();\n const tileGrid = tileSource.getTileGridForProjection(viewState.projection);\n const gutter = tileSource.getGutterForProjection(viewState.projection);\n const extent = getRenderExtent(frameState, frameState.extent);\n const z = tileGrid.getZForResolution(\n viewState.resolution,\n tileSource.zDirection\n );\n\n /**\n * @type {TileRepresentationLookup}\n */\n const tileRepresentationLookup = newTileRepresentationLookup();\n\n const preload = tileLayer.getPreload();\n if (frameState.nextExtent) {\n const targetZ = tileGrid.getZForResolution(\n viewState.nextResolution,\n tileSource.zDirection\n );\n const nextExtent = getRenderExtent(frameState, frameState.nextExtent);\n this.enqueueTiles(\n frameState,\n nextExtent,\n targetZ,\n tileRepresentationLookup,\n preload\n );\n }\n\n this.enqueueTiles(frameState, extent, z, tileRepresentationLookup, 0);\n if (preload > 0) {\n setTimeout(() => {\n this.enqueueTiles(\n frameState,\n extent,\n z - 1,\n tileRepresentationLookup,\n preload - 1\n );\n }, 0);\n }\n\n /**\n * A lookup of alpha values for tiles at the target rendering resolution\n * for tiles that are in transition. If a tile coord key is absent from\n * this lookup, the tile should be rendered at alpha 1.\n * @type {Object}\n */\n const alphaLookup = {};\n\n const uid = getUid(this);\n const time = frameState.time;\n let blend = false;\n\n // look for cached tiles to use if a target tile is not ready\n for (const tileRepresentation of tileRepresentationLookup\n .representationsByZ[z]) {\n const tile = tileRepresentation.tile;\n if (\n (tile instanceof ReprojTile || tile instanceof ReprojDataTile) &&\n tile.getState() === TileState.EMPTY\n ) {\n continue;\n }\n const tileCoord = tile.tileCoord;\n\n if (tileRepresentation.loaded) {\n const alpha = tile.getAlpha(uid, time);\n if (alpha === 1) {\n // no need to look for alt tiles\n tile.endTransition(uid);\n continue;\n }\n blend = true;\n const tileCoordKey = getTileCoordKey(tileCoord);\n alphaLookup[tileCoordKey] = alpha;\n }\n this.renderComplete = false;\n\n // first look for child tiles (at z + 1)\n const coveredByChildren = this.findAltTiles_(\n tileGrid,\n tileCoord,\n z + 1,\n tileRepresentationLookup\n );\n\n if (coveredByChildren) {\n continue;\n }\n\n // next look for parent tiles\n const minZoom = tileGrid.getMinZoom();\n for (let parentZ = z - 1; parentZ >= minZoom; --parentZ) {\n const coveredByParent = this.findAltTiles_(\n tileGrid,\n tileCoord,\n parentZ,\n tileRepresentationLookup\n );\n\n if (coveredByParent) {\n break;\n }\n }\n }\n\n this.beforeTilesRender(frameState, blend);\n\n const representationsByZ = tileRepresentationLookup.representationsByZ;\n const zs = Object.keys(representationsByZ).map(Number).sort(descending);\n for (let j = 0, jj = zs.length; j < jj; ++j) {\n const tileZ = zs[j];\n for (const tileRepresentation of representationsByZ[tileZ]) {\n const tileCoord = tileRepresentation.tile.tileCoord;\n const tileCoordKey = getTileCoordKey(tileCoord);\n if (tileCoordKey in alphaLookup) {\n continue;\n }\n\n this.drawTile_(\n frameState,\n tileRepresentation,\n tileZ,\n gutter,\n extent,\n alphaLookup,\n tileGrid\n );\n }\n }\n\n for (const tileRepresentation of representationsByZ[z]) {\n const tileCoord = tileRepresentation.tile.tileCoord;\n const tileCoordKey = getTileCoordKey(tileCoord);\n if (tileCoordKey in alphaLookup) {\n this.drawTile_(\n frameState,\n tileRepresentation,\n z,\n gutter,\n extent,\n alphaLookup,\n tileGrid\n );\n }\n }\n\n this.helper.finalizeDraw(\n frameState,\n this.dispatchPreComposeEvent,\n this.dispatchPostComposeEvent\n );\n\n const canvas = this.helper.getCanvas();\n\n const tileRepresentationCache = this.tileRepresentationCache;\n while (tileRepresentationCache.canExpireCache()) {\n const tileRepresentation = tileRepresentationCache.pop();\n tileRepresentation.dispose();\n }\n\n // TODO: let the renderers manage their own cache instead of managing the source cache\n /**\n * Here we unconditionally expire the source cache since the renderer maintains\n * its own cache.\n * @param {import(\"../../Map.js\").default} map Map.\n * @param {import(\"../../Map.js\").FrameState} frameState Frame state.\n */\n const postRenderFunction = function (map, frameState) {\n tileSource.updateCacheSize(0.1, frameState.viewState.projection);\n tileSource.expireCache(frameState.viewState.projection, empty);\n };\n\n frameState.postRenderFunctions.push(postRenderFunction);\n\n this.postRender(gl, frameState);\n return canvas;\n }\n\n /**\n * Look for tiles covering the provided tile coordinate at an alternate\n * zoom level. Loaded tiles will be added to the provided tile representation lookup.\n * @param {import(\"../../tilegrid/TileGrid.js\").default} tileGrid The tile grid.\n * @param {import(\"../../tilecoord.js\").TileCoord} tileCoord The target tile coordinate.\n * @param {number} altZ The alternate zoom level.\n * @param {TileRepresentationLookup} tileRepresentationLookup Lookup of\n * tile representations by zoom level.\n * @return {boolean} The tile coordinate is covered by loaded tiles at the alternate zoom level.\n * @private\n */\n findAltTiles_(tileGrid, tileCoord, altZ, tileRepresentationLookup) {\n const tileRange = tileGrid.getTileRangeForTileCoordAndZ(\n tileCoord,\n altZ,\n this.tempTileRange_\n );\n\n if (!tileRange) {\n return false;\n }\n\n let covered = true;\n const tileRepresentationCache = this.tileRepresentationCache;\n const source = this.getLayer().getRenderSource();\n for (let x = tileRange.minX; x <= tileRange.maxX; ++x) {\n for (let y = tileRange.minY; y <= tileRange.maxY; ++y) {\n const cacheKey = getCacheKey(source, [altZ, x, y]);\n let loaded = false;\n if (tileRepresentationCache.containsKey(cacheKey)) {\n const tileRepresentation = tileRepresentationCache.get(cacheKey);\n if (\n tileRepresentation.loaded &&\n !lookupHasTile(tileRepresentationLookup, tileRepresentation.tile)\n ) {\n addTileRepresentationToLookup(\n tileRepresentationLookup,\n tileRepresentation,\n altZ\n );\n loaded = true;\n }\n }\n if (!loaded) {\n covered = false;\n }\n }\n }\n return covered;\n }\n\n clearCache() {\n const tileRepresentationCache = this.tileRepresentationCache;\n tileRepresentationCache.forEach((tileRepresentation) =>\n tileRepresentation.dispose()\n );\n tileRepresentationCache.clear();\n }\n\n removeHelper() {\n if (this.helper) {\n this.clearCache();\n }\n\n super.removeHelper();\n }\n\n /**\n * Clean up.\n */\n disposeInternal() {\n super.disposeInternal();\n delete this.frameState;\n }\n}\n\nexport default WebGLBaseTileLayerRenderer;\n","/**\n * @module ol/renderer/webgl/TileLayer\n */\nimport ReprojDataTile from '../../reproj/DataTile.js';\nimport ReprojTile from '../../reproj/Tile.js';\nimport TileState from '../../TileState.js';\nimport TileTexture from '../../webgl/TileTexture.js';\nimport WebGLArrayBuffer from '../../webgl/Buffer.js';\nimport WebGLBaseTileLayerRenderer, {\n Uniforms as BaseUniforms,\n getCacheKey,\n} from './TileLayerBase.js';\nimport {AttributeType} from '../../webgl/Helper.js';\nimport {ELEMENT_ARRAY_BUFFER, STATIC_DRAW} from '../../webgl.js';\nimport {apply as applyTransform} from '../../transform.js';\nimport {\n boundingExtent,\n containsCoordinate,\n getIntersection,\n} from '../../extent.js';\nimport {fromUserExtent} from '../../proj.js';\nimport {fromTransform as mat4FromTransform} from '../../vec/mat4.js';\nimport {toSize} from '../../size.js';\n\nexport const Uniforms = {\n ...BaseUniforms,\n TILE_TEXTURE_ARRAY: 'u_tileTextures',\n TEXTURE_PIXEL_WIDTH: 'u_texturePixelWidth',\n TEXTURE_PIXEL_HEIGHT: 'u_texturePixelHeight',\n TEXTURE_RESOLUTION: 'u_textureResolution', // map units per texture pixel\n TEXTURE_ORIGIN_X: 'u_textureOriginX', // map x coordinate of left edge of texture\n TEXTURE_ORIGIN_Y: 'u_textureOriginY', // map y coordinate of top edge of texture\n};\n\nexport const Attributes = {\n TEXTURE_COORD: 'a_textureCoord',\n};\n\n/**\n * @type {Array}\n */\nconst attributeDescriptions = [\n {\n name: Attributes.TEXTURE_COORD,\n size: 2,\n type: AttributeType.FLOAT,\n },\n];\n\n/**\n * @typedef {Object} Options\n * @property {string} vertexShader Vertex shader source.\n * @property {string} fragmentShader Fragment shader source.\n * @property {Object} [uniforms] Additional uniforms\n * made available to shaders.\n * @property {Array} [paletteTextures] Palette textures.\n * @property {number} [cacheSize=512] The texture cache size.\n */\n\n/**\n * @typedef {import(\"../../layer/WebGLTile.js\").default} LayerType\n */\n/**\n * @typedef {import(\"../../webgl/TileTexture.js\").TileType} TileTextureType\n */\n/**\n * @typedef {import(\"../../webgl/TileTexture.js\").default} TileTextureRepresentation\n */\n\n/**\n * @classdesc\n * WebGL renderer for tile layers.\n * @extends {WebGLBaseTileLayerRenderer}\n * @api\n */\nclass WebGLTileLayerRenderer extends WebGLBaseTileLayerRenderer {\n /**\n * @param {LayerType} tileLayer Tile layer.\n * @param {Options} options Options.\n */\n constructor(tileLayer, options) {\n super(tileLayer, options);\n\n /**\n * @type {WebGLProgram}\n * @private\n */\n this.program_;\n\n /**\n * @private\n */\n this.vertexShader_ = options.vertexShader;\n\n /**\n * @private\n */\n this.fragmentShader_ = options.fragmentShader;\n\n /**\n * Tiles are rendered as a quad with the following structure:\n *\n * [P3]---------[P2]\n * |` |\n * | ` B |\n * | ` |\n * | ` |\n * | A ` |\n * | ` |\n * [P0]---------[P1]\n *\n * Triangle A: P0, P1, P3\n * Triangle B: P1, P2, P3\n *\n * @private\n */\n this.indices_ = new WebGLArrayBuffer(ELEMENT_ARRAY_BUFFER, STATIC_DRAW);\n this.indices_.fromArray([0, 1, 3, 1, 2, 3]);\n\n /**\n * @type {Array}\n * @private\n */\n this.paletteTextures_ = options.paletteTextures || [];\n }\n\n /**\n * @param {Options} options Options.\n */\n reset(options) {\n super.reset(options);\n\n this.vertexShader_ = options.vertexShader;\n this.fragmentShader_ = options.fragmentShader;\n\n if (this.helper) {\n this.program_ = this.helper.getProgram(\n this.fragmentShader_,\n this.vertexShader_\n );\n }\n }\n\n afterHelperCreated() {\n this.program_ = this.helper.getProgram(\n this.fragmentShader_,\n this.vertexShader_\n );\n this.helper.flushBufferData(this.indices_);\n }\n\n createTileRepresentation(options) {\n return new TileTexture(options);\n }\n\n beforeTilesRender(frameState, tilesWithAlpha) {\n super.beforeTilesRender(frameState, tilesWithAlpha);\n this.helper.useProgram(this.program_, frameState);\n }\n\n renderTile(\n tileTexture,\n tileTransform,\n frameState,\n renderExtent,\n tileResolution,\n tileSize,\n tileOrigin,\n tileExtent,\n depth,\n gutter,\n alpha\n ) {\n const gl = this.helper.getGL();\n this.helper.bindBuffer(tileTexture.coords);\n this.helper.bindBuffer(this.indices_);\n this.helper.enableAttributes(attributeDescriptions);\n\n let textureSlot = 0;\n while (textureSlot < tileTexture.textures.length) {\n const uniformName = `${Uniforms.TILE_TEXTURE_ARRAY}[${textureSlot}]`;\n this.helper.bindTexture(\n tileTexture.textures[textureSlot],\n textureSlot,\n uniformName\n );\n ++textureSlot;\n }\n\n for (\n let paletteIndex = 0;\n paletteIndex < this.paletteTextures_.length;\n ++paletteIndex\n ) {\n const paletteTexture = this.paletteTextures_[paletteIndex];\n const texture = paletteTexture.getTexture(gl);\n this.helper.bindTexture(texture, textureSlot, paletteTexture.name);\n ++textureSlot;\n }\n\n const viewState = frameState.viewState;\n\n const tileWidthWithGutter = tileSize[0] + 2 * gutter;\n const tileHeightWithGutter = tileSize[1] + 2 * gutter;\n\n const tile = tileTexture.tile;\n const tileCoord = tile.tileCoord;\n\n const tileCenterI = tileCoord[1];\n const tileCenterJ = tileCoord[2];\n\n this.helper.setUniformMatrixValue(\n Uniforms.TILE_TRANSFORM,\n mat4FromTransform(this.tempMat4, tileTransform)\n );\n\n this.helper.setUniformFloatValue(Uniforms.TRANSITION_ALPHA, alpha);\n this.helper.setUniformFloatValue(Uniforms.DEPTH, depth);\n\n let gutterExtent = renderExtent;\n if (gutter > 0) {\n gutterExtent = tileExtent;\n getIntersection(gutterExtent, renderExtent, gutterExtent);\n }\n this.helper.setUniformFloatVec4(Uniforms.RENDER_EXTENT, gutterExtent);\n\n this.helper.setUniformFloatValue(Uniforms.RESOLUTION, viewState.resolution);\n this.helper.setUniformFloatValue(Uniforms.ZOOM, viewState.zoom);\n\n this.helper.setUniformFloatValue(\n Uniforms.TEXTURE_PIXEL_WIDTH,\n tileWidthWithGutter\n );\n this.helper.setUniformFloatValue(\n Uniforms.TEXTURE_PIXEL_HEIGHT,\n tileHeightWithGutter\n );\n this.helper.setUniformFloatValue(\n Uniforms.TEXTURE_RESOLUTION,\n tileResolution\n );\n this.helper.setUniformFloatValue(\n Uniforms.TEXTURE_ORIGIN_X,\n tileOrigin[0] +\n tileCenterI * tileSize[0] * tileResolution -\n gutter * tileResolution\n );\n this.helper.setUniformFloatValue(\n Uniforms.TEXTURE_ORIGIN_Y,\n tileOrigin[1] -\n tileCenterJ * tileSize[1] * tileResolution +\n gutter * tileResolution\n );\n\n this.helper.drawElements(0, this.indices_.getSize());\n }\n\n /**\n * @param {import(\"../../pixel.js\").Pixel} pixel Pixel.\n * @return {Uint8ClampedArray|Uint8Array|Float32Array|DataView} Data at the pixel location.\n */\n getData(pixel) {\n const gl = this.helper.getGL();\n if (!gl) {\n return null;\n }\n\n const frameState = this.frameState;\n if (!frameState) {\n return null;\n }\n\n const layer = this.getLayer();\n const coordinate = applyTransform(\n frameState.pixelToCoordinateTransform,\n pixel.slice()\n );\n\n const viewState = frameState.viewState;\n const layerExtent = layer.getExtent();\n if (layerExtent) {\n if (\n !containsCoordinate(\n fromUserExtent(layerExtent, viewState.projection),\n coordinate\n )\n ) {\n return null;\n }\n }\n\n // determine last source suitable for rendering at coordinate\n const sources = layer.getSources(\n boundingExtent([coordinate]),\n viewState.resolution\n );\n let i, source, tileGrid;\n for (i = sources.length - 1; i >= 0; --i) {\n source = sources[i];\n if (source.getState() === 'ready') {\n tileGrid = source.getTileGridForProjection(viewState.projection);\n if (source.getWrapX()) {\n break;\n }\n const gridExtent = tileGrid.getExtent();\n if (!gridExtent || containsCoordinate(gridExtent, coordinate)) {\n break;\n }\n }\n }\n if (i < 0) {\n return null;\n }\n\n const tileTextureCache = this.tileRepresentationCache;\n for (\n let z = tileGrid.getZForResolution(viewState.resolution);\n z >= tileGrid.getMinZoom();\n --z\n ) {\n const tileCoord = tileGrid.getTileCoordForCoordAndZ(coordinate, z);\n const cacheKey = getCacheKey(source, tileCoord);\n if (!tileTextureCache.containsKey(cacheKey)) {\n continue;\n }\n const tileTexture = tileTextureCache.get(cacheKey);\n const tile = tileTexture.tile;\n if (\n (tile instanceof ReprojTile || tile instanceof ReprojDataTile) &&\n tile.getState() === TileState.EMPTY\n ) {\n return null;\n }\n if (!tileTexture.loaded) {\n continue;\n }\n const tileOrigin = tileGrid.getOrigin(z);\n const tileSize = toSize(tileGrid.getTileSize(z));\n const tileResolution = tileGrid.getResolution(z);\n\n const col =\n (coordinate[0] - tileOrigin[0]) / tileResolution -\n tileCoord[1] * tileSize[0];\n\n const row =\n (tileOrigin[1] - coordinate[1]) / tileResolution -\n tileCoord[2] * tileSize[1];\n\n return tileTexture.getPixelData(col, row);\n }\n return null;\n }\n\n /**\n * Clean up.\n */\n disposeInternal() {\n const helper = this.helper;\n if (helper) {\n const gl = helper.getGL();\n gl.deleteProgram(this.program_);\n delete this.program_;\n helper.deleteBuffer(this.indices_);\n }\n super.disposeInternal();\n delete this.indices_;\n }\n}\n\nexport default WebGLTileLayerRenderer;\n","/**\n * Operators and utilities used for style expressions\n * @module ol/style/expressions\n */\n\nimport PaletteTexture from '../webgl/PaletteTexture.js';\nimport {Uniforms} from '../renderer/webgl/TileLayer.js';\nimport {asArray, fromString, isStringColor} from '../color.js';\n\n/**\n * Base type used for literal style parameters; can be a number literal or the output of an operator,\n * which in turns takes {@link import(\"./expressions.js\").ExpressionValue} arguments.\n *\n * The following operators can be used:\n *\n * * Reading operators:\n * * `['band', bandIndex, xOffset, yOffset]` For tile layers only. Fetches pixel values from band\n * `bandIndex` of the source's data. The first `bandIndex` of the source data is `1`. Fetched values\n * are in the 0..1 range. {@link import(\"../source/TileImage.js\").default} sources have 4 bands: red,\n * green, blue and alpha. {@link import(\"../source/DataTile.js\").default} sources can have any number\n * of bands, depending on the underlying data source and\n * {@link import(\"../source/GeoTIFF.js\").Options configuration}. `xOffset` and `yOffset` are optional\n * and allow specifying pixel offsets for x and y. This is used for sampling data from neighboring pixels.\n * * `['get', 'attributeName', typeHint]` fetches a feature property value, similar to `feature.get('attributeName')`\n * A type hint can optionally be specified, in case the resulting expression contains a type ambiguity which\n * will make it invalid. Type hints can be one of: 'string', 'color', 'number', 'boolean', 'number[]'\n * * `['geometry-type']` returns a feature's geometry type as string, either: 'LineString', 'Point' or 'Polygon'\n * `Multi*` values are returned as their singular equivalent\n * `Circle` geometries are returned as 'Polygon'\n * `GeometryCollection` geometries are returned as the type of the first geometry found in the collection\n * * `['resolution']` returns the current resolution\n * * `['time']` returns the time in seconds since the creation of the layer\n * * `['var', 'varName']` fetches a value from the style variables; will throw an error if that variable is undefined\n * * `['zoom']` returns the current zoom level\n *\n * * Math operators:\n * * `['*', value1, value2, ...]` multiplies the values (either numbers or colors)\n * * `['/', value1, value2]` divides `value1` by `value2`\n * * `['+', value1, value2, ...]` adds the values\n * * `['-', value1, value2]` subtracts `value2` from `value1`\n * * `['clamp', value, low, high]` clamps `value` between `low` and `high`\n * * `['%', value1, value2]` returns the result of `value1 % value2` (modulo)\n * * `['^', value1, value2]` returns the value of `value1` raised to the `value2` power\n * * `['abs', value1]` returns the absolute value of `value1`\n * * `['floor', value1]` returns the nearest integer less than or equal to `value1`\n * * `['round', value1]` returns the nearest integer to `value1`\n * * `['ceil', value1]` returns the nearest integer greater than or equal to `value1`\n * * `['sin', value1]` returns the sine of `value1`\n * * `['cos', value1]` returns the cosine of `value1`\n * * `['atan', value1, value2]` returns `atan2(value1, value2)`. If `value2` is not provided, returns `atan(value1)`\n * * `['sqrt', value1]` returns the square root of `value1`\n *\n * * Transform operators:\n * * `['case', condition1, output1, ...conditionN, outputN, fallback]` selects the first output whose corresponding\n * condition evaluates to `true`. If no match is found, returns the `fallback` value.\n * All conditions should be `boolean`, output and fallback can be any kind.\n * * `['match', input, match1, output1, ...matchN, outputN, fallback]` compares the `input` value against all\n * provided `matchX` values, returning the output associated with the first valid match. If no match is found,\n * returns the `fallback` value.\n * `input` and `matchX` values must all be of the same type, and can be `number` or `string`. `outputX` and\n * `fallback` values must be of the same type, and can be of any kind.\n * * `['interpolate', interpolation, input, stop1, output1, ...stopN, outputN]` returns a value by interpolating between\n * pairs of inputs and outputs; `interpolation` can either be `['linear']` or `['exponential', base]` where `base` is\n * the rate of increase from stop A to stop B (i.e. power to which the interpolation ratio is raised); a value\n * of 1 is equivalent to `['linear']`.\n * `input` and `stopX` values must all be of type `number`. `outputX` values can be `number` or `color` values.\n * Note: `input` will be clamped between `stop1` and `stopN`, meaning that all output values will be comprised\n * between `output1` and `outputN`.\n *\n * * Logical operators:\n * * `['<', value1, value2]` returns `true` if `value1` is strictly lower than `value2`, or `false` otherwise.\n * * `['<=', value1, value2]` returns `true` if `value1` is lower than or equals `value2`, or `false` otherwise.\n * * `['>', value1, value2]` returns `true` if `value1` is strictly greater than `value2`, or `false` otherwise.\n * * `['>=', value1, value2]` returns `true` if `value1` is greater than or equals `value2`, or `false` otherwise.\n * * `['==', value1, value2]` returns `true` if `value1` equals `value2`, or `false` otherwise.\n * * `['!=', value1, value2]` returns `true` if `value1` does not equal `value2`, or `false` otherwise.\n * * `['!', value1]` returns `false` if `value1` is `true` or greater than `0`, or `true` otherwise.\n * * `['all', value1, value2, ...]` returns `true` if all the inputs are `true`, `false` otherwise.\n * * `['any', value1, value2, ...]` returns `true` if any of the inputs are `true`, `false` otherwise.\n * * `['between', value1, value2, value3]` returns `true` if `value1` is contained between `value2` and `value3`\n * (inclusively), or `false` otherwise.\n * * `['in', needle, haystack]` returns `true` if `needle` is found in `haystack`, and\n * `false` otherwise.\n * This operator has the following limitations:\n * * `haystack` has to be an array of numbers or strings (searching for a substring in a string is not supported yet)\n * * Only literal arrays are supported as `haystack` for now; this means that `haystack` cannot be the result of an\n * expression. If `haystack` is an array of strings, use the `literal` operator to disambiguate from an expression:\n * `['literal', ['abc', 'def', 'ghi']]`\n *\n * * Conversion operators:\n * * `['array', value1, ...valueN]` creates a numerical array from `number` values; please note that the amount of\n * values can currently only be 2, 3 or 4.\n * * `['color', red, green, blue, alpha]` creates a `color` value from `number` values; the `alpha` parameter is\n * optional; if not specified, it will be set to 1.\n * Note: `red`, `green` and `blue` components must be values between 0 and 255; `alpha` between 0 and 1.\n * * `['palette', index, colors]` picks a `color` value from an array of colors using the given index; the `index`\n * expression must evaluate to a number; the items in the `colors` array must be strings with hex colors\n * (e.g. `'#86A136'`), colors using the rgba[a] functional notation (e.g. `'rgb(134, 161, 54)'` or `'rgba(134, 161, 54, 1)'`),\n * named colors (e.g. `'red'`), or array literals with 3 ([r, g, b]) or 4 ([r, g, b, a]) values (with r, g, and b\n * in the 0-255 range and a in the 0-1 range).\n *\n * Values can either be literals or another operator, as they will be evaluated recursively.\n * Literal values can be of the following types:\n * * `boolean`\n * * `number`\n * * `number[]` (number arrays can only have a length of 2, 3 or 4)\n * * `string`\n * * {@link module:ol/color~Color}\n *\n * @typedef {Array<*>|import(\"../color.js\").Color|string|number|boolean} ExpressionValue\n * @api\n */\n\n/**\n * Possible inferred types from a given value or expression.\n * Note: these are binary flags.\n * @enum {number}\n */\nexport const ValueTypes = {\n NUMBER: 0b00001,\n STRING: 0b00010,\n COLOR: 0b00100,\n BOOLEAN: 0b01000,\n NUMBER_ARRAY: 0b10000,\n ANY: 0b11111,\n NONE: 0,\n};\n\n/**\n * @param {string} typeHint Type hint\n * @return {ValueTypes} Resulting value type (will be a single type)\n */\nfunction getTypeFromHint(typeHint) {\n switch (typeHint) {\n case 'string':\n return ValueTypes.STRING;\n case 'color':\n return ValueTypes.COLOR;\n case 'number':\n return ValueTypes.NUMBER;\n case 'boolean':\n return ValueTypes.BOOLEAN;\n case 'number[]':\n return ValueTypes.NUMBER_ARRAY;\n default:\n throw new Error(`Unrecognized type hint: ${typeHint}`);\n }\n}\n\n/**\n * An operator declaration must contain two methods: `getReturnType` which returns a type based on\n * the operator arguments, and `toGlsl` which returns a GLSL-compatible string.\n * Note: both methods can process arguments recursively.\n * @typedef {Object} Operator\n * @property {function(Array): ValueTypes|number} getReturnType Returns one or several types\n * @property {function(ParsingContext, Array, ValueTypes): string} toGlsl Returns a GLSL-compatible string\n * given a parsing context, an array of arguments and an expected type.\n * Note: the expected type can be a combination such as ValueTypes.NUMBER | ValueTypes.STRING or ValueTypes.ANY for instance\n */\n\n/**\n * Operator declarations\n * @type {Object}\n */\nexport const Operators = {};\n\n/**\n * Returns the possible types for a given value (each type being a binary flag)\n * To test a value use e.g. `getValueType(v) & ValueTypes.BOOLEAN`\n * @param {ExpressionValue} value Value\n * @return {ValueTypes|number} Type or types inferred from the value\n */\nexport function getValueType(value) {\n if (typeof value === 'number') {\n return ValueTypes.NUMBER;\n }\n if (typeof value === 'boolean') {\n return ValueTypes.BOOLEAN;\n }\n if (typeof value === 'string') {\n if (isStringColor(value)) {\n return ValueTypes.COLOR | ValueTypes.STRING;\n }\n return ValueTypes.STRING;\n }\n if (!Array.isArray(value)) {\n throw new Error(`Unhandled value type: ${JSON.stringify(value)}`);\n }\n const valueArr = /** @type {Array<*>} */ (value);\n const onlyNumbers = valueArr.every(function (v) {\n return typeof v === 'number';\n });\n if (onlyNumbers) {\n if (valueArr.length === 3 || valueArr.length === 4) {\n return ValueTypes.COLOR | ValueTypes.NUMBER_ARRAY;\n }\n return ValueTypes.NUMBER_ARRAY;\n }\n if (typeof valueArr[0] !== 'string') {\n throw new Error(\n `Expected an expression operator but received: ${JSON.stringify(\n valueArr\n )}`\n );\n }\n const operator = Operators[valueArr[0]];\n if (operator === undefined) {\n throw new Error(\n `Unrecognized expression operator: ${JSON.stringify(valueArr)}`\n );\n }\n return operator.getReturnType(valueArr.slice(1));\n}\n\n/**\n * Checks if only one value type is enabled in the input number.\n * @param {ValueTypes|number} valueType Number containing value type binary flags\n * @return {boolean} True if only one type flag is enabled, false if zero or multiple\n */\nexport function isTypeUnique(valueType) {\n return Math.log2(valueType) % 1 === 0;\n}\n\n/**\n * Print types as a readable string\n * @param {ValueTypes|number} valueType Number containing value type binary flags\n * @return {string} Types\n */\nfunction printTypes(valueType) {\n const result = [];\n if ((valueType & ValueTypes.NUMBER) > 0) {\n result.push('number');\n }\n if ((valueType & ValueTypes.COLOR) > 0) {\n result.push('color');\n }\n if ((valueType & ValueTypes.BOOLEAN) > 0) {\n result.push('boolean');\n }\n if ((valueType & ValueTypes.NUMBER_ARRAY) > 0) {\n result.push('number[]');\n }\n if ((valueType & ValueTypes.STRING) > 0) {\n result.push('string');\n }\n return result.length > 0 ? result.join(', ') : '(no type)';\n}\n\n/**\n * @typedef {Object} ParsingContextExternal\n * @property {string} name Name, unprefixed\n * @property {ValueTypes} type One of the value types constants\n * @property {function(import(\"../Feature.js\").FeatureLike): *} [callback] Function used for computing the attribute value;\n * if undefined, `feature.get(attribute.name)` will be used\n */\n\n/**\n * Context available during the parsing of an expression.\n * @typedef {Object} ParsingContext\n * @property {boolean} [inFragmentShader] If false, means the expression output should be made for a vertex shader\n * @property {Array} variables External variables used in the expression\n * @property {Array} attributes External attributes used in the expression\n * @property {Object} stringLiteralsMap This object maps all encountered string values to a number\n * @property {Object} functions Lookup of functions used by the style.\n * @property {number} [bandCount] Number of bands per pixel.\n * @property {Array} [paletteTextures] List of palettes used by the style.\n * @property {import(\"../style/literal\").LiteralStyle} style The style being parsed\n */\n\n/**\n * @param {string} operator Operator\n * @param {ParsingContext} context Parsing context\n * @return {string} A function name based on the operator, unique in the given context\n */\nfunction computeOperatorFunctionName(operator, context) {\n return `operator_${operator}_${Object.keys(context.functions).length}`;\n}\n\n/**\n * Will return the number as a float with a dot separator, which is required by GLSL.\n * @param {number} v Numerical value.\n * @return {string} The value as string.\n */\nexport function numberToGlsl(v) {\n const s = v.toString();\n return s.includes('.') ? s : s + '.0';\n}\n\n/**\n * Will return the number array as a float with a dot separator, concatenated with ', '.\n * @param {Array} array Numerical values array.\n * @return {string} The array as a vector, e. g.: `vec3(1.0, 2.0, 3.0)`.\n */\nexport function arrayToGlsl(array) {\n if (array.length < 2 || array.length > 4) {\n throw new Error(\n '`formatArray` can only output `vec2`, `vec3` or `vec4` arrays.'\n );\n }\n return `vec${array.length}(${array.map(numberToGlsl).join(', ')})`;\n}\n\n/**\n * Will normalize and converts to string a `vec4` color array compatible with GLSL.\n * @param {string|import(\"../color.js\").Color} color Color either in string format or [r, g, b, a] array format,\n * with RGB components in the 0..255 range and the alpha component in the 0..1 range.\n * Note that the final array will always have 4 components.\n * @return {string} The color expressed in the `vec4(1.0, 1.0, 1.0, 1.0)` form.\n */\nexport function colorToGlsl(color) {\n const array = asArray(color);\n const alpha = array.length > 3 ? array[3] : 1;\n // all components are premultiplied with alpha value\n return arrayToGlsl([\n (array[0] / 255) * alpha,\n (array[1] / 255) * alpha,\n (array[2] / 255) * alpha,\n alpha,\n ]);\n}\n\n/**\n * Returns a stable equivalent number for the string literal.\n * @param {ParsingContext} context Parsing context\n * @param {string} string String literal value\n * @return {number} Number equivalent\n */\nexport function getStringNumberEquivalent(context, string) {\n if (context.stringLiteralsMap[string] === undefined) {\n context.stringLiteralsMap[string] = Object.keys(\n context.stringLiteralsMap\n ).length;\n }\n return context.stringLiteralsMap[string];\n}\n\n/**\n * Returns a stable equivalent number for the string literal, for use in shaders. This number is then\n * converted to be a GLSL-compatible string.\n * @param {ParsingContext} context Parsing context\n * @param {string} string String literal value\n * @return {string} GLSL-compatible string containing a number\n */\nexport function stringToGlsl(context, string) {\n return numberToGlsl(getStringNumberEquivalent(context, string));\n}\n\n/**\n * Recursively parses a style expression and outputs a GLSL-compatible string. Takes in a parsing context that\n * will be read and modified during the parsing operation.\n * @param {ParsingContext} context Parsing context\n * @param {ExpressionValue} value Value\n * @param {ValueTypes|number} [expectedType] Expected final type (can be several types combined)\n * If omitted, defaults to ValueTypes.NUMBER\n * @return {string} GLSL-compatible output\n */\nexport function expressionToGlsl(context, value, expectedType) {\n const returnType =\n expectedType !== undefined ? expectedType : ValueTypes.NUMBER;\n // operator\n if (Array.isArray(value) && typeof value[0] === 'string') {\n const operator = Operators[value[0]];\n if (operator === undefined) {\n throw new Error(\n `Unrecognized expression operator: ${JSON.stringify(value)}`\n );\n }\n return operator.toGlsl(context, value.slice(1), returnType);\n }\n\n const possibleType = getValueType(value) & returnType;\n assertNotEmptyType(value, possibleType, '');\n\n if ((possibleType & ValueTypes.NUMBER) > 0) {\n return numberToGlsl(/** @type {number} */ (value));\n }\n\n if ((possibleType & ValueTypes.BOOLEAN) > 0) {\n return value.toString();\n }\n\n if ((possibleType & ValueTypes.STRING) > 0) {\n return stringToGlsl(context, value.toString());\n }\n\n if ((possibleType & ValueTypes.COLOR) > 0) {\n return colorToGlsl(/** @type {Array | string} */ (value));\n }\n\n if ((possibleType & ValueTypes.NUMBER_ARRAY) > 0) {\n return arrayToGlsl(/** @type {Array} */ (value));\n }\n\n throw new Error(\n `Unexpected expression ${value} (expected type ${printTypes(returnType)})`\n );\n}\n\nfunction assertNumber(value) {\n if ((getValueType(value) & ValueTypes.NUMBER) === 0) {\n throw new Error(\n `A numeric value was expected, got ${JSON.stringify(value)} instead`\n );\n }\n}\nfunction assertNumbers(values) {\n for (let i = 0; i < values.length; i++) {\n assertNumber(values[i]);\n }\n}\nfunction assertString(value) {\n if ((getValueType(value) & ValueTypes.STRING) === 0) {\n throw new Error(\n `A string value was expected, got ${JSON.stringify(value)} instead`\n );\n }\n}\nfunction assertBoolean(value) {\n if ((getValueType(value) & ValueTypes.BOOLEAN) === 0) {\n throw new Error(\n `A boolean value was expected, got ${JSON.stringify(value)} instead`\n );\n }\n}\nfunction assertArgsCount(args, count) {\n if (args.length !== count) {\n throw new Error(\n `Exactly ${count} arguments were expected, got ${args.length} instead`\n );\n }\n}\nfunction assertArgsMinCount(args, count) {\n if (args.length < count) {\n throw new Error(\n `At least ${count} arguments were expected, got ${args.length} instead`\n );\n }\n}\nfunction assertArgsMaxCount(args, count) {\n if (args.length > count) {\n throw new Error(\n `At most ${count} arguments were expected, got ${args.length} instead`\n );\n }\n}\nfunction assertArgsEven(args) {\n if (args.length % 2 !== 0) {\n throw new Error(\n `An even amount of arguments was expected, got ${JSON.stringify(\n args\n )} instead`\n );\n }\n}\nfunction assertArgsOdd(args) {\n if (args.length % 2 === 0) {\n throw new Error(\n `An odd amount of arguments was expected, got ${JSON.stringify(\n args\n )} instead`\n );\n }\n}\nfunction assertNotEmptyType(args, types, descriptor) {\n if (types === ValueTypes.NONE) {\n throw new Error(\n `No matching type was found for the following expression ${descriptor}: ${JSON.stringify(\n args\n )}`\n );\n }\n}\nfunction assertSingleType(args, types, descriptor) {\n assertNotEmptyType(args, types, descriptor);\n if (!isTypeUnique(types)) {\n throw new Error(\n `Expected to have a unique type for the following expression ${descriptor}: ${JSON.stringify(\n args\n )}\nGot the following types instead: ${printTypes(types)}`\n );\n }\n}\nfunction assertOfType(args, types, expectedTypes, descriptor) {\n if ((types & expectedTypes) === ValueTypes.NONE) {\n throw new Error(\n `Expected the ${descriptor} type of the following expression: ${JSON.stringify(\n args\n )} to be of the following types: ${printTypes(expectedTypes)}\nGot these types instead: ${printTypes(types)}`\n );\n }\n}\n\nOperators['get'] = {\n getReturnType: function (args) {\n if (args.length === 2) {\n const hint = args[1];\n return getTypeFromHint(/** @type {string} */ (hint));\n }\n return ValueTypes.ANY;\n },\n toGlsl: function (context, args, expectedType) {\n assertArgsMinCount(args, 1);\n assertArgsMaxCount(args, 2);\n assertString(args[0]);\n const outputType = expectedType & Operators['get'].getReturnType(args);\n assertSingleType(['get', ...args], outputType, '');\n const name = args[0].toString();\n const existing = context.attributes.find((a) => a.name === name);\n if (!existing) {\n context.attributes.push({\n name: name,\n type: outputType,\n });\n } else if (outputType !== existing.type) {\n throw new Error(\n `The following attribute was used in different places with incompatible types: ${name}\nTypes were: ${printTypes(existing.type)} and ${printTypes(outputType)}`\n );\n }\n const prefix = context.inFragmentShader ? 'v_' : 'a_';\n return prefix + name;\n },\n};\n\n/**\n * Get the uniform name given a variable name.\n * @param {string} variableName The variable name.\n * @return {string} The uniform name.\n */\nexport function uniformNameForVariable(variableName) {\n return 'u_var_' + variableName;\n}\n\nOperators['var'] = {\n getReturnType: function () {\n return ValueTypes.ANY;\n },\n toGlsl: function (context, args, expectedType) {\n assertArgsCount(args, 1);\n assertString(args[0]);\n const name = args[0].toString();\n if (\n !context.style.variables ||\n context.style.variables[name] === undefined\n ) {\n throw new Error(\n `The following variable is missing from the style: ${name}`\n );\n }\n const initialValue = context.style.variables[name];\n const outputType = expectedType & getValueType(initialValue);\n assertSingleType(['var', ...args], outputType, '');\n const existing = context.variables.find((a) => a.name === name);\n if (!existing) {\n context.variables.push({\n name: name,\n type: outputType,\n });\n } else if (outputType !== existing.type) {\n throw new Error(\n `The following variable was used in different places with incompatible types: ${name}\nTypes were: ${printTypes(existing.type)} and ${printTypes(outputType)}`\n );\n }\n return uniformNameForVariable(name);\n },\n};\n\nexport const PALETTE_TEXTURE_ARRAY = 'u_paletteTextures';\n\n// ['palette', index, colors]\nOperators['palette'] = {\n getReturnType: function () {\n return ValueTypes.COLOR;\n },\n toGlsl: function (context, args) {\n assertArgsCount(args, 2);\n assertNumber(args[0]);\n const index = expressionToGlsl(context, args[0]);\n const colors = args[1];\n if (!Array.isArray(colors)) {\n throw new Error('The second argument of palette must be an array');\n }\n const numColors = colors.length;\n const palette = new Uint8Array(numColors * 4);\n for (let i = 0; i < numColors; i++) {\n const candidate = colors[i];\n /**\n * @type {import('../color.js').Color}\n */\n let color;\n if (typeof candidate === 'string') {\n color = fromString(candidate);\n } else {\n if (!Array.isArray(candidate)) {\n throw new Error(\n 'The second argument of palette must be an array of strings or colors'\n );\n }\n const length = candidate.length;\n if (length === 4) {\n color = candidate;\n } else {\n if (length !== 3) {\n throw new Error(\n `Expected palette color to have 3 or 4 values, got ${length}`\n );\n }\n color = [candidate[0], candidate[1], candidate[2], 1];\n }\n }\n const offset = i * 4;\n palette[offset] = color[0];\n palette[offset + 1] = color[1];\n palette[offset + 2] = color[2];\n palette[offset + 3] = color[3] * 255;\n }\n if (!context.paletteTextures) {\n context.paletteTextures = [];\n }\n const paletteName = `${PALETTE_TEXTURE_ARRAY}[${context.paletteTextures.length}]`;\n const paletteTexture = new PaletteTexture(paletteName, palette);\n context.paletteTextures.push(paletteTexture);\n return `texture2D(${paletteName}, vec2((${index} + 0.5) / ${numColors}.0, 0.5))`;\n },\n};\n\nconst GET_BAND_VALUE_FUNC = 'getBandValue';\n\nOperators['band'] = {\n getReturnType: function () {\n return ValueTypes.NUMBER;\n },\n toGlsl: function (context, args) {\n assertArgsMinCount(args, 1);\n assertArgsMaxCount(args, 3);\n const band = args[0];\n\n if (!(GET_BAND_VALUE_FUNC in context.functions)) {\n let ifBlocks = '';\n const bandCount = context.bandCount || 1;\n for (let i = 0; i < bandCount; i++) {\n const colorIndex = Math.floor(i / 4);\n let bandIndex = i % 4;\n if (i === bandCount - 1 && bandIndex === 1) {\n // LUMINANCE_ALPHA - band 1 assigned to rgb and band 2 assigned to alpha\n bandIndex = 3;\n }\n const textureName = `${Uniforms.TILE_TEXTURE_ARRAY}[${colorIndex}]`;\n ifBlocks += `\n if (band == ${i + 1}.0) {\n return texture2D(${textureName}, v_textureCoord + vec2(dx, dy))[${bandIndex}];\n }\n `;\n }\n\n context.functions[GET_BAND_VALUE_FUNC] = `\n float getBandValue(float band, float xOffset, float yOffset) {\n float dx = xOffset / ${Uniforms.TEXTURE_PIXEL_WIDTH};\n float dy = yOffset / ${Uniforms.TEXTURE_PIXEL_HEIGHT};\n ${ifBlocks}\n }\n `;\n }\n\n const bandExpression = expressionToGlsl(context, band);\n const xOffsetExpression = expressionToGlsl(context, args[1] || 0);\n const yOffsetExpression = expressionToGlsl(context, args[2] || 0);\n return `${GET_BAND_VALUE_FUNC}(${bandExpression}, ${xOffsetExpression}, ${yOffsetExpression})`;\n },\n};\n\nOperators['time'] = {\n getReturnType: function () {\n return ValueTypes.NUMBER;\n },\n toGlsl: function (context, args) {\n assertArgsCount(args, 0);\n return 'u_time';\n },\n};\n\nOperators['zoom'] = {\n getReturnType: function () {\n return ValueTypes.NUMBER;\n },\n toGlsl: function (context, args) {\n assertArgsCount(args, 0);\n return 'u_zoom';\n },\n};\n\nOperators['resolution'] = {\n getReturnType: function () {\n return ValueTypes.NUMBER;\n },\n toGlsl: function (context, args) {\n assertArgsCount(args, 0);\n return 'u_resolution';\n },\n};\n\nOperators['geometry-type'] = {\n getReturnType: function () {\n return ValueTypes.STRING;\n },\n toGlsl: function (context, args) {\n assertArgsCount(args, 0);\n const name = 'geometryType';\n const computeType = (geometry) => {\n const type = geometry.getType();\n switch (type) {\n case 'Point':\n case 'LineString':\n case 'Polygon':\n return type;\n case 'MultiPoint':\n case 'MultiLineString':\n case 'MultiPolygon':\n return type.substring(5);\n case 'Circle':\n return 'Polygon';\n case 'GeometryCollection':\n return computeType(geometry.getGeometries()[0]);\n default:\n }\n };\n const existing = context.attributes.find((a) => a.name === name);\n if (!existing) {\n context.attributes.push({\n name: name,\n type: ValueTypes.STRING,\n callback: (feature) => {\n return computeType(feature.getGeometry());\n },\n });\n }\n const prefix = context.inFragmentShader ? 'v_' : 'a_';\n return prefix + name;\n },\n};\n\nOperators['*'] = {\n getReturnType: function (args) {\n let outputType = ValueTypes.NUMBER | ValueTypes.COLOR;\n for (let i = 0; i < args.length; i++) {\n outputType = outputType & getValueType(args[i]);\n }\n return outputType;\n },\n toGlsl: function (context, args, expectedType) {\n assertArgsMinCount(args, 2);\n let outputType = expectedType;\n for (let i = 0; i < args.length; i++) {\n outputType = outputType & getValueType(args[i]);\n }\n assertOfType(\n args,\n outputType,\n ValueTypes.NUMBER | ValueTypes.COLOR,\n 'output'\n );\n return `(${args\n .map((arg) => expressionToGlsl(context, arg, outputType))\n .join(' * ')})`;\n },\n};\n\nOperators['/'] = {\n getReturnType: function () {\n return ValueTypes.NUMBER;\n },\n toGlsl: function (context, args) {\n assertArgsCount(args, 2);\n assertNumbers(args);\n return `(${expressionToGlsl(context, args[0])} / ${expressionToGlsl(\n context,\n args[1]\n )})`;\n },\n};\n\nOperators['+'] = {\n getReturnType: function () {\n return ValueTypes.NUMBER;\n },\n toGlsl: function (context, args) {\n assertArgsMinCount(args, 2);\n assertNumbers(args);\n return `(${args.map((arg) => expressionToGlsl(context, arg)).join(' + ')})`;\n },\n};\n\nOperators['-'] = {\n getReturnType: function () {\n return ValueTypes.NUMBER;\n },\n toGlsl: function (context, args) {\n assertArgsCount(args, 2);\n assertNumbers(args);\n return `(${expressionToGlsl(context, args[0])} - ${expressionToGlsl(\n context,\n args[1]\n )})`;\n },\n};\n\nOperators['clamp'] = {\n getReturnType: function () {\n return ValueTypes.NUMBER;\n },\n toGlsl: function (context, args) {\n assertArgsCount(args, 3);\n assertNumbers(args);\n const min = expressionToGlsl(context, args[1]);\n const max = expressionToGlsl(context, args[2]);\n return `clamp(${expressionToGlsl(context, args[0])}, ${min}, ${max})`;\n },\n};\n\nOperators['%'] = {\n getReturnType: function () {\n return ValueTypes.NUMBER;\n },\n toGlsl: function (context, args) {\n assertArgsCount(args, 2);\n assertNumbers(args);\n return `mod(${expressionToGlsl(context, args[0])}, ${expressionToGlsl(\n context,\n args[1]\n )})`;\n },\n};\n\nOperators['^'] = {\n getReturnType: function () {\n return ValueTypes.NUMBER;\n },\n toGlsl: function (context, args) {\n assertArgsCount(args, 2);\n assertNumbers(args);\n return `pow(${expressionToGlsl(context, args[0])}, ${expressionToGlsl(\n context,\n args[1]\n )})`;\n },\n};\n\nOperators['abs'] = {\n getReturnType: function () {\n return ValueTypes.NUMBER;\n },\n toGlsl: function (context, args) {\n assertArgsCount(args, 1);\n assertNumbers(args);\n return `abs(${expressionToGlsl(context, args[0])})`;\n },\n};\n\nOperators['floor'] = {\n getReturnType: function () {\n return ValueTypes.NUMBER;\n },\n toGlsl: function (context, args) {\n assertArgsCount(args, 1);\n assertNumbers(args);\n return `floor(${expressionToGlsl(context, args[0])})`;\n },\n};\n\nOperators['round'] = {\n getReturnType: function () {\n return ValueTypes.NUMBER;\n },\n toGlsl: function (context, args) {\n assertArgsCount(args, 1);\n assertNumbers(args);\n return `floor(${expressionToGlsl(context, args[0])} + 0.5)`;\n },\n};\n\nOperators['ceil'] = {\n getReturnType: function () {\n return ValueTypes.NUMBER;\n },\n toGlsl: function (context, args) {\n assertArgsCount(args, 1);\n assertNumbers(args);\n return `ceil(${expressionToGlsl(context, args[0])})`;\n },\n};\n\nOperators['sin'] = {\n getReturnType: function () {\n return ValueTypes.NUMBER;\n },\n toGlsl: function (context, args) {\n assertArgsCount(args, 1);\n assertNumbers(args);\n return `sin(${expressionToGlsl(context, args[0])})`;\n },\n};\n\nOperators['cos'] = {\n getReturnType: function () {\n return ValueTypes.NUMBER;\n },\n toGlsl: function (context, args) {\n assertArgsCount(args, 1);\n assertNumbers(args);\n return `cos(${expressionToGlsl(context, args[0])})`;\n },\n};\n\nOperators['atan'] = {\n getReturnType: function () {\n return ValueTypes.NUMBER;\n },\n toGlsl: function (context, args) {\n assertArgsMinCount(args, 1);\n assertArgsMaxCount(args, 2);\n assertNumbers(args);\n return args.length === 2\n ? `atan(${expressionToGlsl(context, args[0])}, ${expressionToGlsl(\n context,\n args[1]\n )})`\n : `atan(${expressionToGlsl(context, args[0])})`;\n },\n};\n\nOperators['sqrt'] = {\n getReturnType: function () {\n return ValueTypes.NUMBER;\n },\n toGlsl: function (context, args) {\n assertArgsCount(args, 1);\n assertNumbers(args);\n return `sqrt(${expressionToGlsl(context, args[0])})`;\n },\n};\n\nOperators['>'] = {\n getReturnType: function () {\n return ValueTypes.BOOLEAN;\n },\n toGlsl: function (context, args) {\n assertArgsCount(args, 2);\n assertNumbers(args);\n return `(${expressionToGlsl(context, args[0])} > ${expressionToGlsl(\n context,\n args[1]\n )})`;\n },\n};\n\nOperators['>='] = {\n getReturnType: function () {\n return ValueTypes.BOOLEAN;\n },\n toGlsl: function (context, args) {\n assertArgsCount(args, 2);\n assertNumbers(args);\n return `(${expressionToGlsl(context, args[0])} >= ${expressionToGlsl(\n context,\n args[1]\n )})`;\n },\n};\n\nOperators['<'] = {\n getReturnType: function () {\n return ValueTypes.BOOLEAN;\n },\n toGlsl: function (context, args) {\n assertArgsCount(args, 2);\n assertNumbers(args);\n return `(${expressionToGlsl(context, args[0])} < ${expressionToGlsl(\n context,\n args[1]\n )})`;\n },\n};\n\nOperators['<='] = {\n getReturnType: function () {\n return ValueTypes.BOOLEAN;\n },\n toGlsl: function (context, args) {\n assertArgsCount(args, 2);\n assertNumbers(args);\n return `(${expressionToGlsl(context, args[0])} <= ${expressionToGlsl(\n context,\n args[1]\n )})`;\n },\n};\n\nfunction getEqualOperator(operator) {\n return {\n getReturnType: function () {\n return ValueTypes.BOOLEAN;\n },\n toGlsl: function (context, args) {\n assertArgsCount(args, 2);\n\n // find common type\n let type = ValueTypes.ANY;\n for (let i = 0; i < args.length; i++) {\n type &= getValueType(args[i]);\n }\n if (type === ValueTypes.NONE) {\n throw new Error(\n `All arguments should be of compatible type, got ${JSON.stringify(\n args\n )} instead`\n );\n }\n\n // Since it's not possible to have color types here, we can leave it out\n // This fixes issues in case the value type is ambiguously detected as a color (e.g. the string 'red')\n type &= ~ValueTypes.COLOR;\n\n return `(${expressionToGlsl(\n context,\n args[0],\n type\n )} ${operator} ${expressionToGlsl(context, args[1], type)})`;\n },\n };\n}\n\nOperators['=='] = getEqualOperator('==');\n\nOperators['!='] = getEqualOperator('!=');\n\nOperators['!'] = {\n getReturnType: function () {\n return ValueTypes.BOOLEAN;\n },\n toGlsl: function (context, args) {\n assertArgsCount(args, 1);\n assertBoolean(args[0]);\n return `(!${expressionToGlsl(context, args[0], ValueTypes.BOOLEAN)})`;\n },\n};\n\nfunction getDecisionOperator(operator) {\n return {\n getReturnType: function () {\n return ValueTypes.BOOLEAN;\n },\n toGlsl: function (context, args) {\n assertArgsMinCount(args, 2);\n for (let i = 0; i < args.length; i++) {\n assertBoolean(args[i]);\n }\n let result = args\n .map((arg) => expressionToGlsl(context, arg, ValueTypes.BOOLEAN))\n .join(` ${operator} `);\n result = `(${result})`;\n return result;\n },\n };\n}\n\nOperators['all'] = getDecisionOperator('&&');\n\nOperators['any'] = getDecisionOperator('||');\n\nOperators['between'] = {\n getReturnType: function () {\n return ValueTypes.BOOLEAN;\n },\n toGlsl: function (context, args) {\n assertArgsCount(args, 3);\n assertNumbers(args);\n const min = expressionToGlsl(context, args[1]);\n const max = expressionToGlsl(context, args[2]);\n const value = expressionToGlsl(context, args[0]);\n return `(${value} >= ${min} && ${value} <= ${max})`;\n },\n};\n\nOperators['array'] = {\n getReturnType: function () {\n return ValueTypes.NUMBER_ARRAY;\n },\n toGlsl: function (context, args) {\n assertArgsMinCount(args, 2);\n assertArgsMaxCount(args, 4);\n assertNumbers(args);\n const parsedArgs = args.map(function (val) {\n return expressionToGlsl(context, val);\n });\n return `vec${args.length}(${parsedArgs.join(', ')})`;\n },\n};\n\nOperators['color'] = {\n getReturnType: function () {\n return ValueTypes.COLOR;\n },\n toGlsl: function (context, args) {\n assertArgsMinCount(args, 3);\n assertArgsMaxCount(args, 4);\n assertNumbers(args);\n const parsedArgs = args\n .slice(0, 3)\n .map((val) => `${expressionToGlsl(context, val)} / 255.0`);\n if (args.length === 3) {\n return `vec4(${parsedArgs.join(', ')}, 1.0)`;\n }\n const alpha = expressionToGlsl(context, args[3]);\n return `(${alpha} * vec4(${parsedArgs.join(', ')}, 1.0))`;\n },\n};\n\nOperators['interpolate'] = {\n getReturnType: function (args) {\n let type = ValueTypes.COLOR | ValueTypes.NUMBER;\n for (let i = 3; i < args.length; i += 2) {\n type = type & getValueType(args[i]);\n }\n return type;\n },\n toGlsl: function (context, args, expectedType) {\n assertArgsEven(args);\n assertArgsMinCount(args, 6);\n\n // validate interpolation type\n const type = args[0];\n let interpolation;\n switch (type[0]) {\n case 'linear':\n interpolation = 1;\n break;\n case 'exponential':\n interpolation = type[1];\n break;\n default:\n interpolation = null;\n }\n if (!interpolation) {\n throw new Error(\n `Invalid interpolation type for \"interpolate\" operator, received: ${JSON.stringify(\n type\n )}`\n );\n }\n\n // compute input/output types\n const inputType = ValueTypes.NUMBER;\n const outputType =\n Operators['interpolate'].getReturnType(args) & expectedType;\n assertSingleType(['interpolate', ...args], outputType, 'output');\n\n const input = expressionToGlsl(context, args[1], inputType);\n const exponent = numberToGlsl(interpolation);\n\n let result = '';\n for (let i = 2; i < args.length - 2; i += 2) {\n const stop1 = expressionToGlsl(context, args[i], inputType);\n const output1 =\n result || expressionToGlsl(context, args[i + 1], outputType);\n const stop2 = expressionToGlsl(context, args[i + 2], inputType);\n const output2 = expressionToGlsl(context, args[i + 3], outputType);\n let ratio;\n if (interpolation === 1) {\n ratio = `(${input} - ${stop1}) / (${stop2} - ${stop1})`;\n } else {\n ratio = `(pow(${exponent}, (${input} - ${stop1})) - 1.0) / (pow(${exponent}, (${stop2} - ${stop1})) - 1.0)`;\n }\n result = `mix(${output1}, ${output2}, clamp(${ratio}, 0.0, 1.0))`;\n }\n return result;\n },\n};\n\nOperators['match'] = {\n getReturnType: function (args) {\n let type = ValueTypes.ANY;\n for (let i = 2; i < args.length; i += 2) {\n type = type & getValueType(args[i]);\n }\n type = type & getValueType(args[args.length - 1]);\n return type;\n },\n toGlsl: function (context, args, expectedType) {\n assertArgsEven(args);\n assertArgsMinCount(args, 4);\n\n let inputType = getValueType(args[0]);\n for (let i = 1; i < args.length - 1; i += 2) {\n inputType = inputType & getValueType(args[i]);\n }\n assertOfType(\n ['match', ...args],\n inputType,\n ValueTypes.STRING | ValueTypes.NUMBER | ValueTypes.BOOLEAN,\n 'input'\n );\n inputType =\n (ValueTypes.STRING | ValueTypes.NUMBER | ValueTypes.BOOLEAN) & inputType;\n\n const outputType = Operators['match'].getReturnType(args) & expectedType;\n assertSingleType(['match', ...args], outputType, 'output');\n\n const input = expressionToGlsl(context, args[0], inputType);\n const fallback = expressionToGlsl(\n context,\n args[args.length - 1],\n outputType\n );\n let result = null;\n for (let i = args.length - 3; i >= 1; i -= 2) {\n const match = expressionToGlsl(context, args[i], inputType);\n const output = expressionToGlsl(context, args[i + 1], outputType);\n result = `(${input} == ${match} ? ${output} : ${result || fallback})`;\n }\n return result;\n },\n};\n\nOperators['case'] = {\n getReturnType: function (args) {\n let type = ValueTypes.ANY;\n for (let i = 1; i < args.length; i += 2) {\n type = type & getValueType(args[i]);\n }\n type = type & getValueType(args[args.length - 1]);\n return type;\n },\n toGlsl: function (context, args, expectedType) {\n assertArgsOdd(args);\n assertArgsMinCount(args, 3);\n\n const outputType = Operators['case'].getReturnType(args) & expectedType;\n assertSingleType(['case', ...args], outputType, 'output');\n for (let i = 0; i < args.length - 1; i += 2) {\n assertBoolean(args[i]);\n }\n\n const fallback = expressionToGlsl(\n context,\n args[args.length - 1],\n outputType\n );\n let result = null;\n for (let i = args.length - 3; i >= 0; i -= 2) {\n const condition = expressionToGlsl(context, args[i], ValueTypes.BOOLEAN);\n const output = expressionToGlsl(context, args[i + 1], outputType);\n result = `(${condition} ? ${output} : ${result || fallback})`;\n }\n return result;\n },\n};\n\nOperators['in'] = {\n getReturnType: function (args) {\n return ValueTypes.BOOLEAN;\n },\n toGlsl: function (context, args) {\n assertArgsCount(args, 2);\n const needle = args[0];\n let haystack = args[1];\n if (!Array.isArray(haystack)) {\n throw new Error(\n `The \"in\" operator expects an array literal as its second argument.`\n );\n }\n if (typeof haystack[0] === 'string') {\n if (haystack[0] !== 'literal') {\n throw new Error(\n `For the \"in\" operator, a string array should be wrapped in a \"literal\" operator to disambiguate from expressions.`\n );\n }\n if (!Array.isArray(haystack[1])) {\n throw new Error(\n `The \"in\" operator was provided a literal value which was not an array as second argument.`\n );\n }\n haystack = haystack[1];\n }\n\n let inputType = getValueType(needle);\n for (let i = 0; i < haystack.length - 1; i += 1) {\n inputType = inputType & getValueType(haystack[i]);\n }\n assertOfType(\n ['match', ...args],\n inputType,\n ValueTypes.STRING | ValueTypes.NUMBER | ValueTypes.BOOLEAN,\n 'input'\n );\n inputType =\n (ValueTypes.STRING | ValueTypes.NUMBER | ValueTypes.BOOLEAN) & inputType;\n\n const funcName = computeOperatorFunctionName('in', context);\n const tests = [];\n for (let i = 0; i < haystack.length; i += 1) {\n tests.push(\n ` if (inputValue == ${expressionToGlsl(\n context,\n haystack[i],\n inputType\n )}) { return true; }`\n );\n }\n context.functions[funcName] = `bool ${funcName}(float inputValue) {\n${tests.join('\\n')}\n return false;\n}`;\n return `${funcName}(${expressionToGlsl(context, needle, inputType)})`;\n },\n};\n","/**\n * @module ol/style/Image\n */\nimport {abstract} from '../util.js';\nimport {toSize} from '../size.js';\n\n/**\n * @typedef {Object} Options\n * @property {number} opacity Opacity.\n * @property {boolean} rotateWithView If the image should get rotated with the view.\n * @property {number} rotation Rotation.\n * @property {number|import(\"../size.js\").Size} scale Scale.\n * @property {Array} displacement Displacement.\n * @property {\"declutter\"|\"obstacle\"|\"none\"|undefined} declutterMode Declutter mode: `declutter`, `obstacle`, 'none */\n\n/**\n * @classdesc\n * A base class used for creating subclasses and not instantiated in\n * apps. Base class for {@link module:ol/style/Icon~Icon}, {@link module:ol/style/Circle~CircleStyle} and\n * {@link module:ol/style/RegularShape~RegularShape}.\n * @abstract\n * @api\n */\nclass ImageStyle {\n /**\n * @param {Options} options Options.\n */\n constructor(options) {\n /**\n * @private\n * @type {number}\n */\n this.opacity_ = options.opacity;\n\n /**\n * @private\n * @type {boolean}\n */\n this.rotateWithView_ = options.rotateWithView;\n\n /**\n * @private\n * @type {number}\n */\n this.rotation_ = options.rotation;\n\n /**\n * @private\n * @type {number|import(\"../size.js\").Size}\n */\n this.scale_ = options.scale;\n\n /**\n * @private\n * @type {import(\"../size.js\").Size}\n */\n this.scaleArray_ = toSize(options.scale);\n\n /**\n * @private\n * @type {Array}\n */\n this.displacement_ = options.displacement;\n\n /**\n * @private\n * @type {\"declutter\"|\"obstacle\"|\"none\"|undefined}\n */\n this.declutterMode_ = options.declutterMode;\n }\n\n /**\n * Clones the style.\n * @return {ImageStyle} The cloned style.\n * @api\n */\n clone() {\n const scale = this.getScale();\n return new ImageStyle({\n opacity: this.getOpacity(),\n scale: Array.isArray(scale) ? scale.slice() : scale,\n rotation: this.getRotation(),\n rotateWithView: this.getRotateWithView(),\n displacement: this.getDisplacement().slice(),\n declutterMode: this.getDeclutterMode(),\n });\n }\n\n /**\n * Get the symbolizer opacity.\n * @return {number} Opacity.\n * @api\n */\n getOpacity() {\n return this.opacity_;\n }\n\n /**\n * Determine whether the symbolizer rotates with the map.\n * @return {boolean} Rotate with map.\n * @api\n */\n getRotateWithView() {\n return this.rotateWithView_;\n }\n\n /**\n * Get the symoblizer rotation.\n * @return {number} Rotation.\n * @api\n */\n getRotation() {\n return this.rotation_;\n }\n\n /**\n * Get the symbolizer scale.\n * @return {number|import(\"../size.js\").Size} Scale.\n * @api\n */\n getScale() {\n return this.scale_;\n }\n\n /**\n * Get the symbolizer scale array.\n * @return {import(\"../size.js\").Size} Scale array.\n */\n getScaleArray() {\n return this.scaleArray_;\n }\n\n /**\n * Get the displacement of the shape\n * @return {Array} Shape's center displacement\n * @api\n */\n getDisplacement() {\n return this.displacement_;\n }\n\n /**\n * Get the declutter mode of the shape\n * @return {\"declutter\"|\"obstacle\"|\"none\"|undefined} Shape's declutter mode\n * @api\n */\n getDeclutterMode() {\n return this.declutterMode_;\n }\n\n /**\n * Get the anchor point in pixels. The anchor determines the center point for the\n * symbolizer.\n * @abstract\n * @return {Array} Anchor.\n */\n getAnchor() {\n return abstract();\n }\n\n /**\n * Get the image element for the symbolizer.\n * @abstract\n * @param {number} pixelRatio Pixel ratio.\n * @return {HTMLCanvasElement|HTMLVideoElement|HTMLImageElement} Image element.\n */\n getImage(pixelRatio) {\n return abstract();\n }\n\n /**\n * @abstract\n * @return {HTMLCanvasElement|HTMLVideoElement|HTMLImageElement} Image element.\n */\n getHitDetectionImage() {\n return abstract();\n }\n\n /**\n * Get the image pixel ratio.\n * @param {number} pixelRatio Pixel ratio.\n * @return {number} Pixel ratio.\n */\n getPixelRatio(pixelRatio) {\n return 1;\n }\n\n /**\n * @abstract\n * @return {import(\"../ImageState.js\").default} Image state.\n */\n getImageState() {\n return abstract();\n }\n\n /**\n * @abstract\n * @return {import(\"../size.js\").Size} Image size.\n */\n getImageSize() {\n return abstract();\n }\n\n /**\n * Get the origin of the symbolizer.\n * @abstract\n * @return {Array} Origin.\n */\n getOrigin() {\n return abstract();\n }\n\n /**\n * Get the size of the symbolizer (in pixels).\n * @abstract\n * @return {import(\"../size.js\").Size} Size.\n */\n getSize() {\n return abstract();\n }\n\n /**\n * Set the displacement.\n *\n * @param {Array} displacement Displacement.\n * @api\n */\n setDisplacement(displacement) {\n this.displacement_ = displacement;\n }\n\n /**\n * Set the opacity.\n *\n * @param {number} opacity Opacity.\n * @api\n */\n setOpacity(opacity) {\n this.opacity_ = opacity;\n }\n\n /**\n * Set whether to rotate the style with the view.\n *\n * @param {boolean} rotateWithView Rotate with map.\n * @api\n */\n setRotateWithView(rotateWithView) {\n this.rotateWithView_ = rotateWithView;\n }\n\n /**\n * Set the rotation.\n *\n * @param {number} rotation Rotation.\n * @api\n */\n setRotation(rotation) {\n this.rotation_ = rotation;\n }\n\n /**\n * Set the scale.\n *\n * @param {number|import(\"../size.js\").Size} scale Scale.\n * @api\n */\n setScale(scale) {\n this.scale_ = scale;\n this.scaleArray_ = toSize(scale);\n }\n\n /**\n * @abstract\n * @param {function(import(\"../events/Event.js\").default): void} listener Listener function.\n */\n listenImageChange(listener) {\n abstract();\n }\n\n /**\n * Load not yet loaded URI.\n * @abstract\n */\n load() {\n abstract();\n }\n\n /**\n * @abstract\n * @param {function(import(\"../events/Event.js\").default): void} listener Listener function.\n */\n unlistenImageChange(listener) {\n abstract();\n }\n}\n\nexport default ImageStyle;\n","/**\n * @module ol/style/RegularShape\n */\n\nimport ImageState from '../ImageState.js';\nimport ImageStyle from './Image.js';\nimport {asArray} from '../color.js';\nimport {asColorLike} from '../colorlike.js';\nimport {createCanvasContext2D} from '../dom.js';\nimport {\n defaultFillStyle,\n defaultLineJoin,\n defaultLineWidth,\n defaultMiterLimit,\n defaultStrokeStyle,\n} from '../render/canvas.js';\n\n/**\n * Specify radius for regular polygons, or radius1 and radius2 for stars.\n * @typedef {Object} Options\n * @property {import(\"./Fill.js\").default} [fill] Fill style.\n * @property {number} points Number of points for stars and regular polygons. In case of a polygon, the number of points\n * is the number of sides.\n * @property {number} [radius] Radius of a regular polygon.\n * @property {number} [radius1] First radius of a star. Ignored if radius is set.\n * @property {number} [radius2] Second radius of a star.\n * @property {number} [angle=0] Shape's angle in radians. A value of 0 will have one of the shape's points facing up.\n * @property {Array} [displacement=[0, 0]] Displacement of the shape in pixels.\n * Positive values will shift the shape right and up.\n * @property {import(\"./Stroke.js\").default} [stroke] Stroke style.\n * @property {number} [rotation=0] Rotation in radians (positive rotation clockwise).\n * @property {boolean} [rotateWithView=false] Whether to rotate the shape with the view.\n * @property {number|import(\"../size.js\").Size} [scale=1] Scale. Unless two dimensional scaling is required a better\n * result may be obtained with appropriate settings for `radius`, `radius1` and `radius2`.\n * @property {\"declutter\"|\"obstacle\"|\"none\"|undefined} [declutterMode] Declutter mode.\n */\n\n/**\n * @typedef {Object} RenderOptions\n * @property {import(\"../colorlike.js\").ColorLike} [strokeStyle] StrokeStyle.\n * @property {number} strokeWidth StrokeWidth.\n * @property {number} size Size.\n * @property {Array|null} lineDash LineDash.\n * @property {number} lineDashOffset LineDashOffset.\n * @property {CanvasLineJoin} lineJoin LineJoin.\n * @property {number} miterLimit MiterLimit.\n */\n\n/**\n * @classdesc\n * Set regular shape style for vector features. The resulting shape will be\n * a regular polygon when `radius` is provided, or a star when `radius1` and\n * `radius2` are provided.\n * @api\n */\nclass RegularShape extends ImageStyle {\n /**\n * @param {Options} options Options.\n */\n constructor(options) {\n /**\n * @type {boolean}\n */\n const rotateWithView =\n options.rotateWithView !== undefined ? options.rotateWithView : false;\n\n super({\n opacity: 1,\n rotateWithView: rotateWithView,\n rotation: options.rotation !== undefined ? options.rotation : 0,\n scale: options.scale !== undefined ? options.scale : 1,\n displacement:\n options.displacement !== undefined ? options.displacement : [0, 0],\n declutterMode: options.declutterMode,\n });\n\n /**\n * @private\n * @type {Object}\n */\n this.canvas_ = undefined;\n\n /**\n * @private\n * @type {HTMLCanvasElement}\n */\n this.hitDetectionCanvas_ = null;\n\n /**\n * @private\n * @type {import(\"./Fill.js\").default}\n */\n this.fill_ = options.fill !== undefined ? options.fill : null;\n\n /**\n * @private\n * @type {Array}\n */\n this.origin_ = [0, 0];\n\n /**\n * @private\n * @type {number}\n */\n this.points_ = options.points;\n\n /**\n * @protected\n * @type {number}\n */\n this.radius_ =\n options.radius !== undefined ? options.radius : options.radius1;\n\n /**\n * @private\n * @type {number|undefined}\n */\n this.radius2_ = options.radius2;\n\n /**\n * @private\n * @type {number}\n */\n this.angle_ = options.angle !== undefined ? options.angle : 0;\n\n /**\n * @private\n * @type {import(\"./Stroke.js\").default}\n */\n this.stroke_ = options.stroke !== undefined ? options.stroke : null;\n\n /**\n * @private\n * @type {import(\"../size.js\").Size}\n */\n this.size_ = null;\n\n /**\n * @private\n * @type {RenderOptions}\n */\n this.renderOptions_ = null;\n\n this.render();\n }\n\n /**\n * Clones the style.\n * @return {RegularShape} The cloned style.\n * @api\n */\n clone() {\n const scale = this.getScale();\n const style = new RegularShape({\n fill: this.getFill() ? this.getFill().clone() : undefined,\n points: this.getPoints(),\n radius: this.getRadius(),\n radius2: this.getRadius2(),\n angle: this.getAngle(),\n stroke: this.getStroke() ? this.getStroke().clone() : undefined,\n rotation: this.getRotation(),\n rotateWithView: this.getRotateWithView(),\n scale: Array.isArray(scale) ? scale.slice() : scale,\n displacement: this.getDisplacement().slice(),\n declutterMode: this.getDeclutterMode(),\n });\n style.setOpacity(this.getOpacity());\n return style;\n }\n\n /**\n * Get the anchor point in pixels. The anchor determines the center point for the\n * symbolizer.\n * @return {Array} Anchor.\n * @api\n */\n getAnchor() {\n const size = this.size_;\n if (!size) {\n return null;\n }\n const displacement = this.getDisplacement();\n const scale = this.getScaleArray();\n // anchor is scaled by renderer but displacement should not be scaled\n // so divide by scale here\n return [\n size[0] / 2 - displacement[0] / scale[0],\n size[1] / 2 + displacement[1] / scale[1],\n ];\n }\n\n /**\n * Get the angle used in generating the shape.\n * @return {number} Shape's rotation in radians.\n * @api\n */\n getAngle() {\n return this.angle_;\n }\n\n /**\n * Get the fill style for the shape.\n * @return {import(\"./Fill.js\").default} Fill style.\n * @api\n */\n getFill() {\n return this.fill_;\n }\n\n /**\n * Set the fill style.\n * @param {import(\"./Fill.js\").default} fill Fill style.\n * @api\n */\n setFill(fill) {\n this.fill_ = fill;\n this.render();\n }\n\n /**\n * @return {HTMLCanvasElement} Image element.\n */\n getHitDetectionImage() {\n if (!this.hitDetectionCanvas_) {\n this.createHitDetectionCanvas_(this.renderOptions_);\n }\n return this.hitDetectionCanvas_;\n }\n\n /**\n * Get the image icon.\n * @param {number} pixelRatio Pixel ratio.\n * @return {HTMLCanvasElement} Image or Canvas element.\n * @api\n */\n getImage(pixelRatio) {\n let image = this.canvas_[pixelRatio];\n if (!image) {\n const renderOptions = this.renderOptions_;\n const context = createCanvasContext2D(\n renderOptions.size * pixelRatio,\n renderOptions.size * pixelRatio\n );\n this.draw_(renderOptions, context, pixelRatio);\n\n image = context.canvas;\n this.canvas_[pixelRatio] = image;\n }\n return image;\n }\n\n /**\n * Get the image pixel ratio.\n * @param {number} pixelRatio Pixel ratio.\n * @return {number} Pixel ratio.\n */\n getPixelRatio(pixelRatio) {\n return pixelRatio;\n }\n\n /**\n * @return {import(\"../size.js\").Size} Image size.\n */\n getImageSize() {\n return this.size_;\n }\n\n /**\n * @return {import(\"../ImageState.js\").default} Image state.\n */\n getImageState() {\n return ImageState.LOADED;\n }\n\n /**\n * Get the origin of the symbolizer.\n * @return {Array} Origin.\n * @api\n */\n getOrigin() {\n return this.origin_;\n }\n\n /**\n * Get the number of points for generating the shape.\n * @return {number} Number of points for stars and regular polygons.\n * @api\n */\n getPoints() {\n return this.points_;\n }\n\n /**\n * Get the (primary) radius for the shape.\n * @return {number} Radius.\n * @api\n */\n getRadius() {\n return this.radius_;\n }\n\n /**\n * Get the secondary radius for the shape.\n * @return {number|undefined} Radius2.\n * @api\n */\n getRadius2() {\n return this.radius2_;\n }\n\n /**\n * Get the size of the symbolizer (in pixels).\n * @return {import(\"../size.js\").Size} Size.\n * @api\n */\n getSize() {\n return this.size_;\n }\n\n /**\n * Get the stroke style for the shape.\n * @return {import(\"./Stroke.js\").default} Stroke style.\n * @api\n */\n getStroke() {\n return this.stroke_;\n }\n\n /**\n * Set the stroke style.\n * @param {import(\"./Stroke.js\").default} stroke Stroke style.\n * @api\n */\n setStroke(stroke) {\n this.stroke_ = stroke;\n this.render();\n }\n\n /**\n * @param {function(import(\"../events/Event.js\").default): void} listener Listener function.\n */\n listenImageChange(listener) {}\n\n /**\n * Load not yet loaded URI.\n */\n load() {}\n\n /**\n * @param {function(import(\"../events/Event.js\").default): void} listener Listener function.\n */\n unlistenImageChange(listener) {}\n\n /**\n * Calculate additional canvas size needed for the miter.\n * @param {string} lineJoin Line join\n * @param {number} strokeWidth Stroke width\n * @param {number} miterLimit Miter limit\n * @return {number} Additional canvas size needed\n * @private\n */\n calculateLineJoinSize_(lineJoin, strokeWidth, miterLimit) {\n if (\n strokeWidth === 0 ||\n this.points_ === Infinity ||\n (lineJoin !== 'bevel' && lineJoin !== 'miter')\n ) {\n return strokeWidth;\n }\n // m | ^\n // i | |\\ .\n // t >| #\\\n // e | |\\ \\ .\n // r \\s\\\n // | \\t\\ . .\n // \\r\\ . .\n // | \\o\\ . . . . .\n // e \\k\\ . . . .\n // | \\e\\ . . . . .\n // d \\ \\ . . . .\n // | _ _a_ _\\# . . .\n // r1 / ` . .\n // | . .\n // b / . .\n // | . .\n // / r2 . .\n // | . .\n // / . .\n // |α . .\n // / . .\n // ° center\n let r1 = this.radius_;\n let r2 = this.radius2_ === undefined ? r1 : this.radius2_;\n if (r1 < r2) {\n const tmp = r1;\n r1 = r2;\n r2 = tmp;\n }\n const points =\n this.radius2_ === undefined ? this.points_ : this.points_ * 2;\n const alpha = (2 * Math.PI) / points;\n const a = r2 * Math.sin(alpha);\n const b = Math.sqrt(r2 * r2 - a * a);\n const d = r1 - b;\n const e = Math.sqrt(a * a + d * d);\n const miterRatio = e / a;\n if (lineJoin === 'miter' && miterRatio <= miterLimit) {\n return miterRatio * strokeWidth;\n }\n // Calculate the distance from center to the stroke corner where\n // it was cut short because of the miter limit.\n // l\n // ----+---- <= distance from center to here is maxr\n // /####|k ##\\\n // /#####^#####\\\n // /#### /+\\# s #\\\n // /### h/+++\\# t #\\\n // /### t/+++++\\# r #\\\n // /### a/+++++++\\# o #\\\n // /### p/++ fill +\\# k #\\\n ///#### /+++++^+++++\\# e #\\\n //#####/+++++/+\\+++++\\#####\\\n const k = strokeWidth / 2 / miterRatio;\n const l = (strokeWidth / 2) * (d / e);\n const maxr = Math.sqrt((r1 + k) * (r1 + k) + l * l);\n const bevelAdd = maxr - r1;\n if (this.radius2_ === undefined || lineJoin === 'bevel') {\n return bevelAdd * 2;\n }\n // If outer miter is over the miter limit the inner miter may reach through the\n // center and be longer than the bevel, same calculation as above but swap r1 / r2.\n const aa = r1 * Math.sin(alpha);\n const bb = Math.sqrt(r1 * r1 - aa * aa);\n const dd = r2 - bb;\n const ee = Math.sqrt(aa * aa + dd * dd);\n const innerMiterRatio = ee / aa;\n if (innerMiterRatio <= miterLimit) {\n const innerLength = (innerMiterRatio * strokeWidth) / 2 - r2 - r1;\n return 2 * Math.max(bevelAdd, innerLength);\n }\n return bevelAdd * 2;\n }\n\n /**\n * @return {RenderOptions} The render options\n * @protected\n */\n createRenderOptions() {\n let lineJoin = defaultLineJoin;\n let miterLimit = 0;\n let lineDash = null;\n let lineDashOffset = 0;\n let strokeStyle;\n let strokeWidth = 0;\n\n if (this.stroke_) {\n strokeStyle = this.stroke_.getColor();\n if (strokeStyle === null) {\n strokeStyle = defaultStrokeStyle;\n }\n strokeStyle = asColorLike(strokeStyle);\n strokeWidth = this.stroke_.getWidth();\n if (strokeWidth === undefined) {\n strokeWidth = defaultLineWidth;\n }\n lineDash = this.stroke_.getLineDash();\n lineDashOffset = this.stroke_.getLineDashOffset();\n lineJoin = this.stroke_.getLineJoin();\n if (lineJoin === undefined) {\n lineJoin = defaultLineJoin;\n }\n miterLimit = this.stroke_.getMiterLimit();\n if (miterLimit === undefined) {\n miterLimit = defaultMiterLimit;\n }\n }\n\n const add = this.calculateLineJoinSize_(lineJoin, strokeWidth, miterLimit);\n const maxRadius = Math.max(this.radius_, this.radius2_ || 0);\n const size = Math.ceil(2 * maxRadius + add);\n\n return {\n strokeStyle: strokeStyle,\n strokeWidth: strokeWidth,\n size: size,\n lineDash: lineDash,\n lineDashOffset: lineDashOffset,\n lineJoin: lineJoin,\n miterLimit: miterLimit,\n };\n }\n\n /**\n * @protected\n */\n render() {\n this.renderOptions_ = this.createRenderOptions();\n const size = this.renderOptions_.size;\n this.canvas_ = {};\n this.size_ = [size, size];\n }\n\n /**\n * @private\n * @param {RenderOptions} renderOptions Render options.\n * @param {CanvasRenderingContext2D} context The rendering context.\n * @param {number} pixelRatio The pixel ratio.\n */\n draw_(renderOptions, context, pixelRatio) {\n context.scale(pixelRatio, pixelRatio);\n // set origin to canvas center\n context.translate(renderOptions.size / 2, renderOptions.size / 2);\n\n this.createPath_(context);\n\n if (this.fill_) {\n let color = this.fill_.getColor();\n if (color === null) {\n color = defaultFillStyle;\n }\n context.fillStyle = asColorLike(color);\n context.fill();\n }\n if (this.stroke_) {\n context.strokeStyle = renderOptions.strokeStyle;\n context.lineWidth = renderOptions.strokeWidth;\n if (renderOptions.lineDash) {\n context.setLineDash(renderOptions.lineDash);\n context.lineDashOffset = renderOptions.lineDashOffset;\n }\n context.lineJoin = renderOptions.lineJoin;\n context.miterLimit = renderOptions.miterLimit;\n context.stroke();\n }\n }\n\n /**\n * @private\n * @param {RenderOptions} renderOptions Render options.\n */\n createHitDetectionCanvas_(renderOptions) {\n if (this.fill_) {\n let color = this.fill_.getColor();\n\n // determine if fill is transparent (or pattern or gradient)\n let opacity = 0;\n if (typeof color === 'string') {\n color = asArray(color);\n }\n if (color === null) {\n opacity = 1;\n } else if (Array.isArray(color)) {\n opacity = color.length === 4 ? color[3] : 1;\n }\n if (opacity === 0) {\n // if a transparent fill style is set, create an extra hit-detection image\n // with a default fill style\n const context = createCanvasContext2D(\n renderOptions.size,\n renderOptions.size\n );\n this.hitDetectionCanvas_ = context.canvas;\n\n this.drawHitDetectionCanvas_(renderOptions, context);\n }\n }\n if (!this.hitDetectionCanvas_) {\n this.hitDetectionCanvas_ = this.getImage(1);\n }\n }\n\n /**\n * @private\n * @param {CanvasRenderingContext2D} context The context to draw in.\n */\n createPath_(context) {\n let points = this.points_;\n const radius = this.radius_;\n if (points === Infinity) {\n context.arc(0, 0, radius, 0, 2 * Math.PI);\n } else {\n const radius2 = this.radius2_ === undefined ? radius : this.radius2_;\n if (this.radius2_ !== undefined) {\n points *= 2;\n }\n const startAngle = this.angle_ - Math.PI / 2;\n const step = (2 * Math.PI) / points;\n for (let i = 0; i < points; i++) {\n const angle0 = startAngle + i * step;\n const radiusC = i % 2 === 0 ? radius : radius2;\n context.lineTo(radiusC * Math.cos(angle0), radiusC * Math.sin(angle0));\n }\n context.closePath();\n }\n }\n\n /**\n * @private\n * @param {RenderOptions} renderOptions Render options.\n * @param {CanvasRenderingContext2D} context The context.\n */\n drawHitDetectionCanvas_(renderOptions, context) {\n // set origin to canvas center\n context.translate(renderOptions.size / 2, renderOptions.size / 2);\n\n this.createPath_(context);\n\n context.fillStyle = defaultFillStyle;\n context.fill();\n if (this.stroke_) {\n context.strokeStyle = renderOptions.strokeStyle;\n context.lineWidth = renderOptions.strokeWidth;\n if (renderOptions.lineDash) {\n context.setLineDash(renderOptions.lineDash);\n context.lineDashOffset = renderOptions.lineDashOffset;\n }\n context.lineJoin = renderOptions.lineJoin;\n context.miterLimit = renderOptions.miterLimit;\n context.stroke();\n }\n }\n}\n\nexport default RegularShape;\n","/**\n * @module ol/style/Circle\n */\n\nimport RegularShape from './RegularShape.js';\n\n/**\n * @typedef {Object} Options\n * @property {import(\"./Fill.js\").default} [fill] Fill style.\n * @property {number} radius Circle radius.\n * @property {import(\"./Stroke.js\").default} [stroke] Stroke style.\n * @property {Array} [displacement=[0,0]] displacement\n * @property {number|import(\"../size.js\").Size} [scale=1] Scale. A two dimensional scale will produce an ellipse.\n * Unless two dimensional scaling is required a better result may be obtained with an appropriate setting for `radius`.\n * @property {number} [rotation=0] Rotation in radians\n * (positive rotation clockwise, meaningful only when used in conjunction with a two dimensional scale).\n * @property {boolean} [rotateWithView=false] Whether to rotate the shape with the view\n * (meaningful only when used in conjunction with a two dimensional scale).\n * @property {\"declutter\"|\"obstacle\"|\"none\"|undefined} [declutterMode] Declutter mode\n */\n\n/**\n * @classdesc\n * Set circle style for vector features.\n * @api\n */\nclass CircleStyle extends RegularShape {\n /**\n * @param {Options} [options] Options.\n */\n constructor(options) {\n options = options ? options : {radius: 5};\n\n super({\n points: Infinity,\n fill: options.fill,\n radius: options.radius,\n stroke: options.stroke,\n scale: options.scale !== undefined ? options.scale : 1,\n rotation: options.rotation !== undefined ? options.rotation : 0,\n rotateWithView:\n options.rotateWithView !== undefined ? options.rotateWithView : false,\n displacement:\n options.displacement !== undefined ? options.displacement : [0, 0],\n declutterMode: options.declutterMode,\n });\n }\n\n /**\n * Clones the style.\n * @return {CircleStyle} The cloned style.\n * @api\n */\n clone() {\n const scale = this.getScale();\n const style = new CircleStyle({\n fill: this.getFill() ? this.getFill().clone() : undefined,\n stroke: this.getStroke() ? this.getStroke().clone() : undefined,\n radius: this.getRadius(),\n scale: Array.isArray(scale) ? scale.slice() : scale,\n rotation: this.getRotation(),\n rotateWithView: this.getRotateWithView(),\n displacement: this.getDisplacement().slice(),\n declutterMode: this.getDeclutterMode(),\n });\n style.setOpacity(this.getOpacity());\n return style;\n }\n\n /**\n * Set the circle radius.\n *\n * @param {number} radius Circle radius.\n * @api\n */\n setRadius(radius) {\n this.radius_ = radius;\n this.render();\n }\n}\n\nexport default CircleStyle;\n","/**\n * @module ol/style/Fill\n */\n\n/**\n * @typedef {Object} Options\n * @property {import(\"../color.js\").Color|import(\"../colorlike.js\").ColorLike|null} [color=null] A color, gradient or pattern.\n * See {@link module:ol/color~Color} and {@link module:ol/colorlike~ColorLike} for possible formats.\n * Default null; if null, the Canvas/renderer default black will be used.\n */\n\n/**\n * @classdesc\n * Set fill style for vector features.\n * @api\n */\nclass Fill {\n /**\n * @param {Options} [options] Options.\n */\n constructor(options) {\n options = options || {};\n\n /**\n * @private\n * @type {import(\"../color.js\").Color|import(\"../colorlike.js\").ColorLike|null}\n */\n this.color_ = options.color !== undefined ? options.color : null;\n }\n\n /**\n * Clones the style. The color is not cloned if it is an {@link module:ol/colorlike~ColorLike}.\n * @return {Fill} The cloned style.\n * @api\n */\n clone() {\n const color = this.getColor();\n return new Fill({\n color: Array.isArray(color) ? color.slice() : color || undefined,\n });\n }\n\n /**\n * Get the fill color.\n * @return {import(\"../color.js\").Color|import(\"../colorlike.js\").ColorLike|null} Color.\n * @api\n */\n getColor() {\n return this.color_;\n }\n\n /**\n * Set the color.\n *\n * @param {import(\"../color.js\").Color|import(\"../colorlike.js\").ColorLike|null} color Color.\n * @api\n */\n setColor(color) {\n this.color_ = color;\n }\n}\n\nexport default Fill;\n","/**\n * @module ol/style/IconImage\n */\n\nimport EventTarget from '../events/Target.js';\nimport EventType from '../events/EventType.js';\nimport ImageState from '../ImageState.js';\nimport {asString} from '../color.js';\nimport {createCanvasContext2D} from '../dom.js';\nimport {shared as iconImageCache} from './IconImageCache.js';\nimport {listenImage} from '../Image.js';\n\n/**\n * @type {CanvasRenderingContext2D}\n */\nlet taintedTestContext = null;\n\nclass IconImage extends EventTarget {\n /**\n * @param {HTMLImageElement|HTMLCanvasElement} image Image.\n * @param {string|undefined} src Src.\n * @param {import(\"../size.js\").Size} size Size.\n * @param {?string} crossOrigin Cross origin.\n * @param {import(\"../ImageState.js\").default} imageState Image state.\n * @param {import(\"../color.js\").Color} color Color.\n */\n constructor(image, src, size, crossOrigin, imageState, color) {\n super();\n\n /**\n * @private\n * @type {HTMLImageElement|HTMLCanvasElement}\n */\n this.hitDetectionImage_ = null;\n\n /**\n * @private\n * @type {HTMLImageElement|HTMLCanvasElement}\n */\n this.image_ = image;\n\n /**\n * @private\n * @type {string|null}\n */\n this.crossOrigin_ = crossOrigin;\n\n /**\n * @private\n * @type {Object}\n */\n this.canvas_ = {};\n\n /**\n * @private\n * @type {import(\"../color.js\").Color}\n */\n this.color_ = color;\n\n /**\n * @private\n * @type {?function():void}\n */\n this.unlisten_ = null;\n\n /**\n * @private\n * @type {import(\"../ImageState.js\").default}\n */\n this.imageState_ = imageState;\n\n /**\n * @private\n * @type {import(\"../size.js\").Size}\n */\n this.size_ = size;\n\n /**\n * @private\n * @type {string|undefined}\n */\n this.src_ = src;\n\n /**\n * @private\n */\n this.tainted_;\n }\n\n /**\n * @private\n */\n initializeImage_() {\n this.image_ = new Image();\n if (this.crossOrigin_ !== null) {\n this.image_.crossOrigin = this.crossOrigin_;\n }\n }\n\n /**\n * @private\n * @return {boolean} The image canvas is tainted.\n */\n isTainted_() {\n if (this.tainted_ === undefined && this.imageState_ === ImageState.LOADED) {\n if (!taintedTestContext) {\n taintedTestContext = createCanvasContext2D(1, 1, undefined, {\n willReadFrequently: true,\n });\n }\n taintedTestContext.drawImage(this.image_, 0, 0);\n try {\n taintedTestContext.getImageData(0, 0, 1, 1);\n this.tainted_ = false;\n } catch (e) {\n taintedTestContext = null;\n this.tainted_ = true;\n }\n }\n return this.tainted_ === true;\n }\n\n /**\n * @private\n */\n dispatchChangeEvent_() {\n this.dispatchEvent(EventType.CHANGE);\n }\n\n /**\n * @private\n */\n handleImageError_() {\n this.imageState_ = ImageState.ERROR;\n this.unlistenImage_();\n this.dispatchChangeEvent_();\n }\n\n /**\n * @private\n */\n handleImageLoad_() {\n this.imageState_ = ImageState.LOADED;\n if (this.size_) {\n this.image_.width = this.size_[0];\n this.image_.height = this.size_[1];\n } else {\n this.size_ = [this.image_.width, this.image_.height];\n }\n this.unlistenImage_();\n this.dispatchChangeEvent_();\n }\n\n /**\n * @param {number} pixelRatio Pixel ratio.\n * @return {HTMLImageElement|HTMLCanvasElement} Image or Canvas element.\n */\n getImage(pixelRatio) {\n if (!this.image_) {\n this.initializeImage_();\n }\n this.replaceColor_(pixelRatio);\n return this.canvas_[pixelRatio] ? this.canvas_[pixelRatio] : this.image_;\n }\n\n /**\n * @param {number} pixelRatio Pixel ratio.\n * @return {number} Image or Canvas element.\n */\n getPixelRatio(pixelRatio) {\n this.replaceColor_(pixelRatio);\n return this.canvas_[pixelRatio] ? pixelRatio : 1;\n }\n\n /**\n * @return {import(\"../ImageState.js\").default} Image state.\n */\n getImageState() {\n return this.imageState_;\n }\n\n /**\n * @return {HTMLImageElement|HTMLCanvasElement} Image element.\n */\n getHitDetectionImage() {\n if (!this.image_) {\n this.initializeImage_();\n }\n if (!this.hitDetectionImage_) {\n if (this.isTainted_()) {\n const width = this.size_[0];\n const height = this.size_[1];\n const context = createCanvasContext2D(width, height);\n context.fillRect(0, 0, width, height);\n this.hitDetectionImage_ = context.canvas;\n } else {\n this.hitDetectionImage_ = this.image_;\n }\n }\n return this.hitDetectionImage_;\n }\n\n /**\n * Get the size of the icon (in pixels).\n * @return {import(\"../size.js\").Size} Image size.\n */\n getSize() {\n return this.size_;\n }\n\n /**\n * @return {string|undefined} Image src.\n */\n getSrc() {\n return this.src_;\n }\n\n /**\n * Load not yet loaded URI.\n */\n load() {\n if (this.imageState_ !== ImageState.IDLE) {\n return;\n }\n if (!this.image_) {\n this.initializeImage_();\n }\n\n this.imageState_ = ImageState.LOADING;\n try {\n /** @type {HTMLImageElement} */ (this.image_).src = this.src_;\n } catch (e) {\n this.handleImageError_();\n }\n this.unlisten_ = listenImage(\n this.image_,\n this.handleImageLoad_.bind(this),\n this.handleImageError_.bind(this)\n );\n }\n\n /**\n * @param {number} pixelRatio Pixel ratio.\n * @private\n */\n replaceColor_(pixelRatio) {\n if (\n !this.color_ ||\n this.canvas_[pixelRatio] ||\n this.imageState_ !== ImageState.LOADED\n ) {\n return;\n }\n\n const image = this.image_;\n const canvas = document.createElement('canvas');\n canvas.width = Math.ceil(image.width * pixelRatio);\n canvas.height = Math.ceil(image.height * pixelRatio);\n\n const ctx = canvas.getContext('2d');\n ctx.scale(pixelRatio, pixelRatio);\n ctx.drawImage(image, 0, 0);\n\n ctx.globalCompositeOperation = 'multiply';\n ctx.fillStyle = asString(this.color_);\n ctx.fillRect(0, 0, canvas.width / pixelRatio, canvas.height / pixelRatio);\n\n ctx.globalCompositeOperation = 'destination-in';\n ctx.drawImage(image, 0, 0);\n\n this.canvas_[pixelRatio] = canvas;\n }\n\n /**\n * Discards event handlers which listen for load completion or errors.\n *\n * @private\n */\n unlistenImage_() {\n if (this.unlisten_) {\n this.unlisten_();\n this.unlisten_ = null;\n }\n }\n}\n\n/**\n * @param {HTMLImageElement|HTMLCanvasElement} image Image.\n * @param {string} src Src.\n * @param {import(\"../size.js\").Size} size Size.\n * @param {?string} crossOrigin Cross origin.\n * @param {import(\"../ImageState.js\").default} imageState Image state.\n * @param {import(\"../color.js\").Color} color Color.\n * @return {IconImage} Icon image.\n */\nexport function get(image, src, size, crossOrigin, imageState, color) {\n let iconImage = iconImageCache.get(src, crossOrigin, color);\n if (!iconImage) {\n iconImage = new IconImage(image, src, size, crossOrigin, imageState, color);\n iconImageCache.set(src, crossOrigin, color, iconImage);\n }\n return iconImage;\n}\n\nexport default IconImage;\n","/**\n * @module ol/style/Icon\n */\nimport EventType from '../events/EventType.js';\nimport ImageState from '../ImageState.js';\nimport ImageStyle from './Image.js';\nimport {asArray} from '../color.js';\nimport {assert} from '../asserts.js';\nimport {get as getIconImage} from './IconImage.js';\nimport {getUid} from '../util.js';\n\n/**\n * @typedef {'fraction' | 'pixels'} IconAnchorUnits\n * Anchor unit can be either a fraction of the icon size or in pixels.\n */\n\n/**\n * @typedef {'bottom-left' | 'bottom-right' | 'top-left' | 'top-right'} IconOrigin\n * Icon origin. One of 'bottom-left', 'bottom-right', 'top-left', 'top-right'.\n */\n\n/**\n * @typedef {Object} Options\n * @property {Array} [anchor=[0.5, 0.5]] Anchor. Default value is the icon center.\n * @property {IconOrigin} [anchorOrigin='top-left'] Origin of the anchor: `bottom-left`, `bottom-right`,\n * `top-left` or `top-right`.\n * @property {IconAnchorUnits} [anchorXUnits='fraction'] Units in which the anchor x value is\n * specified. A value of `'fraction'` indicates the x value is a fraction of the icon. A value of `'pixels'` indicates\n * the x value in pixels.\n * @property {IconAnchorUnits} [anchorYUnits='fraction'] Units in which the anchor y value is\n * specified. A value of `'fraction'` indicates the y value is a fraction of the icon. A value of `'pixels'` indicates\n * the y value in pixels.\n * @property {import(\"../color.js\").Color|string} [color] Color to tint the icon. If not specified,\n * the icon will be left as is.\n * @property {null|string} [crossOrigin] The `crossOrigin` attribute for loaded images. Note that you must provide a\n * `crossOrigin` value if you want to access pixel data with the Canvas renderer.\n * See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.\n * @property {HTMLImageElement|HTMLCanvasElement} [img] Image object for the icon. If the `src` option is not provided then the\n * provided image must already be loaded. And in that case, it is required\n * to provide the size of the image, with the `imgSize` option.\n * @property {import(\"../size.js\").Size} [imgSize] Image size in pixels. Only required if `img` is set and `src` is not.\n * The provided `imgSize` needs to match the actual size of the image.\n * @property {Array} [displacement=[0, 0]] Displacement of the icon in pixels.\n * Positive values will shift the icon right and up.\n * @property {number} [opacity=1] Opacity of the icon.\n * @property {number} [width] The width of the icon in pixels. This can't be used together with `scale`.\n * @property {number} [height] The height of the icon in pixels. This can't be used together with `scale`.\n * @property {number|import(\"../size.js\").Size} [scale=1] Scale.\n * @property {boolean} [rotateWithView=false] Whether to rotate the icon with the view.\n * @property {number} [rotation=0] Rotation in radians (positive rotation clockwise).\n * @property {Array} [offset=[0, 0]] Offset which, together with `size` and `offsetOrigin`, defines the\n * sub-rectangle to use from the original (sprite) image.\n * @property {IconOrigin} [offsetOrigin='top-left'] Origin of the offset: `bottom-left`, `bottom-right`,\n * `top-left` or `top-right`.\n * @property {import(\"../size.js\").Size} [size] Icon size in pixels. Used together with `offset` to define the\n * sub-rectangle to use from the original (sprite) image.\n * @property {string} [src] Image source URI.\n * @property {\"declutter\"|\"obstacle\"|\"none\"|undefined} [declutterMode] Declutter mode.\n */\n\n/**\n * @param {number} width The width.\n * @param {number} height The height.\n * @param {number|undefined} wantedWidth The wanted width.\n * @param {number|undefined} wantedHeight The wanted height.\n * @return {number|Array} The scale.\n */\nfunction calculateScale(width, height, wantedWidth, wantedHeight) {\n if (wantedWidth !== undefined && wantedHeight !== undefined) {\n return [wantedWidth / width, wantedHeight / height];\n }\n if (wantedWidth !== undefined) {\n return wantedWidth / width;\n }\n if (wantedHeight !== undefined) {\n return wantedHeight / height;\n }\n return 1;\n}\n\n/**\n * @classdesc\n * Set icon style for vector features.\n * @api\n */\nclass Icon extends ImageStyle {\n /**\n * @param {Options} [options] Options.\n */\n constructor(options) {\n options = options || {};\n\n /**\n * @type {number}\n */\n const opacity = options.opacity !== undefined ? options.opacity : 1;\n\n /**\n * @type {number}\n */\n const rotation = options.rotation !== undefined ? options.rotation : 0;\n\n /**\n * @type {number|import(\"../size.js\").Size}\n */\n const scale = options.scale !== undefined ? options.scale : 1;\n\n /**\n * @type {boolean}\n */\n const rotateWithView =\n options.rotateWithView !== undefined ? options.rotateWithView : false;\n\n super({\n opacity: opacity,\n rotation: rotation,\n scale: scale,\n displacement:\n options.displacement !== undefined ? options.displacement : [0, 0],\n rotateWithView: rotateWithView,\n declutterMode: options.declutterMode,\n });\n\n /**\n * @private\n * @type {Array}\n */\n this.anchor_ = options.anchor !== undefined ? options.anchor : [0.5, 0.5];\n\n /**\n * @private\n * @type {Array}\n */\n this.normalizedAnchor_ = null;\n\n /**\n * @private\n * @type {IconOrigin}\n */\n this.anchorOrigin_ =\n options.anchorOrigin !== undefined ? options.anchorOrigin : 'top-left';\n\n /**\n * @private\n * @type {IconAnchorUnits}\n */\n this.anchorXUnits_ =\n options.anchorXUnits !== undefined ? options.anchorXUnits : 'fraction';\n\n /**\n * @private\n * @type {IconAnchorUnits}\n */\n this.anchorYUnits_ =\n options.anchorYUnits !== undefined ? options.anchorYUnits : 'fraction';\n\n /**\n * @private\n * @type {?string}\n */\n this.crossOrigin_ =\n options.crossOrigin !== undefined ? options.crossOrigin : null;\n\n /**\n * @type {HTMLImageElement|HTMLCanvasElement}\n */\n const image = options.img !== undefined ? options.img : null;\n\n /**\n * @private\n * @type {import(\"../size.js\").Size|undefined}\n */\n this.imgSize_ = options.imgSize;\n\n /**\n * @type {string|undefined}\n */\n let src = options.src;\n\n assert(!(src !== undefined && image), 4); // `image` and `src` cannot be provided at the same time\n assert(!image || (image && this.imgSize_), 5); // `imgSize` must be set when `image` is provided\n\n if ((src === undefined || src.length === 0) && image) {\n src = /** @type {HTMLImageElement} */ (image).src || getUid(image);\n }\n assert(src !== undefined && src.length > 0, 6); // A defined and non-empty `src` or `image` must be provided\n\n // `width` or `height` cannot be provided together with `scale`\n assert(\n !(\n (options.width !== undefined || options.height !== undefined) &&\n options.scale !== undefined\n ),\n 69\n );\n\n /**\n * @type {import(\"../ImageState.js\").default}\n */\n const imageState =\n options.src !== undefined ? ImageState.IDLE : ImageState.LOADED;\n\n /**\n * @private\n * @type {import(\"../color.js\").Color}\n */\n this.color_ = options.color !== undefined ? asArray(options.color) : null;\n\n /**\n * @private\n * @type {import(\"./IconImage.js\").default}\n */\n this.iconImage_ = getIconImage(\n image,\n /** @type {string} */ (src),\n this.imgSize_ !== undefined ? this.imgSize_ : null,\n this.crossOrigin_,\n imageState,\n this.color_\n );\n\n /**\n * @private\n * @type {Array}\n */\n this.offset_ = options.offset !== undefined ? options.offset : [0, 0];\n /**\n * @private\n * @type {IconOrigin}\n */\n this.offsetOrigin_ =\n options.offsetOrigin !== undefined ? options.offsetOrigin : 'top-left';\n\n /**\n * @private\n * @type {Array}\n */\n this.origin_ = null;\n\n /**\n * @private\n * @type {import(\"../size.js\").Size}\n */\n this.size_ = options.size !== undefined ? options.size : null;\n\n /**\n * Calculate the scale if width or height were given.\n */\n if (options.width !== undefined || options.height !== undefined) {\n let width, height;\n if (options.size) {\n [width, height] = options.size;\n } else {\n const image = this.getImage(1);\n if (\n image instanceof HTMLCanvasElement ||\n (image.src && image.complete)\n ) {\n width = image.width;\n height = image.height;\n } else {\n this.initialOptions_ = options;\n const onload = () => {\n this.unlistenImageChange(onload);\n if (!this.initialOptions_) {\n return;\n }\n const imageSize = this.iconImage_.getSize();\n this.setScale(\n calculateScale(\n imageSize[0],\n imageSize[1],\n options.width,\n options.height\n )\n );\n };\n this.listenImageChange(onload);\n return;\n }\n }\n if (width !== undefined) {\n this.setScale(\n calculateScale(width, height, options.width, options.height)\n );\n }\n }\n }\n\n /**\n * Clones the style. The underlying Image/HTMLCanvasElement is not cloned.\n * @return {Icon} The cloned style.\n * @api\n */\n clone() {\n let scale, width, height;\n if (this.initialOptions_) {\n width = this.initialOptions_.width;\n height = this.initialOptions_.height;\n } else {\n scale = this.getScale();\n scale = Array.isArray(scale) ? scale.slice() : scale;\n }\n const clone = new Icon({\n anchor: this.anchor_.slice(),\n anchorOrigin: this.anchorOrigin_,\n anchorXUnits: this.anchorXUnits_,\n anchorYUnits: this.anchorYUnits_,\n color:\n this.color_ && this.color_.slice\n ? this.color_.slice()\n : this.color_ || undefined,\n crossOrigin: this.crossOrigin_,\n imgSize: this.imgSize_,\n offset: this.offset_.slice(),\n offsetOrigin: this.offsetOrigin_,\n opacity: this.getOpacity(),\n rotateWithView: this.getRotateWithView(),\n rotation: this.getRotation(),\n scale,\n width,\n height,\n size: this.size_ !== null ? this.size_.slice() : undefined,\n src: this.getSrc(),\n displacement: this.getDisplacement().slice(),\n declutterMode: this.getDeclutterMode(),\n });\n return clone;\n }\n\n /**\n * Get the anchor point in pixels. The anchor determines the center point for the\n * symbolizer.\n * @return {Array} Anchor.\n * @api\n */\n getAnchor() {\n let anchor = this.normalizedAnchor_;\n if (!anchor) {\n anchor = this.anchor_;\n const size = this.getSize();\n if (\n this.anchorXUnits_ == 'fraction' ||\n this.anchorYUnits_ == 'fraction'\n ) {\n if (!size) {\n return null;\n }\n anchor = this.anchor_.slice();\n if (this.anchorXUnits_ == 'fraction') {\n anchor[0] *= size[0];\n }\n if (this.anchorYUnits_ == 'fraction') {\n anchor[1] *= size[1];\n }\n }\n\n if (this.anchorOrigin_ != 'top-left') {\n if (!size) {\n return null;\n }\n if (anchor === this.anchor_) {\n anchor = this.anchor_.slice();\n }\n if (\n this.anchorOrigin_ == 'top-right' ||\n this.anchorOrigin_ == 'bottom-right'\n ) {\n anchor[0] = -anchor[0] + size[0];\n }\n if (\n this.anchorOrigin_ == 'bottom-left' ||\n this.anchorOrigin_ == 'bottom-right'\n ) {\n anchor[1] = -anchor[1] + size[1];\n }\n }\n this.normalizedAnchor_ = anchor;\n }\n const displacement = this.getDisplacement();\n const scale = this.getScaleArray();\n // anchor is scaled by renderer but displacement should not be scaled\n // so divide by scale here\n return [\n anchor[0] - displacement[0] / scale[0],\n anchor[1] + displacement[1] / scale[1],\n ];\n }\n\n /**\n * Set the anchor point. The anchor determines the center point for the\n * symbolizer.\n *\n * @param {Array} anchor Anchor.\n * @api\n */\n setAnchor(anchor) {\n this.anchor_ = anchor;\n this.normalizedAnchor_ = null;\n }\n\n /**\n * Get the icon color.\n * @return {import(\"../color.js\").Color} Color.\n * @api\n */\n getColor() {\n return this.color_;\n }\n\n /**\n * Get the image icon.\n * @param {number} pixelRatio Pixel ratio.\n * @return {HTMLImageElement|HTMLCanvasElement} Image or Canvas element.\n * @api\n */\n getImage(pixelRatio) {\n return this.iconImage_.getImage(pixelRatio);\n }\n\n /**\n * Get the pixel ratio.\n * @param {number} pixelRatio Pixel ratio.\n * @return {number} The pixel ratio of the image.\n * @api\n */\n getPixelRatio(pixelRatio) {\n return this.iconImage_.getPixelRatio(pixelRatio);\n }\n\n /**\n * @return {import(\"../size.js\").Size} Image size.\n */\n getImageSize() {\n return this.iconImage_.getSize();\n }\n\n /**\n * @return {import(\"../ImageState.js\").default} Image state.\n */\n getImageState() {\n return this.iconImage_.getImageState();\n }\n\n /**\n * @return {HTMLImageElement|HTMLCanvasElement} Image element.\n */\n getHitDetectionImage() {\n return this.iconImage_.getHitDetectionImage();\n }\n\n /**\n * Get the origin of the symbolizer.\n * @return {Array} Origin.\n * @api\n */\n getOrigin() {\n if (this.origin_) {\n return this.origin_;\n }\n let offset = this.offset_;\n\n if (this.offsetOrigin_ != 'top-left') {\n const size = this.getSize();\n const iconImageSize = this.iconImage_.getSize();\n if (!size || !iconImageSize) {\n return null;\n }\n offset = offset.slice();\n if (\n this.offsetOrigin_ == 'top-right' ||\n this.offsetOrigin_ == 'bottom-right'\n ) {\n offset[0] = iconImageSize[0] - size[0] - offset[0];\n }\n if (\n this.offsetOrigin_ == 'bottom-left' ||\n this.offsetOrigin_ == 'bottom-right'\n ) {\n offset[1] = iconImageSize[1] - size[1] - offset[1];\n }\n }\n this.origin_ = offset;\n return this.origin_;\n }\n\n /**\n * Get the image URL.\n * @return {string|undefined} Image src.\n * @api\n */\n getSrc() {\n return this.iconImage_.getSrc();\n }\n\n /**\n * Get the size of the icon (in pixels).\n * @return {import(\"../size.js\").Size} Image size.\n * @api\n */\n getSize() {\n return !this.size_ ? this.iconImage_.getSize() : this.size_;\n }\n\n /**\n * Get the width of the icon (in pixels). Will return undefined when the icon image is not yet loaded.\n * @return {number} Icon width (in pixels).\n * @api\n */\n getWidth() {\n const scale = this.getScaleArray();\n if (this.size_) {\n return this.size_[0] * scale[0];\n }\n if (this.iconImage_.getImageState() == ImageState.LOADED) {\n return this.iconImage_.getSize()[0] * scale[0];\n }\n return undefined;\n }\n\n /**\n * Get the height of the icon (in pixels). Will return undefined when the icon image is not yet loaded.\n * @return {number} Icon height (in pixels).\n * @api\n */\n getHeight() {\n const scale = this.getScaleArray();\n if (this.size_) {\n return this.size_[1] * scale[1];\n }\n if (this.iconImage_.getImageState() == ImageState.LOADED) {\n return this.iconImage_.getSize()[1] * scale[1];\n }\n return undefined;\n }\n\n /**\n * Set the scale.\n *\n * @param {number|import(\"../size.js\").Size} scale Scale.\n * @api\n */\n setScale(scale) {\n delete this.initialOptions_;\n super.setScale(scale);\n }\n\n /**\n * @param {function(import(\"../events/Event.js\").default): void} listener Listener function.\n */\n listenImageChange(listener) {\n this.iconImage_.addEventListener(EventType.CHANGE, listener);\n }\n\n /**\n * Load not yet loaded URI.\n * When rendering a feature with an icon style, the vector renderer will\n * automatically call this method. However, you might want to call this\n * method yourself for preloading or other purposes.\n * @api\n */\n load() {\n this.iconImage_.load();\n }\n\n /**\n * @param {function(import(\"../events/Event.js\").default): void} listener Listener function.\n */\n unlistenImageChange(listener) {\n this.iconImage_.removeEventListener(EventType.CHANGE, listener);\n }\n}\n\nexport default Icon;\n","/**\n * @module ol/style/Stroke\n */\n\n/**\n * @typedef {Object} Options\n * @property {import(\"../color.js\").Color|import(\"../colorlike.js\").ColorLike} [color] A color, gradient or pattern.\n * See {@link module:ol/color~Color} and {@link module:ol/colorlike~ColorLike} for possible formats.\n * Default null; if null, the Canvas/renderer default black will be used.\n * @property {CanvasLineCap} [lineCap='round'] Line cap style: `butt`, `round`, or `square`.\n * @property {CanvasLineJoin} [lineJoin='round'] Line join style: `bevel`, `round`, or `miter`.\n * @property {Array} [lineDash] Line dash pattern. Default is `null` (no dash).\n * @property {number} [lineDashOffset=0] Line dash offset.\n * @property {number} [miterLimit=10] Miter limit.\n * @property {number} [width] Width.\n */\n\n/**\n * @classdesc\n * Set stroke style for vector features.\n * Note that the defaults given are the Canvas defaults, which will be used if\n * option is not defined. The `get` functions return whatever was entered in\n * the options; they will not return the default.\n * @api\n */\nclass Stroke {\n /**\n * @param {Options} [options] Options.\n */\n constructor(options) {\n options = options || {};\n\n /**\n * @private\n * @type {import(\"../color.js\").Color|import(\"../colorlike.js\").ColorLike}\n */\n this.color_ = options.color !== undefined ? options.color : null;\n\n /**\n * @private\n * @type {CanvasLineCap|undefined}\n */\n this.lineCap_ = options.lineCap;\n\n /**\n * @private\n * @type {Array|null}\n */\n this.lineDash_ = options.lineDash !== undefined ? options.lineDash : null;\n\n /**\n * @private\n * @type {number|undefined}\n */\n this.lineDashOffset_ = options.lineDashOffset;\n\n /**\n * @private\n * @type {CanvasLineJoin|undefined}\n */\n this.lineJoin_ = options.lineJoin;\n\n /**\n * @private\n * @type {number|undefined}\n */\n this.miterLimit_ = options.miterLimit;\n\n /**\n * @private\n * @type {number|undefined}\n */\n this.width_ = options.width;\n }\n\n /**\n * Clones the style.\n * @return {Stroke} The cloned style.\n * @api\n */\n clone() {\n const color = this.getColor();\n return new Stroke({\n color: Array.isArray(color) ? color.slice() : color || undefined,\n lineCap: this.getLineCap(),\n lineDash: this.getLineDash() ? this.getLineDash().slice() : undefined,\n lineDashOffset: this.getLineDashOffset(),\n lineJoin: this.getLineJoin(),\n miterLimit: this.getMiterLimit(),\n width: this.getWidth(),\n });\n }\n\n /**\n * Get the stroke color.\n * @return {import(\"../color.js\").Color|import(\"../colorlike.js\").ColorLike} Color.\n * @api\n */\n getColor() {\n return this.color_;\n }\n\n /**\n * Get the line cap type for the stroke.\n * @return {CanvasLineCap|undefined} Line cap.\n * @api\n */\n getLineCap() {\n return this.lineCap_;\n }\n\n /**\n * Get the line dash style for the stroke.\n * @return {Array|null} Line dash.\n * @api\n */\n getLineDash() {\n return this.lineDash_;\n }\n\n /**\n * Get the line dash offset for the stroke.\n * @return {number|undefined} Line dash offset.\n * @api\n */\n getLineDashOffset() {\n return this.lineDashOffset_;\n }\n\n /**\n * Get the line join type for the stroke.\n * @return {CanvasLineJoin|undefined} Line join.\n * @api\n */\n getLineJoin() {\n return this.lineJoin_;\n }\n\n /**\n * Get the miter limit for the stroke.\n * @return {number|undefined} Miter limit.\n * @api\n */\n getMiterLimit() {\n return this.miterLimit_;\n }\n\n /**\n * Get the stroke width.\n * @return {number|undefined} Width.\n * @api\n */\n getWidth() {\n return this.width_;\n }\n\n /**\n * Set the color.\n *\n * @param {import(\"../color.js\").Color|import(\"../colorlike.js\").ColorLike} color Color.\n * @api\n */\n setColor(color) {\n this.color_ = color;\n }\n\n /**\n * Set the line cap.\n *\n * @param {CanvasLineCap|undefined} lineCap Line cap.\n * @api\n */\n setLineCap(lineCap) {\n this.lineCap_ = lineCap;\n }\n\n /**\n * Set the line dash.\n *\n * @param {Array|null} lineDash Line dash.\n * @api\n */\n setLineDash(lineDash) {\n this.lineDash_ = lineDash;\n }\n\n /**\n * Set the line dash offset.\n *\n * @param {number|undefined} lineDashOffset Line dash offset.\n * @api\n */\n setLineDashOffset(lineDashOffset) {\n this.lineDashOffset_ = lineDashOffset;\n }\n\n /**\n * Set the line join.\n *\n * @param {CanvasLineJoin|undefined} lineJoin Line join.\n * @api\n */\n setLineJoin(lineJoin) {\n this.lineJoin_ = lineJoin;\n }\n\n /**\n * Set the miter limit.\n *\n * @param {number|undefined} miterLimit Miter limit.\n * @api\n */\n setMiterLimit(miterLimit) {\n this.miterLimit_ = miterLimit;\n }\n\n /**\n * Set the width.\n *\n * @param {number|undefined} width Width.\n * @api\n */\n setWidth(width) {\n this.width_ = width;\n }\n}\n\nexport default Stroke;\n","/**\n * @module ol/style/Style\n */\n\nimport CircleStyle from './Circle.js';\nimport Fill from './Fill.js';\nimport Stroke from './Stroke.js';\nimport {assert} from '../asserts.js';\n\n/**\n * A function that takes an {@link module:ol/Feature~Feature} and a `{number}`\n * representing the view's resolution. The function should return a\n * {@link module:ol/style/Style~Style} or an array of them. This way e.g. a\n * vector layer can be styled. If the function returns `undefined`, the\n * feature will not be rendered.\n *\n * @typedef {function(import(\"../Feature.js\").FeatureLike, number):(Style|Array